public class test jorphan utils extends test case public test jorphan utils super testjorphanutils testcase testjorphanutils public test jorphan utils string arg0 super arg0 testjorphanutils public void test replace1 assert equals xyzdef j orphan utils replace first abcdef abc xyz testreplace1 assertequals jorphanutils replacefirst public void test replace2 assert equals axyzdef j orphan utils replace first abcdef bc xyz testreplace2 assertequals jorphanutils replacefirst public void test replace3 assert equals abcxyz j orphan utils replace first abcdef def xyz testreplace3 assertequals jorphanutils replacefirst public void test replace4 assert equals abcdef j orphan utils replace first abcdef bce xyz testreplace4 assertequals jorphanutils replacefirst public void test replace5 assert equals abcdef j orphan utils replace first abcdef alt testreplace5 assertequals jorphanutils replacefirst public void test replace6 assert equals abcdef j orphan utils replace first abcdef alt testreplace6 assertequals jorphanutils replacefirst public void test replace7 assert equals alt j orphan utils replace first alt alt testreplace7 assertequals jorphanutils replacefirst public void test replace8 assert equals img src xyz j orphan utils replace first img src xyz alt alt testreplace8 assertequals jorphanutils replacefirst tests for split string string boolean public void test split1 string in a bc test ignore trailing split characters string out j orphan utils split in true ignore adjacent delimiters assert equals 2 out length assert equals a out 0 assert equals bc out 1 out j orphan utils split in false assert equals should detect the trailing split chars 4 out length assert equals a out 0 assert equals bc out 1 assert equals out 2 assert equals out 3 testsplit1 jorphanutils assertequals assertequals assertequals jorphanutils assertequals assertequals assertequals assertequals assertequals public void test split2 string in a bc test leading split characters string out j orphan utils split in true assert equals 2 out length assert equals a out 0 assert equals bc out 1 out j orphan utils split in false assert equals should detect the leading split chars 4 out length assert equals out 0 assert equals out 1 assert equals a out 2 assert equals bc out 3 testsplit2 jorphanutils assertequals assertequals assertequals jorphanutils assertequals assertequals assertequals assertequals assertequals public void test split3 string in a bc test ignore trailing split characters string out j orphan utils split in true ignore adjacent delimiters assert equals 2 out length assert equals a out 0 assert equals bc out 1 out j orphan utils split in false assert equals should detect the trailing split chars 4 out length assert equals a out 0 assert equals bc out 1 assert equals out 2 assert equals out 3 testsplit3 jorphanutils assertequals assertequals assertequals jorphanutils assertequals assertequals assertequals assertequals assertequals public void test split4 string in a bc test leading split characters string out j orphan utils split in true assert equals 2 out length assert equals a out 0 assert equals bc out 1 out j orphan utils split in false assert equals should detect the leading split chars 4 out length assert equals out 0 assert equals out 1 assert equals a out 2 assert equals bc out 3 testsplit4 jorphanutils assertequals assertequals assertequals jorphanutils assertequals assertequals assertequals assertequals assertequals public void test truncate throws exception string in a b d e f string out j orphan utils split in true assert equals 5 out length assert equals a out 0 assert equals b out 1 assert equals d out 2 assert equals e out 3 assert equals f out 4 out j orphan utils split in false assert equals 8 out length assert equals a out 0 assert equals b out 1 assert equals out 2 assert equals out 3 assert equals d out 4 assert equals e out 5 assert equals out 6 assert equals f out 7 testtruncate jorphanutils assertequals assertequals assertequals assertequals assertequals assertequals jorphanutils assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals public void test split5 throws exception string in a b d e f string out j orphan utils split in true assert equals 5 out length assert equals a out 0 assert equals b out 1 assert equals d out 2 assert equals e out 3 assert equals f out 4 out j orphan utils split in false assert equals 8 out length assert equals a out 0 assert equals b out 1 assert equals out 2 assert equals out 3 assert equals d out 4 assert equals e out 5 assert equals out 6 assert equals f out 7 testsplit5 jorphanutils assertequals assertequals assertequals assertequals assertequals assertequals jorphanutils assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals empty string public void test empty string out j orphan utils split false assert equals 0 out length testempty jorphanutils assertequals tests for split string string string public void test splitsss1 string in a bc test non empty parameters string out j orphan utils split in assert equals 4 out length assert equals a out 0 assert equals bc out 1 assert equals out 2 assert equals out 3 testsplitsss1 jorphanutils assertequals assertequals assertequals assertequals assertequals public void test splitsss2 string in a bc empty default string out j orphan utils split in assert equals 4 out length assert equals a out 0 assert equals bc out 1 assert equals out 2 assert equals out 3 testsplitsss2 jorphanutils assertequals assertequals assertequals assertequals assertequals public void test splitsss3 string in a bc empty delimiter string out j orphan utils split in assert equals 1 out length assert equals in out 0 testsplitsss3 jorphanutils assertequals assertequals public void test splitsss4 string in a b c multiple delimiters string out out j orphan utils split in assert equals 5 out length assert equals a out 0 assert equals b out 1 assert equals c out 2 assert equals out 3 assert equals out 4 out j orphan utils split in assert equals 5 out length assert equals a out 0 assert equals b out 1 assert equals c out 2 assert equals out 3 assert equals out 4 testsplitsss4 jorphanutils assertequals assertequals assertequals assertequals assertequals assertequals jorphanutils assertequals assertequals assertequals assertequals assertequals assertequals public void test splitsss5 string in a bc delimiter same as splitter string out j orphan utils split in assert equals 4 out length assert equals a out 0 assert equals bc out 1 assert equals out 2 assert equals out 3 testsplitsss5 jorphanutils assertequals assertequals assertequals assertequals assertequals public void test splitsss nulls string in a bc string out try out j orphan utils split null assert equals 0 out length fail expecting null pointer exception catch null pointer exception ignored ignored try out j orphan utils split in null assert equals 0 out length fail expecting null pointer exception catch null pointer exception ignored ignored testsplitsssnulls jorphanutils assertequals nullpointerexception nullpointerexception jorphanutils assertequals nullpointerexception nullpointerexception public void test splitsss null string out out j orphan utils split a bc null assert equals 2 out length assert equals a out 0 assert equals bc out 1 out j orphan utils split a bc null assert equals 2 out length assert equals a out 0 assert equals bc out 1 testsplitsssnull jorphanutils assertequals assertequals assertequals jorphanutils assertequals assertequals assertequals public void test splitsss none string out out j orphan utils split x assert equals 0 out length out j orphan utils split a bc x assert equals 1 out length assert equals a bc out 0 testsplitsssnone jorphanutils assertequals jorphanutils assertequals assertequals public void testreplace all chars assert equals j orphan utils replace all chars string in out in source assert equals j orphan utils replace all chars in in out so rce assert equals j orphan utils replace all chars in u out in a b c out a b c assert equals j orphan utils replace all chars in out testreplaceallchars assertequals jorphanutils replaceallchars assertequals jorphanutils replaceallchars assertequals jorphanutils replaceallchars assertequals jorphanutils replaceallchars public void test trim assert equals j orphan utils trim assert equals j orphan utils trim assert equals j orphan utils trim assert equals j orphan utils trim assert equals j orphan utils trim assert equals abc j orphan utils trim abc testtrim assertequals jorphanutils assertequals jorphanutils assertequals jorphanutils assertequals jorphanutils assertequals jorphanutils assertequals jorphanutils public void testba to hex string assert equals j orphan utils ba to hex string new byte assert equals 00 j orphan utils ba to hex string new byte 0 assert equals 0f107f8081ff j orphan utils ba to hex string new byte 15 16 127 128 127 1 testbatohexstring assertequals jorphanutils batohexstring assertequals jorphanutils batohexstring assertequals jorphanutils batohexstring public test stat calculator super teststatcalculator param arg0 public test stat calculator string arg0 super arg0 teststatcalculator public void set up calc new stat calculator setup statcalculator public void test percentage point throws exception calc add value 10 calc add value 9 calc add value 5 calc add value 6 calc add value 1 calc add value 3 calc add value 8 calc add value 2 calc add value 7 calc add value 4 assert equals 10 calc get count assert equals 9 calc get percent point 0 8999999 int value testpercentagepoint addvalue addvalue addvalue addvalue addvalue addvalue addvalue addvalue addvalue addvalue assertequals getcount assertequals getpercentpoint intvalue public void test calculation calc add value 18 calc add value 10 calc add value 9 calc add value 11 calc add value 28 calc add value 3 calc add value 30 calc add value 15 calc add value 15 calc add value 21 assert equals 16 int calc get mean assert equals 8 0622577f float calc get standard deviation 0f assert equals 30 calc get max int value assert equals 3 calc get min int value assert equals 15 calc get median int value testcalculation addvalue addvalue addvalue addvalue addvalue addvalue addvalue addvalue addvalue addvalue assertequals getmean assertequals getstandarddeviation assertequals getmax intvalue assertequals getmin intvalue assertequals getmedian intvalue public class package test extends test case public package test string name super name packagetest testcase packagetest public void test add1 throws exception logger log logging manager get logger for class collection tree path arrays as list new string 1 2 3 4 hash tree tree new hash tree log debug tree path tree path tree add tree path value log debug now tree path tree path log debug tree to string assert equals 1 tree list tree path size assert equals value tree get array tree path 0 testadd1 loggingmanager getloggerforclass treepath aslist hashtree hashtree treepath treepath treepath treepath treepath tostring assertequals treepath assertequals getarray treepath public void test equals and hash code1 throws exception hash tree tree1 new hash tree abcd hash tree tree2 new hash tree abcd hash tree tree3 new hash tree abcde hash tree tree4 new hash tree abcde assert true tree1 equals tree1 assert true tree1 equals tree2 assert true tree2 equals tree1 assert true tree2 equals tree2 assert true tree1 hash code tree2 hash code assert true tree3 equals tree3 assert true tree3 equals tree4 assert true tree4 equals tree3 assert true tree4 equals tree4 assert true tree3 hash code tree4 hash code assert not same tree1 tree2 assert not same tree1 tree3 assert not same tree1 tree4 assert not same tree2 tree3 assert not same tree2 tree4 assert false tree1 equals tree3 assert false tree1 equals tree4 assert false tree2 equals tree3 assert false tree2 equals tree4 assert not null tree1 assert not null tree2 tree1 add abcd tree3 assert false tree1 equals tree2 assert false tree2 equals tree1 check reflexive if tree1 hash code tree2 hash code this is not a requirement system out println warn unequal hash trees should not have equal hash codes tree2 add abcd tree4 assert true tree1 equals tree2 assert true tree2 equals tree1 assert true tree1 hash code tree2 hash code testequalsandhashcode1 hashtree hashtree hashtree hashtree hashtree hashtree hashtree hashtree asserttrue asserttrue asserttrue asserttrue asserttrue hashcode hashcode asserttrue asserttrue asserttrue asserttrue asserttrue hashcode hashcode assertnotsame assertnotsame assertnotsame assertnotsame assertnotsame assertfalse assertfalse assertfalse assertfalse assertnotnull assertnotnull assertfalse assertfalse hashcode hashcode hashtrees hashcodes asserttrue asserttrue asserttrue hashcode hashcode public void test add object and tree throws exception listed hash tree tree new listed hash tree key listed hash tree new tree new listed hash tree value tree add key new tree assert equals tree list size 1 assert equals key tree get array 0 assert equals 1 tree get tree key list size assert equals 0 tree get tree key get tree value size assert equals tree get tree key get array 0 value assert not null tree get tree key get value testaddobjectandtree listedhashtree listedhashtree listedhashtree newtree listedhashtree newtree assertequals assertequals getarray assertequals gettree assertequals gettree gettree assertequals gettree getarray assertnotnull gettree public void test equals and hash code2 throws exception listed hash tree tree1 new listed hash tree abcd listed hash tree tree2 new listed hash tree abcd listed hash tree tree3 new listed hash tree abcde listed hash tree tree4 new listed hash tree abcde assert true tree1 equals tree1 assert true tree1 equals tree2 assert true tree2 equals tree1 assert true tree2 equals tree2 assert true tree1 hash code tree2 hash code assert true tree3 equals tree3 assert true tree3 equals tree4 assert true tree4 equals tree3 assert true tree4 equals tree4 assert true tree3 hash code tree4 hash code assert not same tree1 tree2 assert not same tree1 tree3 assert false tree1 equals tree3 assert false tree3 equals tree1 assert false tree1 equals tree4 assert false tree4 equals tree1 assert false tree2 equals tree3 assert false tree3 equals tree2 assert false tree2 equals tree4 assert false tree4 equals tree2 tree1 add abcd tree3 assert false tree1 equals tree2 assert false tree2 equals tree1 tree2 add abcd tree4 assert true tree1 equals tree2 assert true tree2 equals tree1 assert true tree1 hash code tree2 hash code tree1 add a1 tree1 add a2 tree1 add a3 tree2 add a2 tree2 add a1 assert false tree1 equals tree2 assert false tree2 equals tree1 if tree1 hash code tree2 hash code this is not a requirement system out println warn unequal listed hash trees should not have equal hashcodes tree4 add abcdef assert false tree3 equals tree4 assert false tree4 equals tree3 testequalsandhashcode2 listedhashtree listedhashtree listedhashtree listedhashtree listedhashtree listedhashtree listedhashtree listedhashtree asserttrue asserttrue asserttrue asserttrue asserttrue hashcode hashcode asserttrue asserttrue asserttrue asserttrue asserttrue hashcode hashcode assertnotsame assertnotsame assertfalse assertfalse assertfalse assertfalse assertfalse assertfalse assertfalse assertfalse assertfalse assertfalse asserttrue asserttrue asserttrue hashcode hashcode assertfalse assertfalse hashcode hashcode listedhashtrees assertfalse assertfalse public void test search throws exception listed hash tree tree new listed hash tree search by class searcher new search by class integer class string one one string two two integer o new integer 1 tree add one o tree get tree one add o two tree traverse searcher assert equals 1 searcher get search results size testsearch listedhashtree listedhashtree searchbyclass searchbyclass gettree assertequals getsearchresults public class package test extends test case public package test super packagetest testcase packagetest public package test string arg0 super arg0 packagetest public void test server throws exception bean shell server bshs new bean shell server 9876 assert not null bshs not sure we can test anything else here testserver beanshellserver beanshellserver assertnotnull public void test sub1 throws exception string input http jakarta apache org jmeter index html string pattern jakarta apache org string sub server assert equals http server jmeter index html string utilities substitute input pattern sub testsub1 assertequals stringutilities public void test sub2 throws exception string input arg1 param1 param1 string pattern param1 string sub value assert equals arg1 value value string utilities substitute input pattern sub testsub2 assertequals stringutilities public void test sub3 throws exception string input jakarta apache org string pattern jakarta apache org string sub server assert equals server string utilities substitute input pattern sub testsub3 assertequals stringutilities public void test sub4 throws exception string input a b c string pattern string sub assert equals a b c string utilities substitute input pattern sub testsub4 assertequals stringutilities public class testj meter utils extends test case public testj meter utils super testjmeterutils testcase testjmeterutils public testj meter utils string arg0 super arg0 testjmeterutils todo add some real tests now that split has been removed public void test1 throws exception public class testj meter context service extends test case public testj meter context service string name super name testjmetercontextservice testcase testjmetercontextservice public void test counts assert equals 0 j meter context service get number of threads assert equals 0 j meter context service get total threads incr number of threads assert equals 1 j meter context service get number of threads assert equals 0 j meter context service get total threads decr number of threads assert equals 0 j meter context service get total threads assert equals 0 j meter context service get number of threads j meter context service add total threads 27 j meter context service add total threads 27 assert equals 54 j meter context service get total threads assert equals 0 j meter context service get number of threads testcounts assertequals jmetercontextservice getnumberofthreads assertequals jmetercontextservice gettotalthreads incrnumberofthreads assertequals jmetercontextservice getnumberofthreads assertequals jmetercontextservice gettotalthreads decrnumberofthreads assertequals jmetercontextservice gettotalthreads assertequals jmetercontextservice getnumberofthreads jmetercontextservice addtotalthreads jmetercontextservice addtotalthreads assertequals jmetercontextservice gettotalthreads assertequals jmetercontextservice getnumberofthreads give access to the method for test code public static void incr number of threads j meter context service incr number of threads incrnumberofthreads jmetercontextservice incrnumberofthreads give access to the method for test code public static void decr number of threads j meter context service decr number of threads decrnumberofthreads jmetercontextservice decrnumberofthreads public class test test compiler extends junit framework test case public test test compiler string name super name testtestcompiler testcase testtestcompiler public void test config gathering throws exception listed hash tree testing new listed hash tree generic controller controller new generic controller config test element config1 new config test element config1 set name config1 config1 set property test property a test value test sampler sampler new test sampler sampler set name sampler testing add controller config1 testing add controller sampler test compiler initialize test compiler compiler new test compiler testing new j meter variables testing traverse compiler sampler test sampler compiler configure sampler sampler get sampler assert equals a test value sampler get property as string test property testconfiggathering listedhashtree listedhashtree genericcontroller genericcontroller configtestelement configtestelement setname setproperty testsampler testsampler setname testcompiler testcompiler testcompiler jmetervariables testsampler configuresampler getsampler assertequals getpropertyasstring class test sampler extends abstract sampler public sample result sample org apache jmeter samplers entry e return null testsampler abstractsampler sampleresult public object clone return new test sampler testsampler public class package test extends test case public package test string name super name packagetest testcase packagetest public void test string property throws exception string property prop new string property name value prop set running version true prop set object value new value assert equals new value prop get string value prop recover running version null assert equals value prop get string value prop set object value new value prop set object value 2nd value assert equals 2nd value prop get string value prop recover running version null assert equals value prop get string value teststringproperty stringproperty stringproperty setrunningversion setobjectvalue assertequals getstringvalue recoverrunningversion assertequals getstringvalue setobjectvalue setobjectvalue assertequals getstringvalue recoverrunningversion assertequals getstringvalue public void test element property throws exception login config config new login config config set username username config set password password test element property prop new test element property name config prop set running version true config new login config config set username user2 config set password pass2 prop set object value config assert equals user2 pass2 prop get string value prop recover running version null assert equals username password prop get string value config new login config config set username user2 config set password pass2 prop set object value config config new login config config set username user3 config set password pass3 prop set object value config assert equals user3 pass3 prop get string value prop recover running version null assert equals username password prop get string value testelementproperty loginconfig loginconfig setusername setpassword testelementproperty testelementproperty setrunningversion loginconfig setusername setpassword setobjectvalue assertequals getstringvalue recoverrunningversion assertequals getstringvalue loginconfig setusername setpassword setobjectvalue loginconfig setusername setpassword setobjectvalue assertequals getstringvalue recoverrunningversion assertequals getstringvalue private void check equals j meter property jp1 j meter property jp2 assert equals jp1 jp2 assert equals jp2 jp1 assert equals jp1 jp1 assert equals jp2 jp2 assert equals jp1 hash code jp2 hash code checkequals jmeterproperty jmeterproperty assertequals assertequals assertequals assertequals assertequals hashcode hashcode private void check not equals j meter property jp1 j meter property jp2 assert equals jp1 jp1 assert equals jp2 jp2 assert false jp1 equals jp2 assert false jp2 equals jp1 not an absolute requirement if jp1 hash code jp2 hash code system out println expected different hash codes for jp1 get class get name checknotequals jmeterproperty jmeterproperty assertequals assertequals assertfalse assertfalse hashcode hashcode hashcodes getclass getname public void test boolean equality throws exception boolean property jpn1 new boolean property boolean property jpn2 new boolean property boolean property jp1 new boolean property name1 true boolean property jp2 new boolean property name1 true boolean property jp3 new boolean property name2 true boolean property jp4 new boolean property name2 false check equals jpn1 jpn2 check not equals jpn1 jp1 check not equals jpn1 jp2 check equals jp1 jp2 check not equals jp1 jp3 check not equals jp2 jp3 check not equals jp3 jp4 testbooleanequality booleanproperty booleanproperty booleanproperty booleanproperty booleanproperty booleanproperty booleanproperty booleanproperty booleanproperty booleanproperty booleanproperty booleanproperty checkequals checknotequals checknotequals checkequals checknotequals checknotequals checknotequals public void test double equality throws exception double property jpn1 new double property double property jpn2 new double property double property jp1 new double property name1 123 4 double property jp2 new double property name1 123 4 double property jp3 new double property name2 123 4 double property jp4 new double property name2 123 4 double property jp5 new double property name2 double negative infinity double property jp6 new double property name2 double negative infinity double property jp7 new double property name2 double positive infinity double property jp8 new double property name2 double positive infinity double property jp9 new double property name2 double nan double property jp10 new double property name2 double nan double property jp11 new double property name1 double nan double property jp12 new double property name1 double min value double property jp13 new double property name2 double min value double property jp14 new double property name2 double min value double property jp15 new double property name1 double max value double property jp16 new double property name2 double max value double property jp17 new double property name2 double max value check equals jpn1 jpn2 check not equals jpn1 jp1 check not equals jpn1 jp2 check equals jp1 jp2 check not equals jp1 jp3 check not equals jp2 jp3 check not equals jp3 jp4 check equals jp5 jp6 check not equals jp3 jp6 check equals jp7 jp8 check not equals jp4 jp7 check not equals jp8 jp9 check equals jp9 jp10 check not equals jp10 jp11 check not equals jp5 jp10 check not equals jp12 jp14 check equals jp13 jp14 check not equals jp15 jp16 check equals jp16 jp17 testdoubleequality doubleproperty doubleproperty doubleproperty doubleproperty doubleproperty doubleproperty doubleproperty doubleproperty doubleproperty doubleproperty doubleproperty doubleproperty doubleproperty doubleproperty negative_infinity doubleproperty doubleproperty negative_infinity doubleproperty doubleproperty positive_infinity doubleproperty doubleproperty positive_infinity doubleproperty doubleproperty doubleproperty doubleproperty doubleproperty doubleproperty doubleproperty doubleproperty min_value doubleproperty doubleproperty min_value doubleproperty doubleproperty min_value doubleproperty doubleproperty max_value doubleproperty doubleproperty max_value doubleproperty doubleproperty max_value checkequals checknotequals checknotequals checkequals checknotequals checknotequals checknotequals checkequals checknotequals checkequals checknotequals checknotequals checkequals checknotequals checknotequals checknotequals checkequals checknotequals checkequals public void test float equality throws exception float property jp1 new float property name1 123 4f float property jp2 new float property name1 123 4f float property jp3 new float property name2 123 4f float property jp4 new float property name2 123 4f float property jp5 new float property name2 float negative infinity float property jp6 new float property name2 float negative infinity float property jp7 new float property name2 float positive infinity float property jp8 new float property name2 float positive infinity float property jp9 new float property name2 float nan float property jp10 new float property name2 float nan float property jp11 new float property name1 float nan float property jp12 new float property name1 float min value float property jp13 new float property name2 float min value float property jp14 new float property name2 float min value float property jp15 new float property name1 float max value float property jp16 new float property name2 float max value float property jp17 new float property name2 float max value check equals jp1 jp2 check not equals jp1 jp3 check not equals jp2 jp3 check not equals jp3 jp4 check equals jp5 jp6 check not equals jp3 jp6 check equals jp7 jp8 check not equals jp4 jp7 check not equals jp8 jp9 check equals jp9 jp10 check not equals jp10 jp11 check not equals jp5 jp10 check not equals jp12 jp14 check equals jp13 jp14 check not equals jp15 jp16 check equals jp16 jp17 testfloatequality floatproperty floatproperty floatproperty floatproperty floatproperty floatproperty floatproperty floatproperty floatproperty floatproperty negative_infinity floatproperty floatproperty negative_infinity floatproperty floatproperty positive_infinity floatproperty floatproperty positive_infinity floatproperty floatproperty floatproperty floatproperty floatproperty floatproperty floatproperty floatproperty min_value floatproperty floatproperty min_value floatproperty floatproperty min_value floatproperty floatproperty max_value floatproperty floatproperty max_value floatproperty floatproperty max_value checkequals checknotequals checknotequals checknotequals checkequals checknotequals checkequals checknotequals checknotequals checkequals checknotequals checknotequals checknotequals checkequals checknotequals checkequals public void test integer equality throws exception integer property jp1 new integer property name1 123 integer property jp2 new integer property name1 123 integer property jp3 new integer property name2 123 integer property jp4 new integer property name2 123 integer property jp5 new integer property name2 integer min value integer property jp6 new integer property name2 integer min value integer property jp7 new integer property name2 integer max value integer property jp8 new integer property name2 integer max value integer property jp9 new integer property name1 integer min value integer property jp10 new integer property name1 integer max value check equals jp1 jp2 check not equals jp1 jp3 check not equals jp2 jp3 check not equals jp3 jp4 check equals jp5 jp6 check not equals jp3 jp6 check equals jp7 jp8 check not equals jp4 jp7 check not equals jp9 jp5 check not equals jp10 jp7 check not equals jp9 jp10 try new integer property null fail should have generated an illegal argument exception catch illegal argument exception e try new integer property null 0 fail should have generated an illegal argument exception catch illegal argument exception e testintegerequality integerproperty integerproperty integerproperty integerproperty integerproperty integerproperty integerproperty integerproperty integerproperty integerproperty min_value integerproperty integerproperty min_value integerproperty integerproperty max_value integerproperty integerproperty max_value integerproperty integerproperty min_value integerproperty integerproperty max_value checkequals checknotequals checknotequals checknotequals checkequals checknotequals checkequals checknotequals checknotequals checknotequals checknotequals integerproperty illegalargumentexception integerproperty illegalargumentexception public void test long equality throws exception long property jp1 new long property name1 123 long property jp2 new long property name1 123 long property jp3 new long property name2 123 long property jp4 new long property name2 123 long property jp5 new long property name2 long min value long property jp6 new long property name2 long min value long property jp7 new long property name2 long max value long property jp8 new long property name2 long max value long property jp9 new long property name1 long min value long property jp10 new long property name1 long max value check equals jp1 jp2 check not equals jp1 jp3 check not equals jp2 jp3 check not equals jp3 jp4 check equals jp5 jp6 check not equals jp3 jp6 check equals jp7 jp8 check not equals jp4 jp7 check not equals jp9 jp5 check not equals jp10 jp7 check not equals jp9 jp10 try new long property null 0l fail should have generated an illegal argument exception catch illegal argument exception e testlongequality longproperty longproperty longproperty longproperty longproperty longproperty longproperty longproperty longproperty longproperty min_value longproperty longproperty min_value longproperty longproperty max_value longproperty longproperty max_value longproperty longproperty min_value longproperty longproperty max_value checkequals checknotequals checknotequals checknotequals checkequals checknotequals checkequals checknotequals checknotequals checknotequals checknotequals longproperty illegalargumentexception public void test map equality throws exception try new map property null null fail should have generated an illegal argument exception catch illegal argument exception e testmapequality mapproperty illegalargumentexception public void test null equality throws exception null property jpn1 new null property null property jpn2 new null property try new null property null fail should have generated an illegal argument exception catch illegal argument exception e null property jp1 new null property name1 null property jp2 new null property name1 null property jp3 new null property name2 null property jp4 new null property name2 check equals jpn1 jpn2 check not equals jpn1 jp1 check equals jp1 jp2 check not equals jp1 jp3 check not equals jp2 jp3 check equals jp3 jp4 testnullequality nullproperty nullproperty nullproperty nullproperty nullproperty illegalargumentexception nullproperty nullproperty nullproperty nullproperty nullproperty nullproperty nullproperty nullproperty checkequals checknotequals checkequals checknotequals checknotequals checkequals public void test string equality throws exception string property jpn1 new string property string property jpn2 new string property string property jp1 new string property name1 value1 string property jp2 new string property name1 value1 string property jp3 new string property name2 value1 string property jp4 new string property name2 value2 string property jp5 new string property name1 null string property jp6 new string property name1 null string property jp7 new string property name2 null check equals jpn1 jpn2 check not equals jpn1 jp1 check equals jp1 jp2 check not equals jp1 jp3 check not equals jp2 jp3 check not equals jp3 jp4 check equals jp5 jp6 check not equals jp3 jp5 check not equals jp6 jp7 try new string property null fail should have generated an illegal argument exception catch illegal argument exception e try new string property null null fail should have generated an illegal argument exception catch illegal argument exception e teststringequality stringproperty stringproperty stringproperty stringproperty stringproperty stringproperty stringproperty stringproperty stringproperty stringproperty stringproperty stringproperty stringproperty stringproperty stringproperty stringproperty stringproperty stringproperty checkequals checknotequals checkequals checknotequals checknotequals checknotequals checkequals checknotequals checknotequals stringproperty illegalargumentexception stringproperty illegalargumentexception public void test adding properties throws exception collection property coll new collection property coll add item joe coll add property new function property assert equals joe coll get 0 get string value assert equals org apache jmeter testelement property function property coll get 1 get class get name testaddingproperties collectionproperty collectionproperty additem addproperty functionproperty assertequals getstringvalue assertequals functionproperty getclass getname public class package test extends test case public package test string arg0 super arg0 packagetest testcase packagetest public void test recovery throws exception config test element config new config test element config add property new string property name config config set running version true login config login config new login config login config set username user1 login config set password pass1 assert true config get property login instanceof null property this test should work whether or not all nulls are equal assert equals new null property login config get property login config add property new test element property login login config assert equals login config to string config get property as string login config recover running version assert true config get property login instanceof null property assert equals new null property login config get property login testrecovery configtestelement configtestelement addproperty stringproperty setrunningversion loginconfig loginconfig loginconfig loginconfig setusername loginconfig setpassword asserttrue getproperty nullproperty assertequals nullproperty getproperty addproperty testelementproperty loginconfig assertequals loginconfig tostring getpropertyasstring recoverrunningversion asserttrue getproperty nullproperty assertequals nullproperty getproperty public void test arguments throws exception arguments args new arguments args add argument arg1 val1 test element property prop new test element property args args config test element te new config test element te add property prop te set running version true arguments config new arguments config add argument config1 config value test element property config prop new test element property args config config test element te2 new config test element te2 add property config prop te add test element te2 assert equals 2 args get argument count assert equals config1 config value args get argument 1 to string te recover running version te add test element te2 assert equals 2 args get argument count assert equals config1 config value args get argument 1 to string testarguments addargument testelementproperty testelementproperty configtestelement configtestelement addproperty setrunningversion addargument configvalue testelementproperty configprop testelementproperty configtestelement configtestelement addproperty configprop addtestelement assertequals getargumentcount assertequals configvalue getargument tostring recoverrunningversion addtestelement assertequals getargumentcount assertequals configvalue getargument tostring public class test combo string editor extends junit framework test case public test combo string editor string name super name testcombostringeditor testcase testcombostringeditor private void test set get combo string editor e object value throws exception e set value value assert equals value e get value testsetget combostringeditor setvalue assertequals getvalue private void test set get as text combo string editor e string text throws exception e set as text text assert equals text e get as text testsetgetastext combostringeditor setastext assertequals getastext public void test set get throws exception combo string editor e new combo string editor test set get e any string test set get e test set get e null test set get e var testsetget combostringeditor combostringeditor testsetget testsetget testsetget testsetget public void test set get as text throws exception combo string editor e new combo string editor test set get as text e any string test set get as text e test set get as text e null test set get as text e var check undefined does not become a reserved word e set as text combo string editor undefined to string assert not null e get as text testsetgetastext combostringeditor combostringeditor testsetgetastext testsetgetastext testsetgetastext testsetgetastext setastext combostringeditor tostring assertnotnull getastext public class test boolean property editor extends junit framework test case public test boolean property editor string name super name testbooleanpropertyeditor testcase testbooleanpropertyeditor public void test boolean editor property editor property editor property editor manager find editor boolean class assert not null property editor string tags property editor get tags assert equals 2 tags length assert equals true tags 0 assert equals false tags 1 property editor set value boolean false assert equals false property editor get as text property editor set as text false assert equals false property editor get as text property editor set as text false assert equals false property editor get as text property editor set value boolean true assert equals true property editor get as text property editor set as text true assert equals true property editor get as text property editor set as text true assert equals true property editor get as text testbooleaneditor propertyeditor propertyeditor propertyeditormanager findeditor assertnotnull propertyeditor propertyeditor gettags assertequals assertequals assertequals propertyeditor setvalue assertequals propertyeditor getastext propertyeditor setastext assertequals propertyeditor getastext propertyeditor setastext assertequals propertyeditor getastext propertyeditor setvalue assertequals propertyeditor getastext propertyeditor setastext assertequals propertyeditor getastext propertyeditor setastext assertequals propertyeditor getastext public class test field string editor extends junit framework test case public test field string editor string name super name testfieldstringeditor testcase testfieldstringeditor private void test set get combo string editor e object value throws exception e set value value assert equals value e get value testsetget combostringeditor setvalue assertequals getvalue private void test set get as text combo string editor e string text throws exception e set as text text assert equals text e get as text testsetgetastext combostringeditor setastext assertequals getastext public void test set get throws exception combo string editor e new combo string editor test set get e any string test set get e test set get e var testsetget combostringeditor combostringeditor testsetget testsetget testsetget public void test set get as text throws exception combo string editor e new combo string editor test set get as text e any string test set get as text e test set get as text e var testsetgetastext combostringeditor combostringeditor testsetgetastext testsetgetastext testsetgetastext public class test sample result extends test case public test sample result string name super name testsampleresult testcase testsampleresult public void test elapsed throws exception sample result res new sample result check sample increments ok res sample start thread sleep 110 needs to be greater than the minimum to allow for boundary errors res sample end long time res get time if time 100 fail sample time should be 100 actual time testelapsed sampleresult sampleresult samplestart sampleend gettime public void test pause throws exception sample result res new sample result check sample increments ok res sample start thread sleep 100 res sample pause thread sleep 200 re increment res sample resume thread sleep 100 res sample end long sample time res get time if sample time 198 sample time 290 fail accumulated time sample time was not between 198 and 290 ms testpause sampleresult sampleresult samplestart samplepause sampleresume sampleend sampletime gettime sampletime sampletime sampletime private void divert log n b this needs to divert the log for sample result wr new string writer 1000 log target lt new writer target wr fmt sample result log set log targets lt divertlog sampleresult stringwriter logtarget writertarget sampleresult setlogtargets public void test pause2 throws exception divert log sample result res new sample result res sample start res sample pause assert true wr to string length 0 res sample pause assert false wr to string length 0 testpause2 divertlog sampleresult sampleresult samplestart samplepause asserttrue tostring samplepause assertfalse tostring public void test byte count throws exception sample result res new sample result res sample start res set bytes 100 res set sample label sample of size 100 bytes res sample end assert equals 100 res get bytes assert equals sample of size 100 bytes res get sample label testbytecount sampleresult sampleresult samplestart setbytes setsamplelabel sampleend assertequals getbytes assertequals getsamplelabel private static long sample clock return sample result current time in ms sampleclock sampleresult currenttimeinms public void test sub results throws exception this test tries to emulate a http sample with two subsamples representing images that are downloaded for the page representing the first sample sample that will get two sub results simulates a web page load sample result res with sub results new sample result long begin test sample clock res with sub results sample start thread sleep 100 res with sub results set bytes 300 res with sub results set sample label sample with two subresults res with sub results set successful true res with sub results sample end long sample with sub results time res with sub results get time sample with no sub results simulates an image download sample result res no sub results1 new sample result res no sub results1 sample start thread sleep 100 res no sub results1 set bytes 100 res no sub results1 set sample label sample with no subresults res no sub results1 set successful true res no sub results1 sample end long sample1 time res no sub results1 get time assert true res no sub results1 is successful assert equals 100 res no sub results1 get bytes assert equals sample with no subresults res no sub results1 get sample label assert equals 1 res no sub results1 get sample count assert equals 0 res no sub results1 get sub results length sample with no sub results simulates an image download sample result res no sub results2 new sample result res no sub results2 sample start thread sleep 100 res no sub results2 set bytes 200 res no sub results2 set sample label sample with no subresults res no sub results2 set successful true res no sub results2 sample end long sample2 time res no sub results2 get time long overall time sample clock begin test assert true res no sub results2 is successful assert equals 200 res no sub results2 get bytes assert equals sample with no subresults res no sub results2 get sample label assert equals 1 res no sub results2 get sample count assert equals 0 res no sub results2 get sub results length now add the subsamples to the sample res with sub results add sub result res no sub results1 res with sub results add sub result res no sub results2 assert true res with sub results is successful assert equals 600 res with sub results get bytes assert equals sample with two subresults res with sub results get sample label assert equals 1 res with sub results get sample count assert equals 2 res with sub results get sub results length long total time res with sub results get time check the sample times long allsamples time sample with sub results time sample1 time sample2 time if total time allsamples time fail total total time sum samples allsamples time if total time overall time fail total total time overall time overall time check that calculator gets the correct statistics from the sample calculator calculator new calculator calculator add sample res with sub results assert equals 600 calculator get total bytes assert equals 1 calculator get count assert equals 1d total time 1000d calculator get rate 0 0001d allow for some margin of error check that the throughput uses the time elapsed for the sub results assert false 1d sample with sub results time 1000d calculator get rate testsubresults sampleresult reswithsubresults sampleresult begintest sampleclock reswithsubresults samplestart reswithsubresults setbytes reswithsubresults setsamplelabel reswithsubresults setsuccessful reswithsubresults sampleend samplewithsubresultstime reswithsubresults gettime sampleresult resnosubresults1 sampleresult resnosubresults1 samplestart resnosubresults1 setbytes resnosubresults1 setsamplelabel resnosubresults1 setsuccessful resnosubresults1 sampleend sample1time resnosubresults1 gettime asserttrue resnosubresults1 issuccessful assertequals resnosubresults1 getbytes assertequals resnosubresults1 getsamplelabel assertequals resnosubresults1 getsamplecount assertequals resnosubresults1 getsubresults sampleresult resnosubresults2 sampleresult resnosubresults2 samplestart resnosubresults2 setbytes resnosubresults2 setsamplelabel resnosubresults2 setsuccessful resnosubresults2 sampleend sample2time resnosubresults2 gettime overalltime sampleclock begintest asserttrue resnosubresults2 issuccessful assertequals resnosubresults2 getbytes assertequals resnosubresults2 getsamplelabel assertequals resnosubresults2 getsamplecount assertequals resnosubresults2 getsubresults reswithsubresults addsubresult resnosubresults1 reswithsubresults addsubresult resnosubresults2 asserttrue reswithsubresults issuccessful assertequals reswithsubresults getbytes assertequals reswithsubresults getsamplelabel assertequals reswithsubresults getsamplecount assertequals reswithsubresults getsubresults totaltime reswithsubresults gettime allsamplestime samplewithsubresultstime sample1time sample2time totaltime allsamplestime totaltime allsamplestime totaltime overalltime totaltime overalltime addsample reswithsubresults assertequals gettotalbytes assertequals getcount assertequals totaltime getrate assertfalse samplewithsubresultstime getrate public void test encoding and type throws exception check default sample result res new sample result assert equals sample result default encoding res get data encoding assert equals sample result default encoding res get data encoding with default assert equals data type should be blank res get data type assert null res get data encoding no default check null changes nothing res set encoding and type null assert equals sample result default encoding res get data encoding assert equals sample result default encoding res get data encoding with default assert equals data type should be blank res get data type assert null res get data encoding no default check no charset res set encoding and type text html assert equals sample result default encoding res get data encoding assert equals sample result default encoding res get data encoding with default assert equals text res get data type assert null res get data encoding no default check unquoted charset res set encoding and type text html charset a bcd assert equals a bcd res get data encoding with default assert equals a bcd res get data encoding no default assert equals a bcd res get data encoding assert equals text res get data type check quoted charset res set encoding and type text html charset ab cd assert equals ab cd res get data encoding with default assert equals ab cd res get data encoding no default assert equals ab cd res get data encoding assert equals text res get data type testencodingandtype sampleresult sampleresult assertequals sampleresult default_encoding getdataencoding assertequals sampleresult default_encoding getdataencodingwithdefault assertequals datatype getdatatype assertnull getdataencodingnodefault setencodingandtype assertequals sampleresult default_encoding getdataencoding assertequals sampleresult default_encoding getdataencodingwithdefault assertequals datatype getdatatype assertnull getdataencodingnodefault setencodingandtype assertequals sampleresult default_encoding getdataencoding assertequals sampleresult default_encoding getdataencodingwithdefault assertequals getdatatype assertnull getdataencodingnodefault setencodingandtype abcd assertequals abcd getdataencodingwithdefault assertequals abcd getdataencodingnodefault assertequals abcd getdataencoding assertequals getdatatype setencodingandtype abcd assertequals abcd getdataencodingwithdefault assertequals abcd getdataencodingnodefault assertequals abcd getdataencoding assertequals getdatatype read resource into resource bundle and store in list private property resource bundle getras string res throws exception input stream ras this get class get resource as stream res if ras null return null return new property resource bundle ras resourcebundle propertyresourcebundle inputstream getclass getresourceasstream propertyresourcebundle read resource file saving the keys private int readrf string res list l throws exception int fails 0 input stream ras this get class get resource as stream res if ras null if messages equals resource prefix lang length 0 throw new io exception cannot open resource file res else return 0 buffered reader file reader new buffered reader new input stream reader ras string s while s file reader read line null if s length 0 s starts with s starts with int equ s index of string key s substring 0 equ if resource prefix equals messages only relevant for messages j meter utils get res string converts space to and lowercases the key so make sure all keys pass the test if key index of 0 key to lower case java util locale english equals key system out println invalid key for j meter utils key fails string val s substring equ 1 l add key store the key now check for invalid message format if string contains 0 and there may be a problem so do a format with dummy parameters and check if there is a in the output a bit crude but should be enough for now if val index of 0 0 val index of 0 string m java text message format format val dummy params if m index of 0 fails system out println incorrect message format input output for key system out println val system out println m return fails inputstream getclass getresourceasstream resourceprefix ioexception bufferedreader filereader bufferedreader inputstreamreader filereader readline startswith startswith indexof resourceprefix jmeterutils getresstring _ indexof tolowercase jmeterutils indexof indexof messageformat dummy_params indexof helper method to construct resource name private string get res name string lang if lang length 0 return resource prefix properties else return resource prefix lang properties getresname resourceprefix resourceprefix _ private void check string resname throws exception check resname true check that there aren t any extra entries private void check string resname boolean check unexpected throws exception array list alf new array list 500 holds keys from file string res get res name resname sub test failures readrf res alf collections sort alf look for duplicate keys in the file string last for int i 0 i alf size i string curr string alf get i if curr equals last sub test failures system out println n duplicate key curr in res last curr if resname length 0 must be the default resource file defaultprb getras res if defaultprb null throw new io exception could not find required file res else if check unexpected check all the keys are in the default props file property resource bundle prb getras res if prb null return enumeration enumr prb get keys while enumr has more elements string key null try key string enumr next element defaultprb get string key check key is in default catch missing resource exception e sub test failures system out println resource prefix resname has unexpected key key if sub test failures 0 fail one or more subtests failed checkunexpected arraylist arraylist getresname subtestfailures subtestfailures nduplicate ioexception checkunexpected propertyresourcebundle getkeys hasmoreelements nextelement getstring missingresourceexception subtestfailures resourceprefix _ subtestfailures public static test suite test suite ts new test suite resources package test for int j 0 j prefix list length j string prefix prefix list j test suite pfx new test suite prefix pfx add test new package test test lang prefix load the default resource string lang j meter menu bar get languages for int i 0 i lang length i if en equals lang i don t try to check the default language pfx add test new package test test lang lang i prefix ts add test pfx return ts testsuite testsuite packagetest prefixlist prefixlist testsuite testsuite addtest packagetest testlang jmetermenubar getlanguages addtest packagetest testlang addtest private final string resource prefix e g messages public package test string test name string lang this test name lang messages resourceprefix packagetest testname _lang testname _lang public package test string test name string lang string prop name super test name lang lang sub test failures 0 resource prefix prop name packagetest testname _lang propname testname _lang subtestfailures resourceprefix propname public void test lang throws exception check lang testlang public void test hex string to byte array throws exception byte ba ba binarytcp client impl hex string to byte array assert equals 0 ba length ba binarytcp client impl hex string to byte array 00 assert equals 1 ba length assert equals 0 ba 0 ba binarytcp client impl hex string to byte array 0f107f8081ff assert equals 6 ba length assert equals 15 ba 0 assert equals 16 ba 1 assert equals 127 ba 2 assert equals 128 ba 3 assert equals 127 ba 4 assert equals 1 ba 5 try ba binarytcp client impl hex string to byte array 0f107f8081ff1 odd chars fail expected illegal argument exception catch illegal argument exception expected ignored try ba binarytcp client impl hex string to byte array 0f107xxf8081ff invalid fail expected illegal argument exception catch illegal argument exception expected ignored testhexstringtobytearray binarytcpclientimpl hexstringtobytearray assertequals binarytcpclientimpl hexstringtobytearray assertequals assertequals binarytcpclientimpl hexstringtobytearray assertequals assertequals assertequals assertequals assertequals assertequals assertequals binarytcpclientimpl hexstringtobytearray illegalargumentexception illegalargumentexception binarytcpclientimpl hexstringtobytearray illegalargumentexception illegalargumentexception public void test loop back throws exception assert equals 0f107f8081ff j orphan utils ba to hex string binarytcp client impl hex string to byte array 0f107f8081ff testloopback assertequals jorphanutils batohexstring binarytcpclientimpl hexstringtobytearray public void test round trip throws exception binarytcp client impl bi new binarytcp client impl input stream is null try bi write null is fail expected unsupported operation exception catch unsupported operation exception expected ignored byte array output stream os new byte array output stream bi write os 3132333435 12345 os close assert equals 12345 os to string byte array input stream bis new byte array input stream os to byte array assert equals 3132333435 bi read bis testroundtrip binarytcpclientimpl binarytcpclientimpl inputstream unsupportedoperationexception unsupportedoperationexception bytearrayoutputstream bytearrayoutputstream assertequals tostring bytearrayinputstream bytearrayinputstream tobytearray assertequals public void test int to byte array throws exception byte ba int len 2 ba tcp client decorator int to byte array 0 len assert equals len ba length assert equals 0 ba 0 assert equals 0 ba 1 ba tcp client decorator int to byte array 15 len assert equals len ba length assert equals 0 ba 0 assert equals 15 ba 1 ba tcp client decorator int to byte array 255 len assert equals len ba length assert equals 0 ba 0 assert equals 1 ba 1 ba tcp client decorator int to byte array 256 len assert equals len ba length assert equals 1 ba 0 assert equals 0 ba 1 ba tcp client decorator int to byte array 1 len assert equals len ba length assert equals 1 ba 0 assert equals 1 ba 1 ba tcp client decorator int to byte array short max value len assert equals len ba length assert equals 127 ba 0 assert equals 1 ba 1 ba tcp client decorator int to byte array short min value len assert equals len ba length assert equals 128 ba 0 assert equals 0 ba 1 try ba tcp client decorator int to byte array short min value 1 len fail catch illegal argument exception iae try ba tcp client decorator int to byte array short max value 1 len fail catch illegal argument exception iae len 4 ba tcp client decorator int to byte array 0 len assert equals len ba length assert equals 0 ba 0 assert equals 0 ba 1 assert equals 0 ba 2 assert equals 0 ba 3 ba tcp client decorator int to byte array 15 len assert equals len ba length assert equals 0 ba 0 assert equals 0 ba 1 assert equals 0 ba 2 assert equals 15 ba 3 ba tcp client decorator int to byte array 255 len assert equals len ba length assert equals 0 ba 0 assert equals 0 ba 1 assert equals 0 ba 2 assert equals 1 ba 3 ba tcp client decorator int to byte array 1 len assert equals len ba length assert equals 1 ba 0 assert equals 1 ba 1 assert equals 1 ba 2 assert equals 1 ba 3 ba tcp client decorator int to byte array 256 len assert equals len ba length assert equals 0 ba 0 assert equals 0 ba 1 assert equals 1 ba 2 assert equals 0 ba 3 ba tcp client decorator int to byte array 65535 len assert equals len ba length assert equals 0 ba 0 assert equals 0 ba 1 assert equals 1 ba 2 assert equals 1 ba 3 ba tcp client decorator int to byte array 65536 len assert equals len ba length assert equals 0 ba 0 assert equals 1 ba 1 assert equals 0 ba 2 assert equals 0 ba 3 ba tcp client decorator int to byte array integer min value len assert equals len ba length assert equals 128 ba 0 assert equals 0 ba 1 assert equals 0 ba 2 assert equals 0 ba 3 ba tcp client decorator int to byte array integer max value len assert equals len ba length assert equals 127 ba 0 assert equals 1 ba 1 assert equals 1 ba 2 assert equals 1 ba 3 check illegal array lengths try ba tcp client decorator int to byte array 0 0 fail catch illegal argument exception iae try ba tcp client decorator int to byte array 0 1 fail catch illegal argument exception iae try ba tcp client decorator int to byte array 0 3 fail catch illegal argument exception iae try ba tcp client decorator int to byte array 0 5 fail catch illegal argument exception iae testinttobytearray tcpclientdecorator inttobytearray assertequals assertequals assertequals tcpclientdecorator inttobytearray assertequals assertequals assertequals tcpclientdecorator inttobytearray assertequals assertequals assertequals tcpclientdecorator inttobytearray assertequals assertequals assertequals tcpclientdecorator inttobytearray assertequals assertequals assertequals tcpclientdecorator inttobytearray max_value assertequals assertequals assertequals tcpclientdecorator inttobytearray min_value assertequals assertequals assertequals tcpclientdecorator inttobytearray min_value illegalargumentexception tcpclientdecorator inttobytearray max_value illegalargumentexception tcpclientdecorator inttobytearray assertequals assertequals assertequals assertequals assertequals tcpclientdecorator inttobytearray assertequals assertequals assertequals assertequals assertequals tcpclientdecorator inttobytearray assertequals assertequals assertequals assertequals assertequals tcpclientdecorator inttobytearray assertequals assertequals assertequals assertequals assertequals tcpclientdecorator inttobytearray assertequals assertequals assertequals assertequals assertequals tcpclientdecorator inttobytearray assertequals assertequals assertequals assertequals assertequals tcpclientdecorator inttobytearray assertequals assertequals assertequals assertequals assertequals tcpclientdecorator inttobytearray min_value assertequals assertequals assertequals assertequals assertequals tcpclientdecorator inttobytearray max_value assertequals assertequals assertequals assertequals assertequals tcpclientdecorator inttobytearray illegalargumentexception tcpclientdecorator inttobytearray illegalargumentexception tcpclientdecorator inttobytearray illegalargumentexception tcpclientdecorator inttobytearray illegalargumentexception public void test byte array to int throws exception byte ba ba new byte 0 0 assert equals 0 tcp client decorator byte array to int ba ba new byte 0 15 assert equals 15 tcp client decorator byte array to int ba ba new byte 0 1 assert equals 255 tcp client decorator byte array to int ba ba new byte 1 0 assert equals 256 tcp client decorator byte array to int ba ba new byte 1 1 assert equals 1 tcp client decorator byte array to int ba ba new byte 0 0 1 1 assert equals 65535 tcp client decorator byte array to int ba ba new byte 0 1 0 0 assert equals 65536 tcp client decorator byte array to int ba ba new byte 0 0 0 0 assert equals 0 tcp client decorator byte array to int ba ba new byte 128 0 0 0 assert equals integer min value tcp client decorator byte array to int ba ba new byte 127 1 1 1 assert equals integer max value tcp client decorator byte array to int ba test invalid byte arrays try tcp client decorator byte array to int null fail expected illegal argument exception catch illegal argument exception expected ignored try tcp client decorator byte array to int new byte fail expected illegal argument exception catch illegal argument exception expected ignored try tcp client decorator byte array to int new byte 0 fail expected illegal argument exception catch illegal argument exception expected ignored try tcp client decorator byte array to int new byte 0 0 0 fail expected illegal argument exception catch illegal argument exception expected ignored try tcp client decorator byte array to int new byte 0 0 0 fail expected illegal argument exception catch illegal argument exception expected ignored testbytearraytoint assertequals tcpclientdecorator bytearraytoint assertequals tcpclientdecorator bytearraytoint assertequals tcpclientdecorator bytearraytoint assertequals tcpclientdecorator bytearraytoint assertequals tcpclientdecorator bytearraytoint assertequals tcpclientdecorator bytearraytoint assertequals tcpclientdecorator bytearraytoint assertequals tcpclientdecorator bytearraytoint assertequals min_value tcpclientdecorator bytearraytoint assertequals max_value tcpclientdecorator bytearraytoint tcpclientdecorator bytearraytoint illegalargumentexception illegalargumentexception tcpclientdecorator bytearraytoint illegalargumentexception illegalargumentexception tcpclientdecorator bytearraytoint illegalargumentexception illegalargumentexception tcpclientdecorator bytearraytoint illegalargumentexception illegalargumentexception tcpclientdecorator bytearraytoint illegalargumentexception illegalargumentexception public void test loop back throws exception assert equals short min value tcp client decorator byte array to int tcp client decorator int to byte array short min value 2 assert equals short max value tcp client decorator byte array to int tcp client decorator int to byte array short max value 2 assert equals integer min value tcp client decorator byte array to int tcp client decorator int to byte array integer min value 4 assert equals integer max value tcp client decorator byte array to int tcp client decorator int to byte array integer max value 4 testloopback assertequals min_value tcpclientdecorator bytearraytoint tcpclientdecorator inttobytearray min_value assertequals max_value tcpclientdecorator bytearraytoint tcpclientdecorator inttobytearray max_value assertequals min_value tcpclientdecorator bytearraytoint tcpclientdecorator inttobytearray min_value assertequals max_value tcpclientdecorator bytearraytoint tcpclientdecorator inttobytearray max_value public void test error throws exception byte array output stream os null byte array input stream is null length prefixed binarytcp client impl lp new length prefixed binarytcp client impl try lp write os is fail expected java lang unsupported operation exception catch java lang unsupported operation exception expected testerror bytearrayoutputstream bytearrayinputstream lengthprefixedbinarytcpclientimpl lengthprefixedbinarytcpclientimpl unsupportedoperationexception unsupportedoperationexception public void test valid throws exception byte array output stream os new byte array output stream length prefixed binarytcp client impl lp new length prefixed binarytcp client impl final string data 31323334353637 lp write os data os close final byte byte array os to byte array assert equals 2 data length 2 byte array length byte array input stream is new byte array input stream byte array assert equals data lp read is testvalid bytearrayoutputstream bytearrayoutputstream lengthprefixedbinarytcpclientimpl lengthprefixedbinarytcpclientimpl bytearray tobytearray assertequals bytearray bytearrayinputstream bytearrayinputstream bytearray assertequals public class package test extends test case create a new test param name the name of the test public package test string name super name packagetest testcase packagetest test that adding an argument to the table results in an appropriate test element being created throws exception if an exception occurred during the test public void testldap argument creation throws exception ldap arguments panel gui new ldap arguments panel gui table model add row new ldap argument gui table model set value at howdy 0 0 gui table model add row new ldap argument gui table model set value at doody 0 1 assert equals ldap argument ldap arguments gui create test element get arguments get 0 get object value get meta data testelement testldapargumentcreation ldapargumentspanel ldapargumentspanel tablemodel addrow ldapargument tablemodel setvalueat tablemodel addrow ldapargument tablemodel setvalueat assertequals ldapargument ldaparguments createtestelement getarguments getobjectvalue getmetadata public class testhttp file args extends test case public testhttp file args string name super name testhttpfileargs testcase testhttpfileargs public void test constructors throws exception http file args files new http file args assert equals 0 files gethttp file arg count testconstructors httpfileargs httpfileargs assertequals gethttpfileargcount public void test adding throws exception http file args files new http file args assert equals 0 files gethttp file arg count files addhttp file arg hede assert equals 1 files gethttp file arg count assert equals hede http file arg files iterator next get object value get path http file arg file new http file arg hodo files addhttp file arg file assert equals 2 files gethttp file arg count property iterator iter files iterator assert equals hede http file arg iter next get object value get path assert equals hodo http file arg iter next get object value get path files add emptyhttp file arg assert equals 3 files gethttp file arg count iter files iterator assert equals hede http file arg iter next get object value get path assert equals hodo http file arg iter next get object value get path assert equals http file arg iter next get object value get path testadding httpfileargs httpfileargs assertequals gethttpfileargcount addhttpfilearg assertequals gethttpfileargcount assertequals httpfilearg getobjectvalue getpath httpfilearg httpfilearg addhttpfilearg assertequals gethttpfileargcount propertyiterator assertequals httpfilearg getobjectvalue getpath assertequals httpfilearg getobjectvalue getpath addemptyhttpfilearg assertequals gethttpfileargcount assertequals httpfilearg getobjectvalue getpath assertequals httpfilearg getobjectvalue getpath assertequals httpfilearg getobjectvalue getpath public void test sethttp file args throws exception list newhttp file args new linked list newhttp file args add new http file arg hede http file args files new http file args files sethttp file args newhttp file args assert equals 1 files gethttp file arg count assert equals hede http file arg files iterator next get object value get path testsethttpfileargs newhttpfileargs linkedlist newhttpfileargs httpfilearg httpfileargs httpfileargs sethttpfileargs newhttpfileargs assertequals gethttpfileargcount assertequals httpfilearg getobjectvalue getpath public void test removing throws exception http file args files new http file args assert equals 0 files gethttp file arg count files addhttp file arg hede assert equals 1 files gethttp file arg count files clear assert equals 0 files gethttp file arg count files addhttp file arg file1 files addhttp file arg file2 files addhttp file arg file3 http file arg file new http file arg file4 files addhttp file arg file files addhttp file arg file5 files addhttp file arg file6 assert equals 6 files gethttp file arg count files removehttp file arg file3 assert equals 5 files gethttp file arg count property iterator iter files iterator assert equals file1 http file arg iter next get object value get path assert equals file2 http file arg iter next get object value get path assert equals file4 http file arg iter next get object value get path assert equals file5 http file arg iter next get object value get path assert equals file6 http file arg iter next get object value get path files removehttp file arg file assert equals 4 files gethttp file arg count iter files iterator assert equals file1 http file arg iter next get object value get path assert equals file2 http file arg iter next get object value get path assert equals file5 http file arg iter next get object value get path assert equals file6 http file arg iter next get object value get path files removehttp file arg new http file arg file5 assert equals 3 files gethttp file arg count iter files iterator assert equals file1 http file arg iter next get object value get path assert equals file2 http file arg iter next get object value get path assert equals file6 http file arg iter next get object value get path files removehttp file arg 1 assert equals 2 files gethttp file arg count iter files iterator assert equals file1 http file arg iter next get object value get path assert equals file6 http file arg iter next get object value get path files remove allhttp file args assert equals 0 files gethttp file arg count testremoving httpfileargs httpfileargs assertequals gethttpfileargcount addhttpfilearg assertequals gethttpfileargcount assertequals gethttpfileargcount addhttpfilearg addhttpfilearg addhttpfilearg httpfilearg httpfilearg addhttpfilearg addhttpfilearg addhttpfilearg assertequals gethttpfileargcount removehttpfilearg assertequals gethttpfileargcount propertyiterator assertequals httpfilearg getobjectvalue getpath assertequals httpfilearg getobjectvalue getpath assertequals httpfilearg getobjectvalue getpath assertequals httpfilearg getobjectvalue getpath assertequals httpfilearg getobjectvalue getpath removehttpfilearg assertequals gethttpfileargcount assertequals httpfilearg getobjectvalue getpath assertequals httpfilearg getobjectvalue getpath assertequals httpfilearg getobjectvalue getpath assertequals httpfilearg getobjectvalue getpath removehttpfilearg httpfilearg assertequals gethttpfileargcount assertequals httpfilearg getobjectvalue getpath assertequals httpfilearg getobjectvalue getpath assertequals httpfilearg getobjectvalue getpath removehttpfilearg assertequals gethttpfileargcount assertequals httpfilearg getobjectvalue getpath assertequals httpfilearg getobjectvalue getpath removeallhttpfileargs assertequals gethttpfileargcount public void test to string throws exception http file args files new http file args files addhttp file arg file1 files addhttp file arg file2 files addhttp file arg file3 assert equals file1 file2 file3 files to string testtostring httpfileargs httpfileargs addhttpfilearg addhttpfilearg addhttpfilearg assertequals tostring public class testhttp argument extends test case public testhttp argument string name super name testhttpargument testcase testhttpargument public void test cloning throws exception http argument arg new http argument name value here assert equals name arg get name assert equals value here arg get value assert equals name 3f arg get encoded name assert equals value here arg get encoded value http argument clone http argument arg clone assert equals name 3f clone get encoded name assert equals value here clone get encoded value assert equals name clone get name assert equals value here clone get value testcloning httpargument httpargument value_ assertequals getname assertequals value_ getvalue assertequals getencodedname assertequals value_ getencodedvalue httpargument httpargument assertequals getencodedname assertequals value_ getencodedvalue assertequals getname assertequals value_ getvalue public void test conversion throws exception arguments args new arguments args add argument name value here args add argument name of property value http argument convert arguments tohttp args collection property arg list args get arguments http argument http arg http argument arg list get 0 get object value assert equals name 3f http arg get encoded name assert equals value here http arg get encoded value http arg http argument arg list get 1 get object value assert equals name 24of property http arg get encoded name assert equals value 2b http arg get encoded value testconversion addargument value_ addargument value_ httpargument convertargumentstohttp collectionproperty arglist getarguments httpargument httparg httpargument arglist getobjectvalue assertequals httparg getencodedname assertequals value_ httparg getencodedvalue httparg httpargument arglist getobjectvalue assertequals httparg getencodedname assertequals value_ httparg getencodedvalue public void test encoding throws exception http argument arg arg new http argument name value here false assert equals name arg get name assert equals value here arg get value assert equals name 3f arg get encoded name assert equals value here arg get encoded value show that can bypass encoding arg set always encoded false assert equals name arg get encoded name assert equals value here arg get encoded value the sample does not use a valid encoding arg new http argument name value here true assert equals name arg get name assert equals value here arg get value assert equals name 3f arg get encoded name assert equals value here arg get encoded value arg set always encoded false by default name value are encoded on fetch assert equals name arg get encoded name assert equals value here arg get encoded value try a real encoded argument arg new http argument name 3f value here true assert equals name arg get name assert equals value here arg get value assert equals name 3f arg get encoded name assert equals value here arg get encoded value show that can bypass encoding arg set always encoded false assert equals name arg get encoded name assert equals value here arg get encoded value arg new http argument 00 01 07 false arg set always encoded false assert equals arg get encoded name assert equals 00 01 07 arg get encoded value testencoding httpargument httpargument value_ assertequals getname assertequals value_ getvalue assertequals getencodedname assertequals value_ getencodedvalue setalwaysencoded assertequals getencodedname assertequals value_ getencodedvalue httpargument value_ assertequals getname assertequals value_ getvalue assertequals getencodedname assertequals value_ getencodedvalue setalwaysencoded assertequals getencodedname assertequals value_ getencodedvalue httpargument value_ assertequals getname assertequals value_ getvalue assertequals getencodedname assertequals value_ getencodedvalue setalwaysencoded assertequals getencodedname assertequals value_ getencodedvalue httpargument setalwaysencoded assertequals getencodedname assertequals getencodedvalue public class testhttp file arg extends test case public testhttp file arg string name super name testhttpfilearg testcase testhttpfilearg public void test constructors throws exception http file arg file new http file arg assert equals no parameter failure file get path assert equals no parameter failure file get param name assert equals no parameter failure file get mime type file new http file arg path assert equals single parameter failure path file get path assert equals single parameter failure file get param name assert equals single parameter failure file get mime type file new http file arg path param mimetype assert equals three parameter failure path file get path assert equals three parameter failure param file get param name assert equals three parameter failure mimetype file get mime type http file arg file2 new http file arg file assert equals copy constructor failure path file2 get path assert equals copy constructor failure param file2 get param name assert equals copy constructor failure mimetype file2 get mime type testconstructors httpfilearg httpfilearg assertequals getpath assertequals getparamname assertequals getmimetype httpfilearg assertequals getpath assertequals getparamname assertequals getmimetype httpfilearg assertequals getpath assertequals getparamname assertequals getmimetype httpfilearg httpfilearg assertequals getpath assertequals getparamname assertequals getmimetype public void test getters setters throws exception http file arg file new http file arg assert equals file get path assert equals file get param name assert equals file get mime type file set path path file set param name param file set mime type mimetype file set header header assert equals path file get path assert equals param file get param name assert equals mimetype file get mime type assert equals header file get header testgetterssetters httpfilearg httpfilearg assertequals getpath assertequals getparamname assertequals getmimetype setpath setparamname setmimetype setheader assertequals getpath assertequals getparamname assertequals getmimetype assertequals getheader public void test to string throws exception http file arg file new http file arg path1 param1 mimetype1 assert equals path path1 param param1 mimetype mimetype1 file to string testtostring httpfilearg httpfilearg assertequals tostring public class testhttp utils extends test case public testhttp utils string name super name testhttputils testcase testhttputils public void testget encoding throws exception assert null conversion utils get encoding from content type xyx assert equals utf8 conversion utils get encoding from content type charset utf8 assert equals utf8 conversion utils get encoding from content type charset utf8 assert equals utf8 conversion utils get encoding from content type text plain charset utf8 assert equals utf8 conversion utils get encoding from content type text html charset utf8 charset def assert null conversion utils get encoding from content type charset assert null conversion utils get encoding from content type charset assert null conversion utils get encoding from content type charset no such charset testgetencoding assertnull conversionutils getencodingfromcontenttype assertequals conversionutils getencodingfromcontenttype assertequals conversionutils getencodingfromcontenttype assertequals conversionutils getencodingfromcontenttype assertequals conversionutils getencodingfromcontenttype assertnull conversionutils getencodingfromcontenttype assertnull conversionutils getencodingfromcontenttype assertnull conversionutils getencodingfromcontenttype public void test make relativeurl throws exception url base new url http host a b c assert equals new url http host a b d conversion utils make relativeurl base d assert equals new url http host a d conversion utils make relativeurl base d assert equals new url http host d conversion utils make relativeurl base d assert equals new url http host d conversion utils make relativeurl base d assert equals new url http host d conversion utils make relativeurl base d assert equals new url http host d conversion utils make relativeurl base d testmakerelativeurl assertequals conversionutils makerelativeurl assertequals conversionutils makerelativeurl assertequals conversionutils makerelativeurl assertequals conversionutils makerelativeurl assertequals conversionutils makerelativeurl assertequals conversionutils makerelativeurl public class package test extends test case public package test string arg0 super arg0 packagetest testcase packagetest public void test configuring throws exception http sampler base sampler http sampler base new http test sample gui create test element configure sampler testconfiguring httpsamplerbase httpsamplerbase httptestsamplegui createtestelement public void test configuring2 throws exception http sampler base sampler http sampler base new http test sample gui2 create test element configure sampler testconfiguring2 httpsamplerbase httpsamplerbase httptestsamplegui2 createtestelement private void configure http sampler base sampler throws exception sampler add argument arg1 val1 config test element config config test element new http defaults gui create test element arguments config get property http sampler base arguments get object value add argument new http argument config1 config value config set running version true sampler set running version true sampler set running version true sampler add test element config assert equals config1 config value sampler get arguments get argument 1 to string sampler recover running version config recover running version assert equals 1 sampler get arguments get argument count sampler add test element config assert equals config1 config value sampler get arguments get argument 1 to string httpsamplerbase addargument configtestelement configtestelement httpdefaultsgui createtestelement getproperty httpsamplerbase getobjectvalue addargument httpargument configvalue setrunningversion setrunningversion setrunningversion addtestelement assertequals configvalue getarguments getargument tostring recoverrunningversion recoverrunningversion assertequals getarguments getargumentcount addtestelement assertequals configvalue getarguments getargument tostring public class put writer test extends test case public put writer test string name super name putwritertest testcase putwritertest public void test set headers throws exception url connection uc new nullurl connection http sampler sampler new http sampler sampler sethttp files new http file arg new http file arg file1 mime1 put writer pw new put writer pw set headers uc sampler assert equals mime1 uc get request property http constants header content type uc new nullurl connection sampler sethttp files new http file arg new http file arg file2 param2 mime2 pw set headers uc sampler assert equals mime2 uc get request property http constants header content type testsetheaders urlconnection nullurlconnection httpsampler httpsampler sethttpfiles httpfilearg httpfilearg putwriter putwriter setheaders assertequals getrequestproperty httpconstants header_content_type nullurlconnection sethttpfiles httpfilearg httpfilearg setheaders assertequals getrequestproperty httpconstants header_content_type post writer post writer protected void set up throws exception establish connection sampler new http sampler this must be the original java http sampler post writer new post writer create the test file content test file content foo content 01234 56789 u007c u2aa1 u266a u0153 u20a1 u0115 u0364 u00c5 u2052 get bytes utf 8 create a temporary file to make sure we always have a file to give to the post writer whereever we are or whatever the current path is temporary file file create temp file foo txt output stream output new file output stream temporary file output write test file content output flush output close postwriter postwriter setup establishconnection httpsampler postwriter postwriter test_file_content getbytes utf_8 postwriter temporaryfile createtempfile outputstream fileoutputstream temporaryfile test_file_content protected void tear down throws exception delete temporay file temporary file delete teardown temporaryfile public void test send post data throws io exception sampler set method http sampler base post setup filepart sampler string title value mytitle string description value mydescription setup form data sampler title value description value test sending data with default encoding string content encoding sampler set content encoding content encoding post writer set headers connection sampler post writer send post data connection sampler check content type multipart connection post writer boundary byte expected form body create expected output post writer boundary null title value description value test file content check content length connection expected form body length check arrays have same content expected form body connection get output stream content connection disconnect test sending data as iso 8859 1 establish connection content encoding iso 8859 1 sampler set content encoding content encoding post writer set headers connection sampler post writer send post data connection sampler check content type multipart connection post writer boundary expected form body create expected output post writer boundary content encoding title value description value test file content check content length connection expected form body length check arrays have same content expected form body connection get output stream content connection disconnect test sending data as utf 8 establish connection title value mytitle u0153 u20a1 u0115 u00c5 description value mydescription u0153 u20a1 u0115 u00c5 content encoding utf 8 sampler set content encoding content encoding setup form data sampler title value description value post writer set headers connection sampler post writer send post data connection sampler check content type multipart connection post writer boundary expected form body create expected output post writer boundary content encoding title value description value test file content check content length connection expected form body length check arrays have same content expected form body connection get output stream content connection disconnect test sending utf 8 data with iso 8859 1 content encoding establish connection content encoding utf 8 sampler set content encoding iso 8859 1 post writer set headers connection sampler post writer send post data connection sampler check content type multipart connection post writer boundary expected form body create expected output post writer boundary content encoding title value description value test file content check content length connection expected form body length check arrays have different content expected form body connection get output stream content connection disconnect testsendpostdata ioexception setmethod httpsamplerbase setupfilepart titlevalue descriptionvalue setupformdata titlevalue descriptionvalue contentencoding setcontentencoding contentencoding postwriter setheaders postwriter sendpostdata checkcontenttypemultipart postwriter expectedformbody createexpectedoutput postwriter titlevalue descriptionvalue test_file_content checkcontentlength expectedformbody checkarrayshavesamecontent expectedformbody getoutputstreamcontent establishconnection contentencoding setcontentencoding contentencoding postwriter setheaders postwriter sendpostdata checkcontenttypemultipart postwriter expectedformbody createexpectedoutput postwriter contentencoding titlevalue descriptionvalue test_file_content checkcontentlength expectedformbody checkarrayshavesamecontent expectedformbody getoutputstreamcontent establishconnection titlevalue descriptionvalue contentencoding utf_8 setcontentencoding contentencoding setupformdata titlevalue descriptionvalue postwriter setheaders postwriter sendpostdata checkcontenttypemultipart postwriter expectedformbody createexpectedoutput postwriter contentencoding titlevalue descriptionvalue test_file_content checkcontentlength expectedformbody checkarrayshavesamecontent expectedformbody getoutputstreamcontent establishconnection contentencoding utf_8 setcontentencoding postwriter setheaders postwriter sendpostdata checkcontenttypemultipart postwriter expectedformbody createexpectedoutput postwriter contentencoding titlevalue descriptionvalue test_file_content checkcontentlength expectedformbody checkarrayshavedifferentcontent expectedformbody getoutputstreamcontent public void testsendpostdata nofilename throws io exception setup no filename sampler string title value mytitle string description value mydescription setup form data sampler title value description value test sending data with default encoding string content encoding sampler set content encoding content encoding post writer set headers connection sampler post writer send post data connection sampler check content type url encoded connection byte expected url title mytitle description mydescription get bytes check content length connection expected url length check arrays have same content expected url connection get output stream content expected url title mytitle description mydescription get bytes utf 8 check content length connection expected url length check arrays have same content expected url connection get output stream content connection disconnect test sending data as iso 8859 1 establish connection content encoding iso 8859 1 sampler set content encoding content encoding post writer set headers connection sampler post writer send post data connection sampler check content type url encoded connection expected url title mytitle description mydescription get bytes content encoding check content length connection expected url length check arrays have same content expected url connection get output stream content expected url title mytitle description mydescription get bytes utf 8 check content length connection expected url length check arrays have same content expected url connection get output stream content connection disconnect testsendpostdata_nofilename ioexception setupnofilename titlevalue descriptionvalue setupformdata titlevalue descriptionvalue contentencoding setcontentencoding contentencoding postwriter setheaders postwriter sendpostdata checkcontenttypeurlencoded expectedurl getbytes checkcontentlength expectedurl checkarrayshavesamecontent expectedurl getoutputstreamcontent expectedurl getbytes utf_8 checkcontentlength expectedurl checkarrayshavesamecontent expectedurl getoutputstreamcontent establishconnection contentencoding setcontentencoding contentencoding postwriter setheaders postwriter sendpostdata checkcontenttypeurlencoded expectedurl getbytes contentencoding checkcontentlength expectedurl checkarrayshavesamecontent expectedurl getoutputstreamcontent expectedurl getbytes utf_8 checkcontentlength expectedurl checkarrayshavesamecontent expectedurl getoutputstreamcontent public void testsendpostdata fileasbody throws io exception setup filepart sampler temporary file check using default encoding post writer set headers connection sampler post writer send post data connection sampler check content length connection test file content length check arrays have same content test file content connection get output stream content connection disconnect check using a different encoding string other encoding final string file encoding system get property file encoding non nls 1 log info file encoding file encoding if utf 8 equals ignore case file encoding utf8 equals ignore case file encoding non nls 1 other encoding iso 8859 1 non nls 1 else other encoding utf 8 log info using other encoding other encoding establish connection sampler set content encoding other encoding file content is sent as binary so the content encoding should not change the file data post writer set headers connection sampler post writer send post data connection sampler check content length connection test file content length check arrays have same content test file content connection get output stream content check that other encoding is not the current encoding check arrays have different content new string test file content get bytes other encoding connection get output stream content if we have both file as body and form data then only form data will be sent setup form data sampler establish connection sampler set content encoding post writer set headers connection sampler post writer send post data connection sampler check content type url encoded connection byte expected url title mytitle description mydescription get bytes check content length connection expected url length check arrays have same content expected url connection get output stream content testsendpostdata_fileasbody ioexception setupfilepart temporaryfile postwriter setheaders postwriter sendpostdata checkcontentlength test_file_content checkarrayshavesamecontent test_file_content getoutputstreamcontent otherencoding fileencoding getproperty fileencoding utf_8 equalsignorecase fileencoding equalsignorecase fileencoding otherencoding otherencoding utf_8 otherencoding establishconnection setcontentencoding otherencoding postwriter setheaders postwriter sendpostdata checkcontentlength test_file_content checkarrayshavesamecontent test_file_content getoutputstreamcontent checkarrayshavedifferentcontent test_file_content getbytes otherencoding getoutputstreamcontent setupformdata establishconnection setcontentencoding postwriter setheaders postwriter sendpostdata checkcontenttypeurlencoded expectedurl getbytes checkcontentlength expectedurl checkarrayshavesamecontent expectedurl getoutputstreamcontent public void testsendfiledata multipart throws io exception sampler set method http sampler base post string file field upload string mime type text plain file file temporary file byte file content test file content setup filepart sampler file field file mime type test sending data with default encoding string content encoding sampler set content encoding content encoding post writer set headers connection sampler post writer send post data connection sampler check content type multipart connection post writer boundary byte expected form body create expected filepart output post writer boundary file field file mime type file content true true check content length connection expected form body length check arrays have same content expected form body connection get output stream content connection disconnect test sending data as iso 8859 1 establish connection content encoding iso 8859 1 sampler set content encoding content encoding post writer set headers connection sampler post writer send post data connection sampler check content type multipart connection post writer boundary expected form body create expected filepart output post writer boundary file field file mime type file content true true check content length connection expected form body length check arrays have same content expected form body connection get output stream content connection disconnect test sending data as utf 8 establish connection file field some file field mime type image png content encoding utf 8 sampler set content encoding content encoding setup filepart sampler file field file mime type post writer set headers connection sampler post writer send post data connection sampler check content type multipart connection post writer boundary expected form body create expected filepart output post writer boundary file field file mime type file content true true check content length connection expected form body length check arrays have same content expected form body connection get output stream content connection disconnect testsendfiledata_multipart ioexception setmethod httpsamplerbase filefield mimetype temporaryfile filecontent test_file_content setupfilepart filefield mimetype contentencoding setcontentencoding contentencoding postwriter setheaders postwriter sendpostdata checkcontenttypemultipart postwriter expectedformbody createexpectedfilepartoutput postwriter filefield mimetype filecontent checkcontentlength expectedformbody checkarrayshavesamecontent expectedformbody getoutputstreamcontent establishconnection contentencoding setcontentencoding contentencoding postwriter setheaders postwriter sendpostdata checkcontenttypemultipart postwriter expectedformbody createexpectedfilepartoutput postwriter filefield mimetype filecontent checkcontentlength expectedformbody checkarrayshavesamecontent expectedformbody getoutputstreamcontent establishconnection filefield some_file_field mimetype contentencoding utf_8 setcontentencoding contentencoding setupfilepart filefield mimetype postwriter setheaders postwriter sendpostdata checkcontenttypemultipart postwriter expectedformbody createexpectedfilepartoutput postwriter filefield mimetype filecontent checkcontentlength expectedformbody checkarrayshavesamecontent expectedformbody getoutputstreamcontent public void testsendformdata multipart throws io exception sampler set method http sampler base post string title field title string title value mytitle string description field description string description value mydescription setup form data sampler title value description value tell sampler to do multipart even if we have no files to upload sampler set do multipart post true test sending data with default encoding string content encoding sampler set content encoding content encoding post writer set headers connection sampler post writer send post data connection sampler check content type multipart connection post writer boundary byte expected form body create expected formdata output post writer boundary null title field title value description field description value true true check content length connection expected form body length check arrays have same content expected form body connection get output stream content connection disconnect test sending data as iso 8859 1 establish connection content encoding iso 8859 1 sampler set content encoding content encoding post writer set headers connection sampler post writer send post data connection sampler check content type multipart connection post writer boundary expected form body create expected formdata output post writer boundary content encoding title field title value description field description value true true check content length connection expected form body length check arrays have same content expected form body connection get output stream content connection disconnect test sending data as iso 8859 1 with values that need to be urlencoded establish connection title value mytitle 123 456 yes description value mydescription and some spaces content encoding iso 8859 1 sampler set content encoding content encoding setup form data sampler title value description value post writer set headers connection sampler post writer send post data connection sampler check content type multipart connection post writer boundary expected form body create expected formdata output post writer boundary content encoding title field title value description field description value true true check content length connection expected form body length check arrays have same content expected form body connection get output stream content connection disconnect test sending data as utf 8 establish connection title value mytitle u0153 u20a1 u0115 u00c5 description value mydescription u0153 u20a1 u0115 u00c5 content encoding utf 8 sampler set content encoding content encoding setup form data sampler title value description value post writer set headers connection sampler post writer send post data connection sampler check content type multipart connection post writer boundary expected form body create expected formdata output post writer boundary content encoding title field title value description field description value true true check content length connection expected form body length check arrays have same content expected form body connection get output stream content connection disconnect test sending data as utf 8 with values that would have been urlencoded if it was not sent as multipart establish connection title value mytitle u0153 u20a1 u0115 yes u00c5 description value mydescription u0153 u20a1 u0115 u00c5 content encoding utf 8 sampler set content encoding content encoding setup form data sampler title value description value post writer set headers connection sampler post writer send post data connection sampler check content type multipart connection post writer boundary expected form body create expected formdata output post writer boundary content encoding title field title value description field description value true true check content length connection expected form body length check arrays have same content expected form body connection get output stream content connection disconnect testsendformdata_multipart ioexception setmethod httpsamplerbase titlefield titlevalue descriptionfield descriptionvalue setupformdata titlevalue descriptionvalue setdomultipartpost contentencoding setcontentencoding contentencoding postwriter setheaders postwriter sendpostdata checkcontenttypemultipart postwriter expectedformbody createexpectedformdataoutput postwriter titlefield titlevalue descriptionfield descriptionvalue checkcontentlength expectedformbody checkarrayshavesamecontent expectedformbody getoutputstreamcontent establishconnection contentencoding setcontentencoding contentencoding postwriter setheaders postwriter sendpostdata checkcontenttypemultipart postwriter expectedformbody createexpectedformdataoutput postwriter contentencoding titlefield titlevalue descriptionfield descriptionvalue checkcontentlength expectedformbody checkarrayshavesamecontent expectedformbody getoutputstreamcontent establishconnection titlevalue descriptionvalue contentencoding setcontentencoding contentencoding setupformdata titlevalue descriptionvalue postwriter setheaders postwriter sendpostdata checkcontenttypemultipart postwriter expectedformbody createexpectedformdataoutput postwriter contentencoding titlefield titlevalue descriptionfield descriptionvalue checkcontentlength expectedformbody checkarrayshavesamecontent expectedformbody getoutputstreamcontent establishconnection titlevalue descriptionvalue contentencoding utf_8 setcontentencoding contentencoding setupformdata titlevalue descriptionvalue postwriter setheaders postwriter sendpostdata checkcontenttypemultipart postwriter expectedformbody createexpectedformdataoutput postwriter contentencoding titlefield titlevalue descriptionfield descriptionvalue checkcontentlength expectedformbody checkarrayshavesamecontent expectedformbody getoutputstreamcontent establishconnection titlevalue descriptionvalue contentencoding utf_8 setcontentencoding contentencoding setupformdata titlevalue descriptionvalue postwriter setheaders postwriter sendpostdata checkcontenttypemultipart postwriter expectedformbody createexpectedformdataoutput postwriter contentencoding titlefield titlevalue descriptionfield descriptionvalue checkcontentlength expectedformbody checkarrayshavesamecontent expectedformbody getoutputstreamcontent public void testsendformdata urlencoded throws io exception string title value mytitle string description value mydescription setup form data sampler title value description value test sending data with default encoding string content encoding sampler set content encoding content encoding post writer set headers connection sampler post writer send post data connection sampler check content type url encoded connection byte expected url title title value description description value get bytes us ascii check content length connection expected url length check arrays have same content expected url connection get output stream content assert equals url decoder decode new string expected url us ascii iso 8859 1 url decoder decode new string connection get output stream content us ascii iso 8859 1 connection disconnect test sending data as iso 8859 1 establish connection content encoding iso 8859 1 sampler set content encoding content encoding post writer set headers connection sampler post writer send post data connection sampler check content type url encoded connection expected url new string title title value description description value get bytes us ascii check content length connection expected url length check arrays have same content expected url connection get output stream content assert equals url decoder decode new string expected url us ascii content encoding url decoder decode new string connection get output stream content us ascii content encoding connection disconnect test sending data as iso 8859 1 with values that need to be urlencoded establish connection title value mytitle 123 456 yes description value mydescription and some spaces content encoding iso 8859 1 sampler set content encoding content encoding setup form data sampler title value description value post writer set headers connection sampler post writer send post data connection sampler check content type url encoded connection string expected string title url encoder encode title value content encoding description url encoder encode description value content encoding expected url expected string get bytes content encoding check content length connection expected url length check arrays have same content expected url connection get output stream content assert equals url decoder decode new string expected url us ascii content encoding url decoder decode new string connection get output stream content us ascii content encoding string unencoded string title title value description description value byte unexpected url unencoded string get bytes utf 8 check arrays have different content unexpected url connection get output stream content connection disconnect test sending data as utf 8 establish connection title value mytitle u0153 u20a1 u0115 u00c5 description value mydescription u0153 u20a1 u0115 u00c5 content encoding utf 8 sampler set content encoding content encoding setup form data sampler title value description value post writer set headers connection sampler post writer send post data connection sampler check content type url encoded connection expected string title url encoder encode title value content encoding description url encoder encode description value content encoding expected url expected string get bytes us ascii check content length connection expected url length check arrays have same content expected url connection get output stream content assert equals url decoder decode new string expected url us ascii content encoding url decoder decode new string connection get output stream content us ascii content encoding connection disconnect test sending data as utf 8 with values that needs to be urlencoded establish connection title value mytitle u0153 u20a1 u0115 yes u00c5 description value mydescription u0153 u20a1 u0115 u00c5 content encoding utf 8 sampler set content encoding content encoding setup form data sampler title value description value post writer set headers connection sampler post writer send post data connection sampler check content type url encoded connection expected string title url encoder encode title value utf 8 description url encoder encode description value utf 8 expected url expected string get bytes us ascii check content length connection expected url length check arrays have same content expected url connection get output stream content assert equals url decoder decode new string expected url us ascii content encoding url decoder decode new string connection get output stream content us ascii content encoding unencoded string title title value description description value unexpected url unencoded string get bytes us ascii check arrays have different content unexpected url connection get output stream content connection disconnect test sending parameters which are urlencoded beforehand the values must be url encoded with utf 8 encoding because that is what the http argument assumes c3 85 in utf 8 is the same as c5 in iso 8859 1 which is the same as aring title value mytitle 20and 20space 2 ftest c3 85 description value mydescription and plus as space 2 ftest c3 85 setup form data sampler true title value description value test sending data with default encoding establish connection content encoding sampler set content encoding content encoding post writer set headers connection sampler post writer send post data connection sampler check content type url encoded connection expected url new string title title value replace all 20 replace all c3 85 c5 description description value replace all c3 85 c5 get bytes us ascii check content length connection expected url length check arrays have same content expected url connection get output stream content assert equals url decoder decode new string expected url us ascii iso 8859 1 http sampler uses iso 8859 1 as default encoding url decoder decode new string connection get output stream content us ascii iso 8859 1 http sampler uses iso 8859 1 as default encoding connection disconnect test sending data as iso 8859 1 establish connection content encoding iso 8859 1 sampler set content encoding content encoding post writer set headers connection sampler post writer send post data connection sampler check content type url encoded connection expected url new string title title value replace all 20 replace all c3 85 c5 description description value replace all c3 85 c5 get bytes us ascii check content length connection expected url length check arrays have same content expected url connection get output stream content assert equals url decoder decode new string expected url us ascii content encoding url decoder decode new string connection get output stream content us ascii content encoding connection disconnect test sending data as utf 8 establish connection content encoding utf 8 sampler set content encoding content encoding post writer set headers connection sampler post writer send post data connection sampler check content type url encoded connection expected url new string title title value replace all 20 description description value get bytes us ascii check content length connection expected url length check arrays have same content expected url connection get output stream content assert equals url decoder decode new string expected url us ascii content encoding url decoder decode new string connection get output stream content us ascii content encoding connection disconnect testsendformdata_urlencoded ioexception titlevalue descriptionvalue setupformdata titlevalue descriptionvalue contentencoding setcontentencoding contentencoding postwriter setheaders postwriter sendpostdata checkcontenttypeurlencoded expectedurl titlevalue descriptionvalue getbytes checkcontentlength expectedurl checkarrayshavesamecontent expectedurl getoutputstreamcontent assertequals urldecoder expectedurl urldecoder getoutputstreamcontent establishconnection contentencoding setcontentencoding contentencoding postwriter setheaders postwriter sendpostdata checkcontenttypeurlencoded expectedurl titlevalue descriptionvalue getbytes checkcontentlength expectedurl checkarrayshavesamecontent expectedurl getoutputstreamcontent assertequals urldecoder expectedurl contentencoding urldecoder getoutputstreamcontent contentencoding establishconnection titlevalue descriptionvalue contentencoding setcontentencoding contentencoding setupformdata titlevalue descriptionvalue postwriter setheaders postwriter sendpostdata checkcontenttypeurlencoded expectedstring urlencoder titlevalue contentencoding urlencoder descriptionvalue contentencoding expectedurl expectedstring getbytes contentencoding checkcontentlength expectedurl checkarrayshavesamecontent expectedurl getoutputstreamcontent assertequals urldecoder expectedurl contentencoding urldecoder getoutputstreamcontent contentencoding unencodedstring titlevalue descriptionvalue unexpectedurl unencodedstring getbytes utf_8 checkarrayshavedifferentcontent unexpectedurl getoutputstreamcontent establishconnection titlevalue descriptionvalue contentencoding utf_8 setcontentencoding contentencoding setupformdata titlevalue descriptionvalue postwriter setheaders postwriter sendpostdata checkcontenttypeurlencoded expectedstring urlencoder titlevalue contentencoding urlencoder descriptionvalue contentencoding expectedurl expectedstring getbytes checkcontentlength expectedurl checkarrayshavesamecontent expectedurl getoutputstreamcontent assertequals urldecoder expectedurl contentencoding urldecoder getoutputstreamcontent contentencoding establishconnection titlevalue descriptionvalue contentencoding utf_8 setcontentencoding contentencoding setupformdata titlevalue descriptionvalue postwriter setheaders postwriter sendpostdata checkcontenttypeurlencoded expectedstring urlencoder titlevalue utf_8 urlencoder descriptionvalue utf_8 expectedurl expectedstring getbytes checkcontentlength expectedurl checkarrayshavesamecontent expectedurl getoutputstreamcontent assertequals urldecoder expectedurl contentencoding urldecoder getoutputstreamcontent contentencoding unencodedstring titlevalue descriptionvalue unexpectedurl unencodedstring getbytes checkarrayshavedifferentcontent unexpectedurl getoutputstreamcontent httpargument titlevalue 2ftest descriptionvalue 2ftest setupformdata titlevalue descriptionvalue establishconnection contentencoding setcontentencoding contentencoding postwriter setheaders postwriter sendpostdata checkcontenttypeurlencoded expectedurl titlevalue replaceall replaceall descriptionvalue replaceall getbytes checkcontentlength expectedurl checkarrayshavesamecontent expectedurl getoutputstreamcontent assertequals urldecoder expectedurl httpsampler urldecoder getoutputstreamcontent httpsampler establishconnection contentencoding setcontentencoding contentencoding postwriter setheaders postwriter sendpostdata checkcontenttypeurlencoded expectedurl titlevalue replaceall replaceall descriptionvalue replaceall getbytes checkcontentlength expectedurl checkarrayshavesamecontent expectedurl getoutputstreamcontent assertequals urldecoder expectedurl contentencoding urldecoder getoutputstreamcontent contentencoding establishconnection contentencoding utf_8 setcontentencoding contentencoding postwriter setheaders postwriter sendpostdata checkcontenttypeurlencoded expectedurl titlevalue replaceall descriptionvalue getbytes checkcontentlength expectedurl checkarrayshavesamecontent expectedurl getoutputstreamcontent assertequals urldecoder expectedurl contentencoding urldecoder getoutputstreamcontent contentencoding public void test set headers throws io exception sampler set method http sampler base post setup filepart sampler setup form data sampler post writer set headers connection sampler check content type multipart connection post writer boundary testsetheaders ioexception setmethod httpsamplerbase setupfilepart setupformdata postwriter setheaders checkcontenttypemultipart postwriter public void testsetheaders nofilename throws io exception setup no filename sampler setup form data sampler post writer set headers connection sampler check content type url encoded connection check content length connection title mytitle description mydescription length testsetheaders_nofilename ioexception setupnofilename setupformdata postwriter setheaders checkcontenttypeurlencoded checkcontentlength setup commons parts of http sampler with a no filename param http sampler throws io exception private void setup no filename http sampler http sampler setup filepart sampler upload null application octet stream httpsampler httpsampler ioexception setupnofilename httpsampler httpsampler setupfilepart setup the filepart with default values param http sampler private void setup filepart http sampler http sampler setup filepart sampler upload temporary file text plain httpsampler setupfilepart httpsampler httpsampler setupfilepart temporaryfile setup the filepart with specified values param http sampler private void setup filepart http sampler http sampler string file field file file string mime type http sampler set file field file field if file null http sampler set filename file get absolute path else http sampler set filename http sampler set mimetype mime type httpsampler setupfilepart httpsampler httpsampler filefield mimetype httpsampler setfilefield filefield httpsampler setfilename getabsolutepath httpsampler setfilename httpsampler setmimetype mimetype setup the form data with default values param http sampler private void setup form data http sampler http sampler setup form data http sampler mytitle mydescription httpsampler setupformdata httpsampler httpsampler setupformdata httpsampler setup the form data with specified values param http sampler private void setup form data http sampler http sampler string title value string description value setup form data sampler false title value description value httpsampler setupformdata httpsampler httpsampler titlevalue descriptionvalue setupformdata titlevalue descriptionvalue setup the form data with specified values param http sampler private void setup form data http sampler http sampler boolean is encoded string title value string description value arguments args new arguments http argument argument1 new http argument title title value is encoded http argument argument2 new http argument description description value is encoded args add argument argument1 args add argument argument2 http sampler set arguments args httpsampler setupformdata httpsampler httpsampler isencoded titlevalue descriptionvalue httpargument httpargument titlevalue isencoded httpargument httpargument descriptionvalue isencoded addargument addargument httpsampler setarguments private void establish connection throws malformedurl exception connection new stuburl connection http fake url test establishconnection malformedurlexception stuburlconnection fake_url create the expected output post body for form data and file multiparts with default values for field names private byte create expected output string boundary string string content encoding string title value string description value byte file content throws io exception return create expected output boundary string content encoding title title value description description value upload file content createexpectedoutput boundarystring contentencoding titlevalue descriptionvalue filecontent ioexception createexpectedoutput boundarystring contentencoding titlevalue descriptionvalue filecontent create the expected output post body for form data and file multiparts with specified values private byte create expected output string boundary string string content encoding string title field string title value string description field string description value string file field byte file content throws io exception create the multiparts byte formdata multipart create expected formdata output boundary string content encoding title field title value description field description value true false byte file multipart create expected filepart output boundary string file field temporary file text plain file content false true join the two multiparts byte array output stream output new byte array output stream output write formdata multipart output write file multipart output flush output close return output to byte array createexpectedoutput boundarystring contentencoding titlefield titlevalue descriptionfield descriptionvalue filefield filecontent ioexception formdatamultipart createexpectedformdataoutput boundarystring contentencoding titlefield titlevalue descriptionfield descriptionvalue filemultipart createexpectedfilepartoutput boundarystring filefield temporaryfile filecontent bytearrayoutputstream bytearrayoutputstream formdatamultipart filemultipart tobytearray create the expected output multipart form data with only form data and no file multipart param last multipart true if this is the last multipart in the request private byte create expected formdata output string boundary string string content encoding string title field string title value string description field string description value boolean first multipart boolean last multipart throws io exception final byte dash dash get bytes http encoding all form parameter always have text plain as mime type final string mime type text plain todo make this a parameter final byte array output stream output new byte array output stream if first multipart output write dash dash output write boundary string get bytes http encoding output write crlf output write content disposition form data name get bytes http encoding output write title field get bytes http encoding output write get bytes http encoding output write crlf output write content type get bytes http encoding output write mime type get bytes http encoding output write charset get bytes http encoding output write content encoding null post writer encoding content encoding get bytes http encoding output write crlf output write content transfer encoding 8bit get bytes http encoding output write crlf output write crlf if content encoding null output write title value get bytes content encoding else output write title value get bytes output write crlf output write dash dash output write boundary string get bytes http encoding output write crlf output write content disposition form data name get bytes http encoding output write description field get bytes http encoding output write get bytes http encoding output write crlf output write content type get bytes http encoding output write mime type get bytes http encoding output write charset get bytes http encoding output write content encoding null post writer encoding content encoding get bytes http encoding output write crlf output write content transfer encoding 8bit get bytes http encoding output write crlf output write crlf if content encoding null output write description value get bytes content encoding else output write description value get bytes output write crlf output write dash dash output write boundary string get bytes http encoding if last multipart output write dash dash output write crlf output flush output close return output to byte array lastmultipart createexpectedformdataoutput boundarystring contentencoding titlefield titlevalue descriptionfield descriptionvalue firstmultipart lastmultipart ioexception dash_dash getbytes http_encoding mimetype bytearrayoutputstream bytearrayoutputstream firstmultipart dash_dash boundarystring getbytes http_encoding getbytes http_encoding titlefield getbytes http_encoding getbytes http_encoding getbytes http_encoding mimetype getbytes http_encoding getbytes http_encoding contentencoding postwriter contentencoding getbytes http_encoding getbytes http_encoding contentencoding titlevalue getbytes contentencoding titlevalue getbytes dash_dash boundarystring getbytes http_encoding getbytes http_encoding descriptionfield getbytes http_encoding getbytes http_encoding getbytes http_encoding mimetype getbytes http_encoding getbytes http_encoding contentencoding postwriter contentencoding getbytes http_encoding getbytes http_encoding contentencoding descriptionvalue getbytes contentencoding descriptionvalue getbytes dash_dash boundarystring getbytes http_encoding lastmultipart dash_dash tobytearray create the expected file multipart param last multipart true if this is the last multipart in the request private byte create expected filepart output string boundary string string file field file file string mime type byte file content boolean first multipart boolean last multipart throws io exception the encoding used for http headers and control information final string http encoding iso 8859 1 final byte dash dash get bytes http encoding final byte array output stream output new byte array output stream if first multipart output write dash dash output write boundary string get bytes http encoding output write crlf replace all backslash with double backslash string filename file get name output write content disposition form data name get bytes http encoding output write file field get bytes http encoding output write filename filename get bytes http encoding output write crlf output write content type get bytes http encoding output write mime type get bytes http encoding output write crlf output write content transfer encoding binary get bytes http encoding output write crlf output write crlf output write file content output write crlf output write dash dash output write boundary string get bytes http encoding if last multipart output write dash dash output write crlf output flush output close return output to byte array lastmultipart createexpectedfilepartoutput boundarystring filefield mimetype filecontent firstmultipart lastmultipart ioexception httpencoding dash_dash getbytes httpencoding bytearrayoutputstream bytearrayoutputstream firstmultipart dash_dash boundarystring getbytes httpencoding getname getbytes httpencoding filefield getbytes httpencoding getbytes httpencoding getbytes httpencoding mimetype getbytes httpencoding getbytes httpencoding filecontent dash_dash boundarystring getbytes httpencoding lastmultipart dash_dash tobytearray check that the the two byte arrays have identical content param expected param actual throws unsupported encoding exception private void check arrays have same content byte expected byte actual throws unsupported encoding exception if expected null actual null if expected length actual length system out println new string expected utf 8 system out println system out println new string actual utf 8 system out println fail arrays have different length expected is expected length actual is actual length else for int i 0 i expected length i if expected i actual i system out println new string expected 0 i 1 system out println system out println new string actual 0 i 1 system out println fail byte at position i is different expected is expected i actual is actual i else fail expected or actual byte arrays were null unsupportedencodingexception checkarrayshavesamecontent unsupportedencodingexception utf_8 utf_8 check that the the two byte arrays different content param expected param actual private void check arrays have different content byte expected byte actual if expected null actual null if expected length actual length boolean all same true for int i 0 i expected length i if expected i actual i all same false break if all same fail all bytes were equal else fail expected or actual byte arrays were null checkarrayshavedifferentcontent allsame allsame allsame private void check content type multipart httpurl connection conn string boundary string assert equals multipart form data boundary boundary string conn get request property content type checkcontenttypemultipart httpurlconnection boundarystring assertequals boundarystring getrequestproperty private void check content type url encoded httpurl connection conn assert equals http sampler base application x www form urlencoded conn get request property content type checkcontenttypeurlencoded httpurlconnection assertequals httpsamplerbase application_x_www_form_urlencoded getrequestproperty private void check content length httpurl connection conn int length assert equals integer to string length conn get request property content length checkcontentlength httpurlconnection assertequals tostring getrequestproperty private map properties new hash map public stuburl connection string url throws malformedurl exception super new url url hashmap stuburlconnection malformedurlexception public void connect throws io exception ioexception public output stream get output stream throws io exception return output outputstream getoutputstream ioexception public void disconnect public boolean using proxy return false usingproxy public string get request property string key return string properties get key getrequestproperty public void set request property string key string value properties put key value setrequestproperty public byte get output stream content return output to byte array getoutputstreamcontent tobytearray public class testhttp samplers extends test case public testhttp samplers string arg0 super arg0 testhttpsamplers testcase testhttpsamplers parse arguments singly public void test parse arguments http sampler base sampler new http null sampler arguments args argument arg args sampler get arguments assert equals 0 args get argument count assert equals 0 sampler gethttp file count sampler parse arguments args sampler get arguments assert equals 0 args get argument count assert equals 0 sampler gethttp file count sampler parse arguments name1 args sampler get arguments assert equals 1 args get argument count arg args get argument 0 assert equals name1 arg get name assert equals arg get meta data assert equals arg get value assert equals 0 sampler gethttp file count sampler parse arguments name2 args sampler get arguments assert equals 2 args get argument count arg args get argument 1 assert equals name2 arg get name assert equals arg get meta data assert equals arg get value assert equals 0 sampler gethttp file count sampler parse arguments name3 value3 args sampler get arguments assert equals 3 args get argument count arg args get argument 2 assert equals name3 arg get name assert equals arg get meta data assert equals value3 arg get value assert equals 0 sampler gethttp file count testparsearguments httpsamplerbase httpnullsampler getarguments assertequals getargumentcount assertequals gethttpfilecount parsearguments getarguments assertequals getargumentcount assertequals gethttpfilecount parsearguments getarguments assertequals getargumentcount getargument assertequals getname assertequals getmetadata assertequals getvalue assertequals gethttpfilecount parsearguments getarguments assertequals getargumentcount getargument assertequals getname assertequals getmetadata assertequals getvalue assertequals gethttpfilecount parsearguments getarguments assertequals getargumentcount getargument assertequals getname assertequals getmetadata assertequals getvalue assertequals gethttpfilecount parse arguments all at once public void test parse arguments2 http sampler base sampler new http null sampler arguments args argument arg args sampler get arguments assert equals 0 args get argument count assert equals 0 sampler gethttp file count sampler parse arguments name1 name2 name3 value3 args sampler get arguments assert equals 3 args get argument count assert equals 0 sampler gethttp file count arg args get argument 0 assert equals name1 arg get name assert equals arg get meta data assert equals arg get value assert equals 0 sampler gethttp file count arg args get argument 1 assert equals name2 arg get name assert equals arg get meta data assert equals arg get value assert equals 0 sampler gethttp file count arg args get argument 2 assert equals name3 arg get name assert equals arg get meta data assert equals value3 arg get value assert equals 0 sampler gethttp file count testparsearguments2 httpsamplerbase httpnullsampler getarguments assertequals getargumentcount assertequals gethttpfilecount parsearguments getarguments assertequals getargumentcount assertequals gethttpfilecount getargument assertequals getname assertequals getmetadata assertequals getvalue assertequals gethttpfilecount getargument assertequals getname assertequals getmetadata assertequals getvalue assertequals gethttpfilecount getargument assertequals getname assertequals getmetadata assertequals getvalue assertequals gethttpfilecount public void test argument without equals throws exception http sampler base sampler new http null sampler sampler set protocol http sampler set method http sampler base get sampler set path index html pear sampler set domain www apache org assert equals http www apache org index html pear sampler get url to string testargumentwithoutequals httpsamplerbase httpnullsampler setprotocol setmethod httpsamplerbase setpath setdomain assertequals geturl tostring public void test making url throws exception http sampler base config new http null sampler config set protocol http config set method http sampler base get config add argument param1 value1 config set path index html config set domain www apache org assert equals http www apache org index html param1 value1 config get url to string testmakingurl httpsamplerbase httpnullsampler setprotocol setmethod httpsamplerbase addargument setpath setdomain assertequals geturl tostring public void test making url2 throws exception http sampler base config new http null sampler config set protocol http config set method http sampler base get config add argument param1 value1 config set path index html p1 p2 config set domain www apache org assert equals http www apache org index html param1 value1 p1 p2 config get url to string testmakingurl2 httpsamplerbase httpnullsampler setprotocol setmethod httpsamplerbase addargument setpath setdomain assertequals geturl tostring public void test making url3 throws exception http sampler base config new http null sampler config set protocol http config set method http sampler base post config add argument param1 value1 config set path index html p1 p2 config set domain www apache org assert equals http www apache org index html p1 p2 config get url to string testmakingurl3 httpsamplerbase httpnullsampler setprotocol setmethod httpsamplerbase addargument setpath setdomain assertequals geturl tostring public void test making url4 throws exception http sampler base config new http null sampler config set protocol http config set method http sampler base get config add argument param1 value1 config set path index html config set domain www apache org assert equals http www apache org index html param1 value1 config get url to string testmakingurl4 httpsamplerbase httpnullsampler setprotocol setmethod httpsamplerbase addargument setpath setdomain assertequals geturl tostring public void test making url5 throws exception http sampler base config new http null sampler config set protocol http config set method http sampler base get config add argument param1 config set path index html config set domain www apache org assert equals http www apache org index html param1 config get url to string testmakingurl5 httpsamplerbase httpnullsampler setprotocol setmethod httpsamplerbase addargument setpath setdomain assertequals geturl tostring public void test making url6 throws exception http sampler base config new http null sampler config set protocol http config set method http sampler base get config add argument param1 config set path index html config set domain www apache org assert equals http www apache org index html param1 config get url to string testmakingurl6 httpsamplerbase httpnullsampler setprotocol setmethod httpsamplerbase addargument setpath setdomain assertequals geturl tostring public void test making url7 throws exception http sampler base config new http null sampler config set protocol http config set method http sampler base get config parse arguments param1 value1 config set path index html config set domain www apache org assert equals http www apache org index html param1 value1 config get url to string testmakingurl7 httpsamplerbase httpnullsampler setprotocol setmethod httpsamplerbase parsearguments setpath setdomain assertequals geturl tostring public void test making url8 throws exception http sampler base config new http null sampler config set protocol http config set method http sampler base get config parse arguments param1 config set path index html config set domain www apache org assert equals http www apache org index html param1 config get url to string testmakingurl8 httpsamplerbase httpnullsampler setprotocol setmethod httpsamplerbase parsearguments setpath setdomain assertequals geturl tostring public void test making url9 throws exception http sampler base config new http null sampler config set protocol http config set method http sampler base get config parse arguments param1 config set path index html config set domain www apache org assert equals http www apache org index html param1 config get url to string testmakingurl9 httpsamplerbase httpnullsampler setprotocol setmethod httpsamplerbase parsearguments setpath setdomain assertequals geturl tostring public void test making url10 throws exception http sampler base config new http null sampler config set protocol http config set method http sampler base get config parse arguments config set path index html config set domain www apache org assert equals http www apache org index html config get url to string testmakingurl10 httpsamplerbase httpnullsampler setprotocol setmethod httpsamplerbase parsearguments setpath setdomain assertequals geturl tostring public void test file list http sampler base config new http null sampler http file arg arg arg config gethttp files assert not null arg assert equals 0 arg length config set file field config set filename config set mimetype arg config gethttp files assert not null arg assert equals 0 arg length config set mimetype text plain arg config gethttp files assert not null arg assert equals 1 arg length assert equals text plain arg 0 get mime type assert equals arg 0 get path assert equals arg 0 get param name config set file field test123 tmp config set filename tmp test123 tmp arg config gethttp files assert not null arg assert equals 1 arg length assert equals text plain arg 0 get mime type assert equals tmp test123 tmp arg 0 get path assert equals test123 tmp arg 0 get param name http file arg files ignore empty file specs config sethttp files files arg config gethttp files assert not null arg assert equals 0 arg length files new http file arg new http file arg new http file arg config sethttp files files arg config gethttp files assert not null arg assert equals 0 arg length ignore trailing empty spec files new http file arg new http file arg file new http file arg config sethttp files files arg config gethttp files assert not null arg assert equals 1 arg length ignore leading empty spec files new http file arg new http file arg new http file arg file1 new http file arg new http file arg file2 new http file arg config sethttp files files arg config gethttp files assert not null arg assert equals 2 arg length testfilelist httpsamplerbase httpnullsampler httpfilearg gethttpfiles assertnotnull assertequals setfilefield setfilename setmimetype gethttpfiles assertnotnull assertequals setmimetype gethttpfiles assertnotnull assertequals assertequals getmimetype assertequals getpath assertequals getparamname setfilefield setfilename gethttpfiles assertnotnull assertequals assertequals getmimetype assertequals getpath assertequals getparamname httpfilearg sethttpfiles gethttpfiles assertnotnull assertequals httpfilearg httpfilearg httpfilearg sethttpfiles gethttpfiles assertnotnull assertequals httpfilearg httpfilearg httpfilearg sethttpfiles gethttpfiles assertnotnull assertequals httpfilearg httpfilearg httpfilearg httpfilearg httpfilearg httpfilearg sethttpfiles gethttpfiles assertnotnull assertequals public void test set and get file field http sampler base sampler new http null sampler sampler set file field param assert equals param sampler get file field http file arg file sampler gethttp files 0 assert equals param file get param name sampler set file field param2 assert equals param2 sampler get file field file sampler gethttp files 0 assert equals param2 file get param name testsetandgetfilefield httpsamplerbase httpnullsampler setfilefield assertequals getfilefield httpfilearg gethttpfiles assertequals getparamname setfilefield assertequals getfilefield gethttpfiles assertequals getparamname public void test set and get filename http sampler base sampler new http null sampler sampler set filename name assert equals name sampler get filename http file arg file sampler gethttp files 0 assert equals name file get path sampler set filename name2 assert equals name2 sampler get filename file sampler gethttp files 0 assert equals name2 file get path testsetandgetfilename httpsamplerbase httpnullsampler setfilename assertequals getfilename httpfilearg gethttpfiles assertequals getpath setfilename assertequals getfilename gethttpfiles assertequals getpath public void test set and get mimetype http sampler base sampler new http null sampler sampler set mimetype mime assert equals mime sampler get mimetype http file arg file sampler gethttp files 0 assert equals mime file get mime type sampler set mimetype mime2 assert equals mime2 sampler get mimetype file sampler gethttp files 0 assert equals mime2 file get mime type testsetandgetmimetype httpsamplerbase httpnullsampler setmimetype assertequals getmimetype httpfilearg gethttpfiles assertequals getmimetype setmimetype assertequals getmimetype gethttpfiles assertequals getmimetype proxy control control public test proxy control string name super name proxycontrol testproxycontrol public void set up control new proxy control control add included pattern jsp control add excluded pattern apache org sampler new http null sampler setup proxycontrol addincludedpattern addexcludedpattern httpnullsampler public void test filter1 throws exception sampler set domain jakarta org sampler set path index jsp assert true should find jakarta org index jsp control filter url sampler testfilter1 setdomain setpath asserttrue filterurl public void test filter2 throws exception sampler set path index jsp sampler set domain www apache org assert false should not match www apache org control filter url sampler testfilter2 setpath setdomain assertfalse filterurl public void test filter3 throws exception sampler set path header gif sampler set domain jakarta org assert false should not match header gif control filter url sampler testfilter3 setpath setdomain assertfalse filterurl public void test content type no filters throws exception sample result result new sample result no filters control set content type include null control set content type exclude null result set content type null assert true should allow if no content type present control filter content type result result set content type text html charset utf 8 assert true should allow text html control filter content type result result set content type image png assert true should allow image png control filter content type result empty filters control set content type include control set content type exclude result set content type null assert true should allow if no content type present control filter content type result result set content type text html charset utf 8 assert true should allow text html control filter content type result result set content type image png assert true should allow image png control filter content type result non empty filters control set content type include control set content type exclude result set content type null assert true should allow if no content type present control filter content type result result set content type text html charset utf 8 assert false should not allow text html control filter content type result result set content type image png assert false should not allow image png control filter content type result testcontenttypenofilters sampleresult sampleresult setcontenttypeinclude setcontenttypeexclude setcontenttype asserttrue filtercontenttype setcontenttype asserttrue filtercontenttype setcontenttype asserttrue filtercontenttype setcontenttypeinclude setcontenttypeexclude setcontenttype asserttrue filtercontenttype setcontenttype asserttrue filtercontenttype setcontenttype asserttrue filtercontenttype setcontenttypeinclude setcontenttypeexclude setcontenttype asserttrue filtercontenttype setcontenttype assertfalse filtercontenttype setcontenttype assertfalse filtercontenttype public void test content type include throws exception sample result result new sample result control set content type include text html text ascii result set content type null assert true should allow if no content type present control filter content type result result set content type text html charset utf 8 assert true should allow text html control filter content type result result set content type text css assert false should not allow text css control filter content type result testcontenttypeinclude sampleresult sampleresult setcontenttypeinclude setcontenttype asserttrue filtercontenttype setcontenttype asserttrue filtercontenttype setcontenttype assertfalse filtercontenttype public void test content type exclude throws exception sample result result new sample result control set content type exclude text css result set content type null assert true should allow if no content type present control filter content type result result set content type text html charset utf 8 assert true should allow text html control filter content type result result set content type text css assert false should not allow text css control filter content type result testcontenttypeexclude sampleresult sampleresult setcontenttypeexclude setcontenttype asserttrue filtercontenttype setcontenttype asserttrue filtercontenttype setcontenttype assertfalse filtercontenttype public void test content type include and exclude throws exception sample result result new sample result simple inclusion and exclusion filter control set content type include text html text ascii control set content type exclude text css result set content type null assert true should allow if no content type present control filter content type result result set content type text html charset utf 8 assert true should allow text html control filter content type result result set content type text css assert false should not allow text css control filter content type result result set content type image png assert false should not allow image png control filter content type result allow all but images control set content type include null control set content type exclude image result set content type null assert true should allow if no content type present control filter content type result result set content type text html charset utf 8 assert true should allow text html control filter content type result result set content type text css assert true should allow text css control filter content type result result set content type image png assert false should not allow image png control filter content type result testcontenttypeincludeandexclude sampleresult sampleresult setcontenttypeinclude setcontenttypeexclude setcontenttype asserttrue filtercontenttype setcontenttype asserttrue filtercontenttype setcontenttype assertfalse filtercontenttype setcontenttype assertfalse filtercontenttype setcontenttypeinclude setcontenttypeexclude setcontenttype asserttrue filtercontenttype setcontenttype asserttrue filtercontenttype setcontenttype asserttrue filtercontenttype setcontenttype assertfalse filtercontenttype private http test sample gui gui public test http test sample gui string name super name httptestsamplegui testhttptestsamplegui public void set up gui new http test sample gui setup httptestsamplegui public void test clone sampler throws exception http sampler base sampler http sampler base gui create test element sampler add argument param value http sampler base cloned sampler http sampler base sampler clone cloned sampler set running version true sampler get arguments get argument 0 set value new value assert equals sampler didn t clone correctly new value sampler get arguments get argument 0 get value testclonesampler httpsamplerbase httpsamplerbase createtestelement addargument httpsamplerbase clonedsampler httpsamplerbase clonedsampler setrunningversion getarguments getargument setvalue assertequals getarguments getargument getvalue private final static int http server port 8181 public testhttp mirror thread string arg0 super arg0 http_server_port testhttpmirrorthread public static test suite test setup setup new test setup new test suite testhttp mirror thread class private http mirror server http server protected void set up throws exception http server start http mirror http server port protected void tear down throws exception shutdown the http server http server stop server http server null return setup testsetup testsetup testsuite testhttpmirrorthread httpmirrorserver httpserver setup httpserver starthttpmirror http_server_port teardown httpserver stopserver httpserver private http mirror server http server protected void set up throws exception http server start http mirror http server port httpmirrorserver httpserver setup httpserver starthttpmirror http_server_port protected void tear down throws exception shutdown the http server http server stop server http server null teardown httpserver stopserver httpserver utility method to handle starting the http mirror server for testing also used by testhttp samplers against http mirror server public static http mirror server start http mirror int port throws exception http mirror server server null server new http mirror server port server start exception e null for int i 0 i 10 i wait up to 1 second try thread sleep 100 catch interrupted exception ignored e server get exception if e null already failed throw new exception could not start mirror server on port port e if server is alive break succeeded if server is alive throw new exception could not start mirror server on port port return server httpmirrorserver testhttpsamplersagainsthttpmirrorserver httpmirrorserver starthttpmirror httpmirrorserver httpmirrorserver interruptedexception getexception isalive isalive public void test get request throws exception connect to the http server and do a simple http get socket client socket new socket localhost http server port output stream output stream client socket get output stream input stream input stream client socket get input stream write to the socket byte array output stream bos new byte array output stream headers bos write get http 1 1 get bytes iso 8859 1 bos write crlf bos write host localhost get bytes iso 8859 1 bos write crlf bos write crlf bos close output stream write bos to byte array read the response byte array output stream response new byte array output stream byte buffer new byte 1024 int length 0 while length input stream read buffer 1 response write buffer 0 length response close byte mirrored response get mirrored response response to byte array check that the request and response matches check arrays have same content bos to byte array mirrored response close the connection client socket close connect to the http server and do a simple http get with a pause in the middle of transmitting the header client socket new socket localhost http server port output stream client socket get output stream input stream client socket get input stream write to the socket bos new byte array output stream headers bos write get http 1 1 get bytes iso 8859 1 bos write crlf write the start of the headers and then sleep so that the mirror thread will have to block to wait for more data to appear bos close byte first chunk bos to byte array output stream write first chunk thread sleep 300 write the rest of the headers bos new byte array output stream bos write host localhost get bytes iso 8859 1 bos write crlf bos write crlf bos close byte second chunk bos to byte array output stream write second chunk read the response response new byte array output stream buffer new byte 1024 length 0 while length input stream read buffer 1 response write buffer 0 length response close mirrored response get mirrored response response to byte array the content sent bos new byte array output stream bos write first chunk bos write second chunk bos close check that the request and response matches check arrays have same content bos to byte array mirrored response close the connection client socket close testgetrequest clientsocket http_server_port outputstream outputstream clientsocket getoutputstream inputstream inputstream clientsocket getinputstream bytearrayoutputstream bytearrayoutputstream getbytes iso_8859_1 getbytes iso_8859_1 outputstream tobytearray bytearrayoutputstream bytearrayoutputstream inputstream mirroredresponse getmirroredresponse tobytearray checkarrayshavesamecontent tobytearray mirroredresponse clientsocket clientsocket http_server_port outputstream clientsocket getoutputstream inputstream clientsocket getinputstream bytearrayoutputstream getbytes iso_8859_1 firstchunk tobytearray outputstream firstchunk bytearrayoutputstream getbytes iso_8859_1 secondchunk tobytearray outputstream secondchunk bytearrayoutputstream inputstream mirroredresponse getmirroredresponse tobytearray bytearrayoutputstream firstchunk secondchunk checkarrayshavesamecontent tobytearray mirroredresponse clientsocket public void test post request throws exception connect to the http server and do a simple http post socket client socket new socket localhost http server port output stream output stream client socket get output stream input stream input stream client socket get input stream construct body string buffer post body buffer new string buffer for int i 0 i 1000 i post body buffer append abc byte post body post body buffer to string get bytes iso 8859 1 write to the socket byte array output stream bos new byte array output stream headers bos write get http 1 1 get bytes iso 8859 1 bos write crlf bos write host localhost get bytes iso 8859 1 bos write crlf bos write content type text plain charset iso 8859 1 get bytes iso 8859 1 bos write crlf bos write content length post body length get bytes iso 8859 1 bos write crlf bos write crlf bos write post body bos close write the headers and body output stream write bos to byte array read the response byte array output stream response new byte array output stream byte buffer new byte 1024 int length 0 while length input stream read buffer 1 response write buffer 0 length response close byte mirrored response get mirrored response response to byte array check that the request and response matches check arrays have same content bos to byte array mirrored response close the connection client socket close connect to the http server and do a simple http post with a pause after transmitting the headers client socket new socket localhost http server port output stream client socket get output stream input stream client socket get input stream write to the socket bos new byte array output stream headers bos write get http 1 1 get bytes iso 8859 1 bos write crlf bos write host localhost get bytes iso 8859 1 bos write crlf bos write content type text plain charset iso 8859 1 get bytes iso 8859 1 bos write crlf bos write content length post body length get bytes iso 8859 1 bos write crlf bos write crlf bos close write the headers and then sleep bos close byte first chunk bos to byte array output stream write first chunk thread sleep 300 write the body byte second chunk post body output stream write second chunk read the response response new byte array output stream buffer new byte 1024 length 0 while length input stream read buffer 1 response write buffer 0 length response close mirrored response get mirrored response response to byte array the content sent bos new byte array output stream bos write first chunk bos write second chunk bos close check that the request and response matches check arrays have same content bos to byte array mirrored response close the connection client socket close connect to the http server and do a simple http post with utf 8 encoding of the body which caused problems when reader writer classes were used in the http mirror thread client socket new socket localhost http server port output stream client socket get output stream input stream client socket get input stream construct body post body buffer new string buffer for int i 0 i 1000 i post body buffer append u0364 u00c5 u2052 post body post body buffer to string get bytes utf 8 write to the socket bos new byte array output stream headers bos write get http 1 1 get bytes iso 8859 1 bos write crlf bos write host localhost get bytes iso 8859 1 bos write crlf bos write content type text plain charset utf 8 get bytes iso 8859 1 bos write crlf bos write content length post body length get bytes iso 8859 1 bos write crlf bos write crlf bos close write the headers and then sleep bos close first chunk bos to byte array output stream write first chunk thread sleep 300 write the body second chunk post body output stream write second chunk read the response response new byte array output stream buffer new byte 1024 length 0 while length input stream read buffer 1 response write buffer 0 length response close mirrored response get mirrored response response to byte array the content sent bos new byte array output stream bos write first chunk bos write second chunk bos close check that the request and response matches check arrays have same content bos to byte array mirrored response close the connection client socket close testpostrequest clientsocket http_server_port outputstream outputstream clientsocket getoutputstream inputstream inputstream clientsocket getinputstream stringbuffer postbodybuffer stringbuffer postbodybuffer postbody postbodybuffer tostring getbytes iso_8859_1 bytearrayoutputstream bytearrayoutputstream getbytes iso_8859_1 getbytes iso_8859_1 iso_8859_1 getbytes iso_8859_1 postbody getbytes iso_8859_1 postbody outputstream tobytearray bytearrayoutputstream bytearrayoutputstream inputstream mirroredresponse getmirroredresponse tobytearray checkarrayshavesamecontent tobytearray mirroredresponse clientsocket clientsocket http_server_port outputstream clientsocket getoutputstream inputstream clientsocket getinputstream bytearrayoutputstream getbytes iso_8859_1 getbytes iso_8859_1 iso_8859_1 getbytes iso_8859_1 postbody getbytes iso_8859_1 firstchunk tobytearray outputstream firstchunk secondchunk postbody outputstream secondchunk bytearrayoutputstream inputstream mirroredresponse getmirroredresponse tobytearray bytearrayoutputstream firstchunk secondchunk checkarrayshavesamecontent tobytearray mirroredresponse clientsocket httpmirrorthread clientsocket http_server_port outputstream clientsocket getoutputstream inputstream clientsocket getinputstream postbodybuffer stringbuffer postbodybuffer postbody postbodybuffer tostring getbytes utf_8 bytearrayoutputstream getbytes iso_8859_1 getbytes iso_8859_1 utf_8 getbytes iso_8859_1 postbody getbytes iso_8859_1 firstchunk tobytearray outputstream firstchunk secondchunk postbody outputstream secondchunk bytearrayoutputstream inputstream mirroredresponse getmirroredresponse tobytearray bytearrayoutputstream firstchunk secondchunk checkarrayshavesamecontent tobytearray mirroredresponse clientsocket check that the the two byte arrays have identical content param expected param actual throws unsupported encoding exception private void check arrays have same content byte expected byte actual throws unsupported encoding exception if expected null actual null if expected length actual length system out println expected length expected length system out println new string expected utf 8 system out println actual length actual length system out println new string actual utf 8 system out println fail arrays have different length expected is expected length actual is actual length else for int i 0 i expected length i if expected i actual i system out println expected length expected length system out println new string expected 0 i 1 system out println actual length actual length system out println new string actual 0 i 1 system out println useful to when debugging for int j 0 j expected length j system out print expected j system out println for int j 0 j actual length j system out print actual j system out println fail byte at position i is different expected is expected i actual is actual i else fail expected or actual byte arrays were null unsupportedencodingexception checkarrayshavesamecontent unsupportedencodingexception private byte get mirrored response byte all response the response includes the headers from the mirror server we want to skip those to only keep the content mirrored look for the first crlfcrlf section int start of mirror response 0 for int i 0 i all response length i todo this is a bit fragile if all response i 0x0d all response i 1 0x0a all response i 2 0x0d all response i 3 0x0a start of mirror response i 4 break byte mirror response new byte all response length start of mirror response system arraycopy all response start of mirror response mirror response 0 mirror response length return mirror response getmirroredresponse allresponse startofmirrorresponse allresponse allresponse allresponse allresponse allresponse startofmirrorresponse mirrorresponse allresponse startofmirrorresponse allresponse startofmirrorresponse mirrorresponse mirrorresponse mirrorresponse public class multipart url config test extends test case public multipart url config test string name super name multiparturlconfigtest testcase multiparturlconfigtest public void test constructors multipart url config muc new multipart url config assert equals 0 muc get arguments get argument count assert equals 0 muc gethttp file args gethttp file arg count muc new multipart url config boundary assert equals 0 muc get arguments get argument count assert equals 0 muc gethttp file args gethttp file arg count assert equals boundary muc get boundary testconstructors multiparturlconfig multiparturlconfig assertequals getarguments getargumentcount assertequals gethttpfileargs gethttpfileargcount multiparturlconfig assertequals getarguments getargumentcount assertequals gethttpfileargs gethttpfileargcount assertequals getboundary public void test parse arguments string query string content disposition form data name aa n content type text plain charset iso 8859 1 n content transfer encoding 8bit n n aa n 7d159c1302d0y0 n content disposition form data name xx n content type text plain charset iso 8859 1 n content transfer encoding 8bit n n xx n 7d159c1302d0y0 n content disposition form data name param1 filename file1 n content type text plain n content transfer encoding binary n n file content n n multipart url config muc new multipart url config 7d159c1302d0y0 muc parse arguments query string http file args files muc gethttp file args assert equals 1 files gethttp file arg count http file arg file http file arg files iterator next get object value assert equals file1 file get path assert equals param1 file get param name assert equals text plain file get mime type arguments args muc get arguments assert equals 2 args get argument count argument arg args get argument 0 assert equals aa arg get name assert equals aa arg get value arg args get argument 1 assert equals xx arg get name assert equals xx arg get value testparsearguments querystring multiparturlconfig multiparturlconfig parsearguments querystring httpfileargs gethttpfileargs assertequals gethttpfileargcount httpfilearg httpfilearg getobjectvalue assertequals getpath assertequals getparamname assertequals getmimetype getarguments assertequals getargumentcount getargument assertequals getname assertequals getvalue getargument assertequals getname assertequals getvalue todo turn this into a proper test case public void test something throws exception testsomething basic method for testing the class param args public static void main string args if args null args length 2 string file null int count 1 if args 0 null file args 0 if args 1 null count integer parse int args 1 try object factory of object factory get instance java io file infile new java io file file java io file input stream fis new java io file input stream infile java io input stream reader isr new java io input stream reader fis string buffer buf new string buffer java io buffered reader br new java io buffered reader isr string line null while line br read line null buf append line system out println contents system out println buf to string system out println status st of parse bytes buf to string get bytes if st null system out println parse failed else system out println parse successful system out println st get jvm get memory get free system out println st get jvm get memory get total system out println st get jvm get memory get max system out println connector size st get connector size connector conn connector st get connector get 0 system out println conn conn get thread info get max threads catch java io file not found exception e e print stack trace catch java io io exception e e print stack trace else parseint objectfactory objectfactory getinstance fileinputstream fileinputstream inputstreamreader inputstreamreader stringbuffer stringbuffer bufferedreader bufferedreader readline tostring parsebytes tostring getbytes getjvm getmemory getfree getjvm getmemory gettotal getjvm getmemory getmax getconnector getconnector getthreadinfo getmaxthreads filenotfoundexception printstacktrace ioexception printstacktrace private static final string file prefix public j meter test case super fileprefix jmetertestcase public j meter test case string name super name jmetertestcase private static void logprop string prop system out println prop system get property prop getproperty helper method to find a file protected static file find test file string file file f new file file if file prefix length 0 f is absolute f new file file prefix file add the offset return f findtestfile fileprefix isabsolute fileprefix protected void check invalid parameter counts abstract function func int minimum throws exception collection parms new linked list for int c 0 c minimum c try func set parameters parms fail should have generated invalid variable exception for parms size parameters catch invalid variable exception ignored parms add func set parameters parms checkinvalidparametercounts abstractfunction linkedlist setparameters invalidvariableexception invalidvariableexception setparameters protected void check invalid parameter counts abstract function func int min int max throws exception collection parms new linked list for int count 0 count min count try func set parameters parms fail should have generated invalid variable exception for parms size parameters catch invalid variable exception ignored parms add for int count min count max count func set parameters parms parms add parms add try func set parameters parms fail should have generated invalid variable exception for parms size parameters catch invalid variable exception ignored checkinvalidparametercounts abstractfunction linkedlist setparameters invalidvariableexception invalidvariableexception setparameters setparameters invalidvariableexception invalidvariableexception public class package test extends test case public package test string arg0 super arg0 packagetest testcase packagetest todo add tests for save graphics public void test save graphics throws exception savegraphics testsavegraphics todo add tests for report save graphics public void test report save graphics throws exception reportsavegraphics testreportsavegraphics save save public test save string name super name testsave public void set up save new save setup public void test tree conversion throws exception hash tree tree new listed hash tree j meter tree node root new j meter tree node new arguments null tree add root root tree get tree root add root root save convert sub tree tree assert equals tree get array 0 get class get name root get test element get class get name tree tree get tree tree get array 0 assert equals tree get array 0 get class get name root get test element get class get name assert equals tree get tree tree get array 0 get array 0 get class get name root get test element get class get name testtreeconversion hashtree listedhashtree jmetertreenode jmetertreenode gettree convertsubtree assertequals getarray getclass getname gettestelement getclass getname gettree getarray assertequals getarray getclass getname gettestelement getclass getname assertequals gettree getarray getarray getclass getname gettestelement getclass getname j meter variables vars public test regex extractor string name super name jmetervariables testregexextractor public void set up jmctx j meter context service get context extractor new regex extractor extractor set thread context jmctx this would be done by the run command extractor set ref name reg val result new sample result string data company xmlext query ret row value field ret code lis ok value value field ret code extension value value field alias value value field positioncount value value field invalidpincount 0 value value field pinposition1 1 value value field pinpositionvalue1 value value field pinposition2 5 value value field pinpositionvalue2 value value field pinposition3 6 value value field pinpositionvalue3 value row company xmlext query ret result set response data data get bytes result set response headers header1 value1 n header2 value2 result set response code abcd result set response message the quick brown fox vars new j meter variables jmctx set variables vars jmctx set previous result result setup jmetercontextservice getcontext regexextractor setthreadcontext setrefname regval sampleresult retcode lis_ok retcodeextension setresponsedata getbytes setresponseheaders nheader2 setresponsecode setresponsemessage jmetervariables setvariables setpreviousresult public void test variable extraction throws exception extractor set regex value field pinposition d d value extractor set template 2 extractor set match number 2 extractor process assert equals 5 vars get reg val assert equals pinposition2 vars get regval g1 assert equals 5 vars get regval g2 assert equals value field pinposition2 5 value vars get regval g0 assert null vars get regval g3 assert equals 2 vars get regval g testvariableextraction setregex settemplate setmatchnumber assertequals regval assertequals regval_g1 assertequals regval_g2 assertequals regval_g0 assertnull regval_g3 assertequals regval_g static void template setup regex extractor rex string tmp rex set regex company w w w rex set match number 1 rex set template tmp rex process templatesetup regexextractor setregex setmatchnumber settemplate public void test template1 throws exception template setup extractor assert equals company xmlext query ret vars get regval g0 assert equals xmlext vars get regval g1 assert equals query vars get regval g2 assert equals ret vars get regval g3 assert equals vars get reg val assert equals 3 vars get regval g testtemplate1 templatesetup assertequals regval_g0 assertequals regval_g1 assertequals regval_g2 assertequals regval_g3 assertequals regval assertequals regval_g public void test template2 throws exception template setup extractor abc assert equals abc vars get reg val testtemplate2 templatesetup assertequals regval public void test template3 throws exception template setup extractor 2 assert equals query vars get reg val testtemplate3 templatesetup assertequals regval public void test template4 throws exception template setup extractor pre 2 assert equals pr equery vars get reg val testtemplate4 templatesetup assertequals prequery regval public void test template5 throws exception template setup extractor 2 post assert equals querypost vars get reg val testtemplate5 templatesetup assertequals regval public void test template6 throws exception template setup extractor 2 1 assert equals queryxmlext vars get reg val testtemplate6 templatesetup assertequals regval public void test template7 throws exception template setup extractor 2 mid 1 assert equals querymi dxmlext vars get reg val testtemplate7 templatesetup assertequals querymidxmlext regval public void test variable extraction2 throws exception extractor set regex value field pinposition d d value extractor set template 1 extractor set match number 3 extractor process assert equals pinposition3 vars get reg val testvariableextraction2 setregex settemplate setmatchnumber assertequals regval public void test variable extraction6 throws exception extractor set regex value field pinposition d d value extractor set template 2 extractor set match number 4 extractor set default value default extractor process assert equals default vars get reg val testvariableextraction6 setregex settemplate setmatchnumber setdefaultvalue assertequals regval public void test variable extraction3 throws exception extractor set regex value field pinposition d d value extractor set template 1 extractor set match number 2 extractor process assert equals pinposition2 vars get reg val testvariableextraction3 setregex settemplate _ setmatchnumber assertequals _pinposition2 regval public void test variable extraction5 throws exception extractor set regex value field pinposition d d value extractor set template 1 extractor set match number 1 set up the non wild variables extractor process assert not null vars get reg val assert equals 2 vars get regval g assert not null vars get regval g0 assert not null vars get regval g1 assert not null vars get regval g2 extractor set match number 1 extractor process assert not null vars get reg val should not clear this assert null vars get regval g assert null vars get regval g1 assert null vars get regval g2 assert equals 3 vars get regval matchnr assert equals pinposition1 vars get regval 1 assert equals pinposition2 vars get regval 2 assert equals pinposition3 vars get regval 3 assert equals 2 vars get regval 1 g assert equals pinposition1 vars get regval 1 g1 assert equals 1 vars get regval 1 g2 assert equals 6 vars get regval 3 g2 assert equals value field pinposition1 1 value vars get regval 1 g0 assert null vars get regval 4 check old values don t hang around extractor set regex w count fewer matches extractor process assert equals 2 vars get regval matchnr assert equals position vars get regval 1 assert equals 1 vars get regval 1 g assert equals position vars get regval 1 g1 assert null unused variables should be null vars get regval 1 g2 assert equals invalidpin vars get regval 2 assert equals 1 vars get regval 2 g assert equals invalidpin vars get regval 2 g1 assert null unused variables should be null vars get regval 2 g2 assert equals 1 vars get regval 1 g assert null unused variables should be null vars get regval 3 assert null unused variables should be null vars get regval 3 g assert null unused variables should be null vars get regval 3 g0 assert null unused variables should be null vars get regval 3 g1 assert null unused variables should be null vars get regval 3 g2 check when match fails extractor set regex xxxx extractor process assert equals 0 vars get regval matchnr assert null unused variables should be null vars get regval 1 assert null unused variables should be null vars get regval 1 g0 assert null unused variables should be null vars get regval 1 g1 assert null unused variables should be null vars get regval 1 g2 testvariableextraction5 setregex settemplate setmatchnumber assertnotnull regval assertequals regval_g assertnotnull regval_g0 assertnotnull regval_g1 assertnotnull regval_g2 setmatchnumber assertnotnull regval assertnull regval_g assertnull regval_g1 assertnull regval_g2 assertequals regval_matchnr assertequals regval_1 assertequals regval_2 assertequals regval_3 assertequals regval_1_g assertequals regval_1_g1 assertequals regval_1_g2 assertequals regval_3_g2 assertequals regval_1_g0 assertnull regval_4 setregex assertequals regval_matchnr assertequals regval_1 assertequals regval_1_g assertequals regval_1_g1 assertnull regval_1_g2 assertequals regval_2 assertequals regval_2_g assertequals regval_2_g1 assertnull regval_2_g2 assertequals regval_1_g assertnull regval_3 assertnull regval_3_g assertnull regval_3_g0 assertnull regval_3_g1 assertnull regval_3_g2 setregex assertequals regval_matchnr assertnull regval_1 assertnull regval_1_g0 assertnull regval_1_g1 assertnull regval_1_g2 public void test variable extraction7 throws exception extractor set regex header1 s extractor set template 1 extractor set match number 1 assert true use body should be true extractor use body assert false use hdrs should be false extractor use headers assert false useurl should be false extractor use url extractor set use field regex extractor use body assert true use body should be true extractor use body assert false use hdrs should be false extractor use headers assert false useurl should be false extractor use url extractor set use field regex extractor use hdrs assert true use hdrs should be true extractor use headers assert false use body should be false extractor use body assert false useurl should be false extractor use url extractor process assert equals value1 vars get reg val extractor set use field regex extractor use url assert false use hdrs should be false extractor use headers assert false use body should be false extractor use body assert true useurl should be true extractor use url testvariableextraction7 setregex settemplate setmatchnumber asserttrue usebody usebody assertfalse usehdrs useheaders assertfalse useurl setusefield regexextractor use_body asserttrue usebody usebody assertfalse usehdrs useheaders assertfalse useurl setusefield regexextractor use_hdrs asserttrue usehdrs useheaders assertfalse usebody usebody assertfalse useurl assertequals regval setusefield regexextractor use_url assertfalse usehdrs useheaders assertfalse usebody usebody asserttrue useurl public void test variable extraction8 throws exception extractor set regex http jakarta apache org w extractor set template 1 extractor set match number 1 extractor set use field regex extractor use url assert false use hdrs should be false extractor use headers assert false use body should be false extractor use body assert true useurl should be true extractor use url extractor process assert null vars get reg val result seturl new url http jakarta apache org index html abcd extractor process assert equals index vars get reg val testvariableextraction8 setregex settemplate setmatchnumber setusefield regexextractor use_url assertfalse usehdrs useheaders assertfalse usebody usebody asserttrue useurl assertnull regval assertequals regval public void test variable extraction9 throws exception extractor set regex w extractor set template 1 extractor set match number 1 extractor set use field regex extractor use code assert false use hdrs should be false extractor use headers assert false use body should be false extractor use body assert false useurl should be false extractor use url assert false use message should be false extractor use message assert true use code should be true extractor use code extractor process assert equals abcd vars get reg val extractor set use field regex extractor use message assert false use hdrs should be false extractor use headers assert false use body should be false extractor use body assert false useurl should be false extractor use url assert true use message should be true extractor use message assert false use code should be falsee extractor use code extractor set match number 3 extractor process assert equals brown vars get reg val testvariableextraction9 setregex settemplate setmatchnumber setusefield regexextractor use_code assertfalse usehdrs useheaders assertfalse usebody usebody assertfalse useurl assertfalse usemessage usemessage asserttrue usecode usecode assertequals regval setusefield regexextractor use_message assertfalse usehdrs useheaders assertfalse usebody usebody assertfalse useurl asserttrue usemessage usemessage assertfalse usecode usecode setmatchnumber assertequals regval public void test no default throws exception extractor set regex value field pinposition d d value extractor set template 2 extractor set match number 4 extractor set default value default vars put reg val initial assert equals initial vars get reg val extractor process assert equals initial vars get reg val testnodefault setregex settemplate setmatchnumber setdefaultvalue regval assertequals regval assertequals regval public void test default throws exception extractor set regex value field pinposition d d value extractor set template 2 extractor set match number 999 extractor set default value default vars put reg val initial assert equals initial vars get reg val extractor process assert equals default vars get reg val assert null vars get regval g0 assert null vars get regval g1 testdefault setregex settemplate setmatchnumber setdefaultvalue regval assertequals regval assertequals regval assertnull regval_g0 assertnull regval_g1 public void test stale variables throws exception extractor set regex value field pinposition d d value extractor set template 2 extractor set match number 1 extractor set default value default extractor process assert equals 1 vars get reg val assert equals 1 vars get regval g2 assert equals 2 vars get regval g assert not null vars get regval g0 assert not null vars get regval g1 now rerun with match fail extractor set match number 10 extractor process assert equals default vars get reg val assert null vars get regval g0 assert null vars get regval g1 assert null vars get regval g teststalevariables setregex settemplate setmatchnumber setdefaultvalue assertequals regval assertequals regval_g2 assertequals regval_g assertnotnull regval_g0 assertnotnull regval_g1 setmatchnumber assertequals regval assertnull regval_g0 assertnull regval_g1 assertnull regval_g j meter variables vars public testx path extractor string name super name jmetervariables testxpathextractor private final static string val name nr value matchnr public void set up jmctx j meter context service get context extractor new x path extractor extractor set thread context jmctx this would be done by the run command extractor set ref name val name extractor set default value default result new sample result string data book preface title intro zero preface page one page page two page empty empty a b b a book result set response data data get bytes vars new j meter variables jmctx set variables vars jmctx set previous result result val_name_nr value_matchnr setup jmetercontextservice getcontext xpathextractor setthreadcontext setrefname val_name setdefaultvalue sampleresult setresponsedata getbytes jmetervariables setvariables setpreviousresult public void test attribute extraction throws exception extractor setx path query book preface title extractor process assert equals intro vars get val name assert equals 1 vars get val name nr assert equals intro vars get val name 1 assert null vars get val name 2 extractor setx path query book preface title extractor process assert equals zero vars get val name assert equals 1 vars get val name nr assert equals zero vars get val name 1 assert null vars get val name 2 extractor setx path query book preface title intro extractor process assert equals zero vars get val name assert equals 1 vars get val name nr assert equals zero vars get val name 1 assert null vars get val name 2 extractor setx path query book preface title xyz extractor process assert equals default vars get val name assert equals 0 vars get val name nr assert null vars get val name 1 testattributeextraction setxpathquery assertequals val_name assertequals val_name_nr assertequals val_name _1 assertnull val_name _2 setxpathquery assertequals val_name assertequals val_name_nr assertequals val_name _1 assertnull val_name _2 setxpathquery assertequals val_name assertequals val_name_nr assertequals val_name _1 assertnull val_name _2 setxpathquery assertequals val_name assertequals val_name_nr assertnull val_name _1 public void test variable extraction throws exception extractor setx path query book preface extractor process assert equals zero vars get val name assert equals 1 vars get val name nr assert equals zero vars get val name 1 assert null vars get val name 2 extractor setx path query book page extractor process assert equals one vars get val name assert equals 2 vars get val name nr assert equals one vars get val name 1 assert equals two vars get val name 2 assert null vars get val name 3 extractor setx path query book page 2 extractor process assert equals two vars get val name assert equals 1 vars get val name nr assert equals two vars get val name 1 assert null vars get val name 2 assert null vars get val name 3 extractor setx path query book index extractor process assert equals default vars get val name assert equals 0 vars get val name nr assert null vars get val name 1 has child but child is empty extractor setx path query book a extractor process assert equals default vars get val name assert equals 1 vars get val name nr assert null vars get val name 1 has no child extractor setx path query book empty extractor process assert equals default vars get val name assert equals 1 vars get val name nr assert null vars get val name 1 testvariableextraction setxpathquery assertequals val_name assertequals val_name_nr assertequals val_name _1 assertnull val_name _2 setxpathquery assertequals val_name assertequals val_name_nr assertequals val_name _1 assertequals val_name _2 assertnull val_name _3 setxpathquery assertequals val_name assertequals val_name_nr assertequals val_name _1 assertnull val_name _2 assertnull val_name _3 setxpathquery assertequals val_name assertequals val_name_nr assertnull val_name _1 setxpathquery assertequals val_name assertequals val_name_nr assertnull val_name _1 setxpathquery assertequals val_name assertequals val_name_nr assertnull val_name _1 public void test invalid xpath throws exception extractor setx path query extractor process assert equals default vars get val name assert equals 0 vars get val name nr testinvalidxpath setxpathquery assertequals val_name assertequals val_name_nr public void test invalid document throws exception result set response data z get bytes extractor setx path query extractor process assert equals default vars get val name assert equals 0 vars get val name nr testinvaliddocument setresponsedata getbytes setxpathquery assertequals val_name assertequals val_name_nr public class test tree cloner extends junit framework test case public test tree cloner string name super name testtreecloner testcase testtreecloner public void test cloning throws exception listed hash tree original new listed hash tree generic controller controller new generic controller controller set name controller arguments args new arguments args set name args test plan plan new test plan plan add parameter server jakarta original add controller args original add plan result collector listener new result collector listener set name collector original add controller listener tree cloner cloner new tree cloner original traverse cloner listed hash tree new tree cloner get cloned tree assert true original new tree assert equals original size new tree size assert equals original get tree original get array 0 size new tree get tree new tree get array 0 size assert true original get array 0 new tree get array 0 assert equals generic controller original get array 0 get name generic controller new tree get array 0 get name assert same original get tree original get array 0 get array 1 new tree get tree new tree get array 0 get array 1 test plan cloned test plan test plan new tree get array 1 cloned test plan set running version true cloned test plan recover running version assert true plan get user defined variables as property is running version assert true cloned test plan get user defined variables as property is running version arguments vars arguments plan get user defined variables as property get object value property iterator iter collection property vars get property arguments arguments iterator while iter has next j meter property arg prop iter next assert true arg prop is running version assert true arg prop get object value instanceof argument argument arg argument arg prop get object value arg set value yahoo assert equals yahoo arg get value vars arguments cloned test plan get user defined variables as property get object value iter vars property iterator while iter has next assert true iter next is running version testcloning listedhashtree listedhashtree genericcontroller genericcontroller setname setname testplan testplan addparameter resultcollector resultcollector setname treecloner treecloner listedhashtree newtree getclonedtree asserttrue newtree assertequals newtree assertequals gettree getarray newtree gettree newtree getarray asserttrue getarray newtree getarray assertequals genericcontroller getarray getname genericcontroller newtree getarray getname assertsame gettree getarray getarray newtree gettree newtree getarray getarray testplan clonedtestplan testplan newtree getarray clonedtestplan setrunningversion clonedtestplan recoverrunningversion asserttrue getuserdefinedvariablesasproperty isrunningversion asserttrue clonedtestplan getuserdefinedvariablesasproperty isrunningversion getuserdefinedvariablesasproperty getobjectvalue propertyiterator collectionproperty getproperty hasnext jmeterproperty argprop asserttrue argprop isrunningversion asserttrue argprop getobjectvalue argprop getobjectvalue setvalue assertequals getvalue clonedtestplan getuserdefinedvariablesasproperty getobjectvalue propertyiterator hasnext asserttrue isrunningversion public class test arguments panel extends test case create a new test param name the name of the test public test arguments panel string name super name testargumentspanel testcase testargumentspanel test that adding an argument to the table results in an appropriate test element being created throws exception if an exception occurred during the test public void test argument creation throws exception arguments panel gui new arguments panel gui table model add row new argument gui table model set value at howdy 0 0 gui table model add row new argument gui table model set value at doody 0 1 assert equals argument arguments gui create test element get arguments get 0 get object value get meta data testelement testargumentcreation argumentspanel argumentspanel tablemodel addrow tablemodel setvalueat tablemodel addrow tablemodel setvalueat assertequals createtestelement getarguments getobjectvalue getmetadata public class md5 hex assertion test extends test case public md5 hex assertion test super md5hexassertiontest testcase md5hexassertiontest public md5 hex assertion test string arg0 super arg0 md5hexassertiontest public void testmd5 throws exception assert equals d41d8cd98f00b204e9800998ecf8427e md5 hex assertion bamd5 hex new byte to upper case java util locale english assertequals md5hexassertion bamd5hex touppercase public class response assertion test extends test case public response assertion test responseassertiontest testcase responseassertiontest public void set up throws malformedurl exception jmctx j meter context service get context assertion new response assertion assertion set thread context jmctx sample new sample result vars new j meter variables jmctx set variables vars jmctx set previous result sample sample set response data response data n line 2 n neof get bytes sample seturl new url http localhost sampler data sample set response code 401 sample set response headers x header abcd setup malformedurlexception jmetercontextservice getcontext responseassertion setthreadcontext sampleresult jmetervariables setvariables setpreviousresult setresponsedata getbytes setresponsecode setresponseheaders public void test response assertion equals throws exception assertion unset not type assertion set to equals type assertion set test fieldurl assertion add test string sampler label assertion add test string sampler labelx result assertion get result sample assert failed assertion set to not type assertion clear test strings assertion add test string sampler label assertion add test string sampler labelx result assertion get result sample assert passed testresponseassertionequals unsetnottype settoequalstype settestfieldurl addteststring addteststring getresult assertfailed settonottype clearteststrings addteststring addteststring getresult assertpassed public void test response assertion headers throws exception assertion unset not type assertion set to equals type assertion set test field response headers assertion add test string x header abcd assertion add test string x header abcdx result assertion get result sample assert failed assertion clear test strings assertion add test string x header abcd result assertion get result sample assert passed testresponseassertionheaders unsetnottype settoequalstype settestfieldresponseheaders addteststring addteststring getresult assertfailed clearteststrings addteststring getresult assertpassed public void test response assertion contains throws exception assertion unset not type assertion set to contains type assertion set test fieldurl assertion add test string sampler assertion add test string label assertion add test string x result assertion get result sample assert failed assertion set to not type result assertion get result sample assert failed assertion clear test strings assertion add test string r l result assertion get result sample assert passed assertion unset not type assertion set test field response data assertion clear test strings assertion add test string line 2 result assertion get result sample assert passed assertion clear test strings assertion add test string s line d eof result assertion get result sample assert passed assertion set test field response code assertion clear test strings assertion add test string 401 result assertion get result sample assert passed testresponseassertioncontains unsetnottype settocontainstype settestfieldurl addteststring addteststring addteststring getresult assertfailed settonottype getresult assertfailed clearteststrings addteststring getresult assertpassed unsetnottype settestfieldresponsedata clearteststrings addteststring getresult assertpassed clearteststrings addteststring getresult assertpassed settestfieldresponsecode clearteststrings addteststring getresult assertpassed bug 46831 check can match dollars public void test response assertion contains dollar throws exception sample set response data value id group ctl00 drp emails get bytes assertion unset not type assertion set to contains type assertion set test field response data assertion add test string value id group ctl00 drp emails result assertion get result sample assert passed testresponseassertioncontainsdollar setresponsedata drpemails getbytes unsetnottype settocontainstype settestfieldresponsedata addteststring drpemails getresult assertpassed public void test response assertion substring throws exception assertion unset not type assertion set to substring type assertion set test fieldurl assertion add test string sampler assertion add test string label assertion add test string result assertion get result sample assert failed assertion set to not type result assertion get result sample assert failed assertion clear test strings assertion add test string r l result assertion get result sample assert passed assertion unset not type assertion set test field response data assertion clear test strings assertion add test string line 2 result assertion get result sample assert passed assertion clear test strings assertion add test string line 2 n neof result assertion get result sample assert passed assertion set test field response code assertion clear test strings assertion add test string 401 result assertion get result sample assert passed testresponseassertionsubstring unsetnottype settosubstringtype settestfieldurl addteststring addteststring addteststring getresult assertfailed settonottype getresult assertfailed clearteststrings addteststring getresult assertpassed unsetnottype settestfieldresponsedata clearteststrings addteststring getresult assertpassed clearteststrings addteststring getresult assertpassed settestfieldresponsecode clearteststrings addteststring getresult assertpassed private void assert passed throws exception assert null result get failure message result get failure message assert false not expecting error result get failure message result is error assert false not expecting error result is error assert false not expecting failure result is failure assertpassed assertnull getfailuremessage getfailuremessage assertfalse getfailuremessage iserror assertfalse iserror assertfalse isfailure private void assert failed throws exception assert not null result get failure message assert false should not be response was null response was null equals result get failure message assert false not expecting error result get failure message result is error assert true expecting failure result is failure assertfailed assertnotnull getfailuremessage assertfalse getfailuremessage assertfalse getfailuremessage iserror asserttrue isfailure public void test thread safety throws exception thread threads new thread 100 for int i 0 i threads length i threads i new test thread failed 0 for int i 0 i threads length i threads i start threads running synchronized this while threads running 0 wait assert equals failed 0 testthreadsafety testthread threadsrunning threadsrunning assertequals public void run response assertion assertion new response assertion assertion set test field response data assertion set to contains type assertion add test string test pattern sample result response new sample result response set response data test string get bytes for int i 0 i 100 i assertion result result result assertion get result response if result is failure result is error failed synchronized response assertion test this threads running response assertion test this notify all responseassertion responseassertion settestfieldresponsedata settocontainstype addteststring test_pattern sampleresult sampleresult setresponsedata test_string getbytes assertionresult getresult isfailure iserror responseassertiontest threadsrunning responseassertiontest notifyall public clutil test case this command line interpreter test case clutiltestcase public clutil test case string name super name clutiltestcase public void test optional arg with space final cl option descriptor options new cl option descriptor all taint final string args new string t param a final cl args parser parser new cl args parser args options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals option count 3 size final cl option option0 cl option cl options get 0 assert equals option code option0 get descriptor get id taint opt option0 get descriptor get id assert equals option arg option0 get argument 0 null option0 get argument 0 final cl option option1 cl option cl options get 1 assert equals option1 get descriptor get id cl option text argument assert equals option1 get argument 0 param final cl option option2 cl option cl options get 2 assert equals option2 get descriptor get id all opt assert equals option2 get argument 0 null testoptionalargwithspace cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals cloption cloption cloptions assertequals getdescriptor getid taint_opt getdescriptor getid assertequals getargument getargument cloption cloption cloptions assertequals getdescriptor getid cloption text_argument assertequals getargument cloption cloption cloptions assertequals getdescriptor getid all_opt assertequals getargument public void test optional arg long final cl option descriptor options new cl option descriptor all taint check that optional args work woth long options final string args new string taint param a final cl args parser parser new cl args parser args options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals option count 3 size final cl option option0 cl option cl options get 0 assert equals option code option0 get descriptor get id taint opt option0 get descriptor get id assert equals option arg option0 get argument 0 null option0 get argument 0 final cl option option1 cl option cl options get 1 assert equals cl option text argument option1 get descriptor get id assert equals param option1 get argument 0 final cl option option2 cl option cl options get 2 assert equals option2 get descriptor get id all opt assert equals option2 get argument 0 null testoptionalarglong cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals cloption cloption cloptions assertequals getdescriptor getid taint_opt getdescriptor getid assertequals getargument getargument cloption cloption cloptions assertequals cloption text_argument getdescriptor getid assertequals getargument cloption cloption cloptions assertequals getdescriptor getid all_opt assertequals getargument public void test optional arg long equals final cl option descriptor options new cl option descriptor all taint check that optional args work woth long options final string args new string taint param a final cl args parser parser new cl args parser args options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals option count 2 size final cl option option0 cl option cl options get 0 assert equals option code option0 get descriptor get id taint opt option0 get descriptor get id assert equals option arg option0 get argument 0 param option0 get argument 0 final cl option option2 cl option cl options get 1 assert equals option2 get descriptor get id all opt assert equals option2 get argument 0 null testoptionalarglongequals cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals cloption cloption cloptions assertequals getdescriptor getid taint_opt getdescriptor getid assertequals getargument getargument cloption cloption cloptions assertequals getdescriptor getid all_opt assertequals getargument public void test short opt arg unentered before other opt final cl option descriptor options new cl option descriptor all taint final string args new string t a final cl args parser parser new cl args parser args options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals option count 2 size final cl option option0 cl option cl options get 0 assert equals option code option0 get descriptor get id taint opt option0 get descriptor get id assert equals option arg option0 get argument 0 null option0 get argument 0 final cl option option1 cl option cl options get 1 assert equals option1 get descriptor get id all opt assert equals option1 get argument 0 null testshortoptargunenteredbeforeotheropt cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals cloption cloption cloptions assertequals getdescriptor getid taint_opt getdescriptor getid assertequals getargument getargument cloption cloption cloptions assertequals getdescriptor getid all_opt assertequals getargument public void test optional args with arg short before other opt t3 a final cl option descriptor options new cl option descriptor all taint final string args new string t3 a final cl args parser parser new cl args parser args options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals size 2 final cl option option0 cl option cl options get 0 assert equals option0 get descriptor get id taint opt assert equals option0 get argument 0 3 final cl option option1 cl option cl options get 1 assert equals all opt option1 get descriptor get id assert equals null option1 get argument 0 testoptionalargswithargshortbeforeotheropt cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals cloption cloption cloptions assertequals getdescriptor getid taint_opt assertequals getargument cloption cloption cloptions assertequals all_opt getdescriptor getid assertequals getargument public void test optional args with arg short equals before other opt t3 a final cl option descriptor options new cl option descriptor all taint final string args new string t 3 a final cl args parser parser new cl args parser args options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals size 2 final cl option option0 cl option cl options get 0 assert equals option0 get descriptor get id taint opt assert equals option0 get argument 0 3 final cl option option1 cl option cl options get 1 assert equals all opt option1 get descriptor get id assert equals null option1 get argument 0 testoptionalargswithargshortequalsbeforeotheropt cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals cloption cloption cloptions assertequals getdescriptor getid taint_opt assertequals getargument cloption cloption cloptions assertequals all_opt getdescriptor getid assertequals getargument public void test optional args no arg short before other opt t a final cl option descriptor options new cl option descriptor all taint final string args new string t a final cl args parser parser new cl args parser args options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals size 2 final cl option option0 cl option cl options get 0 assert equals taint opt option0 get descriptor get id assert equals null option0 get argument 0 final cl option option1 cl option cl options get 1 assert equals all opt option1 get descriptor get id assert equals null option1 get argument 0 testoptionalargsnoargshortbeforeotheropt cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals cloption cloption cloptions assertequals taint_opt getdescriptor getid assertequals getargument cloption cloption cloptions assertequals all_opt getdescriptor getid assertequals getargument public void test full parse final cl option descriptor options new cl option descriptor you all clear1 clear2 clear3 clear5 final cl args parser parser new cl args parser arglist1 options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals size 8 assert equals cl option cl options get 0 get descriptor get id you opt assert equals cl option cl options get 1 get descriptor get id 0 assert equals cl option cl options get 2 get descriptor get id all opt assert equals cl option cl options get 3 get descriptor get id clear1 opt assert equals cl option cl options get 4 get descriptor get id clear2 opt assert equals cl option cl options get 5 get descriptor get id clear3 opt assert equals cl option cl options get 6 get descriptor get id clear5 opt assert equals cl option cl options get 7 get descriptor get id 0 testfullparse cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals cloption cloptions getdescriptor getid you_opt assertequals cloption cloptions getdescriptor getid assertequals cloption cloptions getdescriptor getid all_opt assertequals cloption cloptions getdescriptor getid clear1_opt assertequals cloption cloptions getdescriptor getid clear2_opt assertequals cloption cloptions getdescriptor getid clear3_opt assertequals cloption cloptions getdescriptor getid clear5_opt assertequals cloption cloptions getdescriptor getid public void test duplicate options dstupid idiot are all all here final cl option descriptor options new cl option descriptor define all clear1 final cl args parser parser new cl args parser arglist3 options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals size 5 assert equals cl option cl options get 0 get descriptor get id define opt assert equals cl option cl options get 1 get descriptor get id 0 assert equals cl option cl options get 2 get descriptor get id all opt assert equals cl option cl options get 3 get descriptor get id all opt assert equals cl option cl options get 4 get descriptor get id 0 testduplicateoptions cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals cloption cloptions getdescriptor getid define_opt assertequals cloption cloptions getdescriptor getid assertequals cloption cloptions getdescriptor getid all_opt assertequals cloption cloptions getdescriptor getid all_opt assertequals cloption cloptions getdescriptor getid public void test incompatable options final cl option descriptor options new cl option descriptor define all clear1 blee final cl args parser parser new cl args parser arglist4 options assert not null parser get error string final list cl options parser get arguments final int size cl options size assert equals size 5 assert equals cl option cl options get 0 get descriptor get id define opt assert equals cl option cl options get 1 get descriptor get id 0 assert equals cl option cl options get 2 get descriptor get id all opt assert equals cl option cl options get 3 get descriptor get id blee opt assert equals cl option cl options get 4 get descriptor get id 0 testincompatableoptions cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnotnull geterrorstring cloptions getarguments cloptions assertequals assertequals cloption cloptions getdescriptor getid define_opt assertequals cloption cloptions getdescriptor getid assertequals cloption cloptions getdescriptor getid all_opt assertequals cloption cloptions getdescriptor getid blee_opt assertequals cloption cloptions getdescriptor getid public void test single arg final cl option descriptor options new cl option descriptor file final cl args parser parser new cl args parser arglist5 options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals size 1 assert equals cl option cl options get 0 get descriptor get id file opt assert equals cl option cl options get 0 get argument myfile txt testsinglearg cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals cloption cloptions getdescriptor getid file_opt assertequals cloption cloptions getargument public void test single arg2 final cl option descriptor options new cl option descriptor file final cl args parser parser new cl args parser new string f check delimiters are allowed options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals 1 size assert equals file opt cl option cl options get 0 get descriptor get id assert equals cl option cl options get 0 get argument testsinglearg2 cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals file_opt cloption cloptions getdescriptor getid assertequals cloption cloptions getargument public void test single arg3 final cl option descriptor options new cl option descriptor file final cl args parser parser new cl args parser new string file check delimiters are allowed options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals 1 size assert equals file opt cl option cl options get 0 get descriptor get id assert equals cl option cl options get 0 get argument testsinglearg3 cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals file_opt cloption cloptions getdescriptor getid assertequals cloption cloptions getargument public void test single arg4 final cl option descriptor options new cl option descriptor file final cl args parser parser new cl args parser new string file myfile txt options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals 1 size assert equals file opt cl option cl options get 0 get descriptor get id assert equals myfile txt cl option cl options get 0 get argument testsinglearg4 cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals file_opt cloption cloptions getdescriptor getid assertequals cloption cloptions getargument public void test single arg5 final cl option descriptor options new cl option descriptor file final cl args parser parser new cl args parser new string f myfile txt options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals 1 size assert equals file opt cl option cl options get 0 get descriptor get id assert equals myfile txt cl option cl options get 0 get argument testsinglearg5 cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals file_opt cloption cloptions getdescriptor getid assertequals cloption cloptions getargument public void test single arg6 final cl option descriptor options new cl option descriptor file final cl args parser parser new cl args parser new string f options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals 1 size assert equals file opt cl option cl options get 0 get descriptor get id assert equals cl option cl options get 0 get argument testsinglearg6 cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals file_opt cloption cloptions getdescriptor getid assertequals cloption cloptions getargument public void test single arg7 final cl option descriptor options new cl option descriptor file final cl args parser parser new cl args parser new string file options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals 1 size assert equals file opt cl option cl options get 0 get descriptor get id assert equals cl option cl options get 0 get argument testsinglearg7 cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals file_opt cloption cloptions getdescriptor getid assertequals cloption cloptions getargument public void test single arg8 final cl option descriptor options new cl option descriptor file final cl args parser parser new cl args parser new string file options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals 1 size assert equals file opt cl option cl options get 0 get descriptor get id assert equals cl option cl options get 0 get argument testsinglearg8 cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals file_opt cloption cloptions getdescriptor getid assertequals cloption cloptions getargument public void test single arg9 final cl option descriptor options new cl option descriptor file final cl args parser parser new cl args parser new string file options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals 1 size assert equals file opt cl option cl options get 0 get descriptor get id assert equals cl option cl options get 0 get argument testsinglearg9 cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals file_opt cloption cloptions getdescriptor getid assertequals cloption cloptions getargument public void test combined args1 final cl option descriptor options new cl option descriptor blee taint final cl args parser parser new cl args parser new string bt rest options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals 3 size assert equals blee opt cl option cl options get 0 get descriptor get id assert equals taint opt cl option cl options get 1 get descriptor get id assert equals 0 cl option cl options get 2 get descriptor get id assert equals rest cl option cl options get 2 get argument testcombinedargs1 cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals blee_opt cloption cloptions getdescriptor getid assertequals taint_opt cloption cloptions getdescriptor getid assertequals cloption cloptions getdescriptor getid assertequals cloption cloptions getargument public void test combined args2 final cl option descriptor options new cl option descriptor blee taint file final cl args parser parser new cl args parser new string bt fa options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals 3 size assert equals blee opt cl option cl options get 0 get descriptor get id assert equals taint opt cl option cl options get 1 get descriptor get id assert equals file opt cl option cl options get 2 get descriptor get id assert equals a cl option cl options get 2 get argument testcombinedargs2 cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals blee_opt cloption cloptions getdescriptor getid assertequals taint_opt cloption cloptions getdescriptor getid assertequals file_opt cloption cloptions getdescriptor getid assertequals cloption cloptions getargument public void test combined args3 final cl option descriptor options new cl option descriptor blee taint file final cl args parser parser new cl args parser new string bt fa should not detect trailing option options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals 3 size assert equals blee opt cl option cl options get 0 get descriptor get id assert equals taint opt cl option cl options get 1 get descriptor get id assert equals 0 cl option cl options get 2 get descriptor get id assert equals fa cl option cl options get 2 get argument testcombinedargs3 cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals blee_opt cloption cloptions getdescriptor getid assertequals taint_opt cloption cloptions getdescriptor getid assertequals cloption cloptions getdescriptor getid assertequals cloption cloptions getargument public void test combined args4 final cl option descriptor options new cl option descriptor blee taint file final cl args parser parser new cl args parser new string bt rest fa should detect trailing option options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals 4 size assert equals blee opt cl option cl options get 0 get descriptor get id assert equals taint opt cl option cl options get 1 get descriptor get id assert equals 0 cl option cl options get 2 get descriptor get id assert equals rest cl option cl options get 2 get argument assert equals file opt cl option cl options get 3 get descriptor get id assert equals a cl option cl options get 3 get argument testcombinedargs4 cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals blee_opt cloption cloptions getdescriptor getid assertequals taint_opt cloption cloptions getdescriptor getid assertequals cloption cloptions getdescriptor getid assertequals cloption cloptions getargument assertequals file_opt cloption cloptions getdescriptor getid assertequals cloption cloptions getargument public void test2 args parse dstupid idiot are all here final cl option descriptor options new cl option descriptor define all clear1 case check final cl args parser parser new cl args parser arglist2 options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals size 5 assert equals cl option cl options get 0 get descriptor get id define opt assert equals cl option cl options get 1 get descriptor get id 0 assert equals cl option cl options get 2 get descriptor get id all opt assert equals cl option cl options get 3 get descriptor get id 0 assert equals cl option cl options get 4 get descriptor get id case check opt final cl option option cl option cl options get 0 assert equals stupid option get argument 0 assert equals idiot option get argument 1 test2argsparse cloptiondescriptor cloptiondescriptor case_check clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals cloption cloptions getdescriptor getid define_opt assertequals cloption cloptions getdescriptor getid assertequals cloption cloptions getdescriptor getid all_opt assertequals cloption cloptions getdescriptor getid assertequals cloption cloptions getdescriptor getid case_check_opt cloption cloption cloptions assertequals getargument assertequals getargument public void test2 args parse2 final cl option descriptor options new cl option descriptor define final cl args parser parser new cl args parser new string define a b c d e f check is allowed in arg2 options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals 1 size assert equals define opt cl option cl options get 0 get descriptor get id final cl option option cl option cl options get 0 assert equals a b c option get argument 0 assert equals d e f option get argument 1 test2argsparse2 cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals define_opt cloption cloptions getdescriptor getid cloption cloption cloptions assertequals getargument assertequals getargument public void test2 args parse3 final cl option descriptor options new cl option descriptor define final cl args parser parser new cl args parser new string d a b c g e f options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals 1 size assert equals define opt cl option cl options get 0 get descriptor get id final cl option option cl option cl options get 0 assert equals a b c option get argument 0 assert equals g e f option get argument 1 test2argsparse3 cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals define_opt cloption cloptions getdescriptor getid cloption cloption cloptions assertequals getargument assertequals getargument public void test2 args parse4 final cl option descriptor options new cl option descriptor define many final cl args parser parser new cl args parser new string dval1 1 d val2 2 define val 3 3 define val4 4 options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals 4 size for int i 0 i size i assert equals define opt cl option cl options get i get descriptor get id cl option option option cl option cl options get 0 assert equals val1 option get argument 0 assert equals 1 option get argument 1 option cl option cl options get 1 assert equals val2 option get argument 0 assert equals 2 option get argument 1 option cl option cl options get 2 assert equals val 3 option get argument 0 assert equals 3 option get argument 1 option cl option cl options get 3 assert equals val4 option get argument 0 assert equals 4 option get argument 1 test2argsparse4 cloptiondescriptor cloptiondescriptor define_many clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals define_opt cloption cloptions getdescriptor getid cloption cloption cloptions assertequals getargument assertequals getargument cloption cloptions assertequals getargument assertequals getargument cloption cloptions assertequals getargument assertequals getargument cloption cloptions assertequals getargument assertequals getargument public void test part parse final cl option descriptor options new cl option descriptor you final parser control control new abstract parser control public boolean is finished int last option code return last option code you opt final cl args parser parser new cl args parser arglist1 options control assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals size 1 assert equals cl option cl options get 0 get descriptor get id you opt testpartparse cloptiondescriptor cloptiondescriptor parsercontrol abstractparsercontrol isfinished lastoptioncode lastoptioncode you_opt clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals cloption cloptions getdescriptor getid you_opt final parser control control new abstract parser control public boolean is finished int last option code return last option code you opt parsercontrol abstractparsercontrol isfinished lastoptioncode lastoptioncode you_opt public void test2 part parse final cl option descriptor options1 new cl option descriptor you final cl option descriptor options2 new cl option descriptor all clear1 clear2 clear3 clear5 final parser control control1 new abstract parser control public boolean is finished int last option code return last option code you opt final cl args parser parser1 new cl args parser arglist1 options1 control1 assert null parser1 get error string parser1 get error string final list cl options1 parser1 get arguments final int size1 cl options1 size assert equals size1 1 assert equals cl option cl options1 get 0 get descriptor get id you opt final cl args parser parser2 new cl args parser parser1 get unparsed args options2 assert null parser2 get error string parser2 get error string final list cl options2 parser2 get arguments final int size2 cl options2 size assert equals size2 7 assert equals cl option cl options2 get 0 get descriptor get id 0 assert equals cl option cl options2 get 1 get descriptor get id all opt assert equals cl option cl options2 get 2 get descriptor get id clear1 opt assert equals cl option cl options2 get 3 get descriptor get id clear2 opt assert equals cl option cl options2 get 4 get descriptor get id clear3 opt assert equals cl option cl options2 get 5 get descriptor get id clear5 opt assert equals cl option cl options2 get 6 get descriptor get id 0 test2partparse cloptiondescriptor cloptiondescriptor cloptiondescriptor cloptiondescriptor parsercontrol abstractparsercontrol isfinished lastoptioncode lastoptioncode you_opt clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions1 getarguments cloptions1 assertequals assertequals cloption cloptions1 getdescriptor getid you_opt clargsparser clargsparser getunparsedargs assertnull geterrorstring geterrorstring cloptions2 getarguments cloptions2 assertequals assertequals cloption cloptions2 getdescriptor getid assertequals cloption cloptions2 getdescriptor getid all_opt assertequals cloption cloptions2 getdescriptor getid clear1_opt assertequals cloption cloptions2 getdescriptor getid clear2_opt assertequals cloption cloptions2 getdescriptor getid clear3_opt assertequals cloption cloptions2 getdescriptor getid clear5_opt assertequals cloption cloptions2 getdescriptor getid final parser control control1 new abstract parser control public boolean is finished int last option code return last option code you opt parsercontrol abstractparsercontrol isfinished lastoptioncode lastoptioncode you_opt public void test2 part partial parse final cl option descriptor options1 new cl option descriptor you all clear1 final cl option descriptor options2 new cl option descriptor final parser control control1 new abstract parser control public boolean is finished final int last option code return last option code clear1 opt final cl args parser parser1 new cl args parser arglist1 options1 control1 assert null parser1 get error string parser1 get error string final list cl options1 parser1 get arguments final int size1 cl options1 size assert equals size1 4 assert equals cl option cl options1 get 0 get descriptor get id you opt assert equals cl option cl options1 get 1 get descriptor get id 0 assert equals cl option cl options1 get 2 get descriptor get id all opt assert equals cl option cl options1 get 3 get descriptor get id clear1 opt assert true parser1 get unparsed args 0 equals ler final cl args parser parser2 new cl args parser parser1 get unparsed args options2 assert null parser2 get error string parser2 get error string final list cl options2 parser2 get arguments final int size2 cl options2 size assert equals size2 2 assert equals cl option cl options2 get 0 get descriptor get id 0 assert equals cl option cl options2 get 1 get descriptor get id 0 test2partpartialparse cloptiondescriptor cloptiondescriptor cloptiondescriptor cloptiondescriptor parsercontrol abstractparsercontrol isfinished lastoptioncode lastoptioncode clear1_opt clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions1 getarguments cloptions1 assertequals assertequals cloption cloptions1 getdescriptor getid you_opt assertequals cloption cloptions1 getdescriptor getid assertequals cloption cloptions1 getdescriptor getid all_opt assertequals cloption cloptions1 getdescriptor getid clear1_opt asserttrue getunparsedargs clargsparser clargsparser getunparsedargs assertnull geterrorstring geterrorstring cloptions2 getarguments cloptions2 assertequals assertequals cloption cloptions2 getdescriptor getid assertequals cloption cloptions2 getdescriptor getid final parser control control1 new abstract parser control public boolean is finished final int last option code return last option code clear1 opt parsercontrol abstractparsercontrol isfinished lastoptioncode lastoptioncode clear1_opt public void test duplicates fail final cl option descriptor options new cl option descriptor you all clear1 clear2 clear3 clear5 final cl args parser parser new cl args parser arglist1 options assert null parser get error string parser get error string testduplicatesfail cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring public void test incomplete2 args dstupid final cl option descriptor options new cl option descriptor define final cl args parser parser new cl args parser new string dstupid options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals size 1 final cl option option cl option cl options get 0 assert equals option get descriptor get id define opt assert equals option get argument 0 stupid assert equals option get argument 1 testincomplete2args cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals cloption cloption cloptions assertequals getdescriptor getid define_opt assertequals getargument assertequals getargument public void test incomplete2 args mixed dstupid c final cl option descriptor options new cl option descriptor define clear1 final string args new string dstupid c final cl args parser parser new cl args parser args options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals size 2 assert equals cl option cl options get 1 get descriptor get id clear1 opt final cl option option cl option cl options get 0 assert equals option get descriptor get id define opt assert equals option get argument 0 stupid assert equals option get argument 1 testincomplete2argsmixed cloptiondescriptor cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals cloption cloptions getdescriptor getid clear1_opt cloption cloption cloptions assertequals getdescriptor getid define_opt assertequals getargument assertequals getargument public void test incomplete2 args mixed no eq dstupid c final cl option descriptor options new cl option descriptor define clear1 final string args new string d stupid c final cl args parser parser new cl args parser args options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size assert equals size 2 assert equals cl option cl options get 1 get descriptor get id clear1 opt final cl option option cl option cl options get 0 assert equals option get descriptor get id define opt assert equals option get argument 0 stupid assert equals option get argument 1 testincomplete2argsmixednoeq cloptiondescriptor cloptiondescriptor dstupid clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions assertequals assertequals cloption cloptions getdescriptor getid clear1_opt cloption cloption cloptions assertequals getdescriptor getid define_opt assertequals getargument assertequals getargument test the get argument by id and get argument by name lookup methods public void test argument lookup final string args f testarg final cl option descriptor options file final cl args parser parser new cl args parser args options assert null parser get error string parser get error string cl option option by id parser get argument by id file opt assert not null option by id assert equals file opt option by id get descriptor get id assert equals testarg option by id get argument cl option option by name parser get argument by name file get name assert not null option by name assert equals file opt option by name get descriptor get id assert equals testarg option by name get argument getargumentbyid getargumentbyname testargumentlookup cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloption optionbyid getargumentbyid file_opt assertnotnull optionbyid assertequals file_opt optionbyid getdescriptor getid assertequals optionbyid getargument cloption optionbyname getargumentbyname getname assertnotnull optionbyname assertequals file_opt optionbyname getdescriptor getid assertequals optionbyname getargument test that you can have null long forms public void test null long form final cl option descriptor test new cl option descriptor null cl option descriptor argument disallowed n test null long form final string args n testarg final cl option descriptor options test final cl args parser parser new cl args parser args options assert null parser get error string parser get error string final cl option option byid parser get argument by id n assert not null option byid assert equals n option byid get descriptor get id final cl option option by name parser get argument by name file get name assert null looking for non existent option by name option by name testnulllongform cloptiondescriptor cloptiondescriptor cloptiondescriptor argument_disallowed cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloption optionbyid getargumentbyid assertnotnull optionbyid assertequals optionbyid getdescriptor getid cloption optionbyname getargumentbyname getname assertnull optionbyname test that you can have null descriptions public void test null description final cl option descriptor test new cl option descriptor nulltest cl option descriptor argument disallowed n null final string args n testarg final cl option descriptor options test final cl args parser parser new cl args parser args options assert null parser get error string parser get error string final cl option option byid parser get argument by id n assert not null option byid assert equals n option byid get descriptor get id final string buffer sb cl util describe options options final string line separator system get property line separator assert equals testing display of null description t n nulltest line separator sb to string testnulldescription cloptiondescriptor cloptiondescriptor cloptiondescriptor argument_disallowed cloptiondescriptor clargsparser clargsparser assertnull geterrorstring geterrorstring cloption optionbyid getargumentbyid assertnotnull optionbyid assertequals optionbyid getdescriptor getid stringbuffer clutil describeoptions lineseparator getproperty assertequals lineseparator tostring public void test combinations throws exception check new string check new string none 0 0 0 canonical form check new string one a one a 1b 1 c 1 d 1 a 1 a 1 b 1 c 1 d check new string 2n v 2 n v 2 n v 2 n v check new string two n v two n v 2 n v 2 n v test optional arguments check new string a separate argument b c a b c check new string optional a ok optional b should treat b as separate optional should have no arg a b testcombinations private void check string args string canon final cl args parser parser new cl args parser args options assert null parser get error string parser get error string final list cl options parser get arguments final int size cl options size string buffer sb new string buffer for int i 0 i size i if i 0 sb append sb append cl option cl options get i to short string assert equals canonical form size canon sb to string clargsparser clargsparser assertnull geterrorstring geterrorstring cloptions getarguments cloptions stringbuffer stringbuffer cloption cloptions toshortstring assertequals tostring public void initialize bsf manager mgr string lang vector declared beans throws bsf exception super initialize mgr lang declared beans jc jexl helper create context for int i 0 i declared beans size i bsf declared bean bean bsf declared bean declared beans element at i jc get vars put bean name bean bean bsfmanager declaredbeans bsfexception declaredbeans jexlhelper createcontext declaredbeans bsfdeclaredbean bsfdeclaredbean declaredbeans elementat getvars public void terminate if jc null jc get vars clear jc null getvars public void declare bean bsf declared bean bean throws bsf exception jc get vars put bean name bean bean declarebean bsfdeclaredbean bsfexception getvars public void undeclare bean bsf declared bean bean throws bsf exception jc get vars remove bean name undeclarebean bsfdeclaredbean bsfexception getvars public object eval string file name int line no int col no object expr throws bsf exception if expr null return null try script j expr null if expr instanceof file j expr script factory create script file expr else if expr instanceof url j expr script factory create script url expr else j expr script factory create script string expr return j expr execute jc catch exception e todo better messages throw new bsf exception e get message filename lineno colno bsfexception jexpr jexpr scriptfactory createscript jexpr scriptfactory createscript jexpr scriptfactory createscript jexpr bsfexception getmessage public void exec string file name int line no int col no object script throws bsf exception if script null return try script j expr null if script instanceof file j expr script factory create script file script else if script instanceof url j expr script factory create script url script else j expr script factory create script string script j expr execute jc catch exception e throw new bsf exception e get message filename lineno colno bsfexception jexpr jexpr scriptfactory createscript jexpr scriptfactory createscript jexpr scriptfactory createscript jexpr bsfexception getmessage public void iexec string file name int line no int col no object script throws bsf exception exec file name line no col no script filename lineno colno bsfexception filename lineno colno public object call object object string name object args throws bsf exception try class types new class args length for int i 0 i args length i types i args i get class method m object get class get method name types return m invoke object args catch exception e throw new bsf exception e get message bsfexception getclass getclass getmethod bsfexception getmessage return an object from an extension param object object on which to make the call ignored param method the name of the method to call param args an array of arguments to be passed to the extension which may be either vectors of nodes or strings public object call object object string method object args throws bsf exception object retval null context cx try cx context enter remind convert arg list vectors here object fun global get method global note source and line arguments are nonsense in a call any way to make these arguments sensible if fun scriptable not found throw new evaluator exception function method not found none 0 cx set optimization level 1 cx set generating debug false cx set generating source false cx set optimization level 0 cx set debugger null null retval function fun call cx global global args script runtime call cx fun global args global if retval instanceof wrapper retval wrapper retval unwrap catch throwable t handle error t finally context exit return retval bsfexception not_found evaluatorexception setoptimizationlevel setgeneratingdebug setgeneratingsource setoptimizationlevel setdebugger scriptruntime handleerror public void declare bean bsf declared bean bean throws bsf exception if bean bean instanceof number bean bean null bean bean instanceof string bean bean instanceof boolean global put bean name global bean bean else must wrap non scriptable objects before presenting to rhino scriptable wrapped context to object bean bean global global put bean name global wrapped declarebean bsfdeclaredbean bsfexception toobject this is used by an application to evaluate a string containing some expression public object eval string source int line no int column no object oscript throws bsf exception string script text oscript to string object retval null context cx try cx context enter cx set optimization level 1 cx set generating debug false cx set generating source false cx set optimization level 0 cx set debugger null null retval cx evaluate string global script text source line no null if retval instanceof native java object retval native java object retval unwrap catch throwable t includes java script exception rethrows errors handle error t finally context exit return retval lineno columnno bsfexception scripttext tostring setoptimizationlevel setgeneratingdebug setgeneratingsource setoptimizationlevel setdebugger evaluatestring scripttext lineno nativejavaobject nativejavaobject javascriptexception handleerror private void handle error throwable t throws bsf exception if t instanceof wrapped exception t wrapped exception t get wrapped exception string message null throwable target t if t instanceof java script exception message t get localized message is it an exception wrapped in a java script exception object value java script exception t get value if value instanceof throwable likely a wrapped exception from a live connect call display its stack trace as a diagnostic target throwable value else if t instanceof evaluator exception t instanceof security exception message t get localized message else if t instanceof runtime exception message internal error t to string else if t instanceof stack overflow error message stack overflow if message null message t to string if t instanceof error t instanceof stack overflow error re throw errors because we re supposed to let the jvm see it don t re throw stack overflows because we know we ve corrected the situation by aborting the loop and a long stacktrace would end up on the user s console throw error t else throw new bsf exception bsf exception reason other error java script error message target handleerror bsfexception wrappedexception wrappedexception getwrappedexception javascriptexception getlocalizedmessage javascriptexception javascriptexception getvalue liveconnect evaluatorexception securityexception getlocalizedmessage runtimeexception tostring stackoverflowerror tostring stackoverflowerror stackoverflows bsfexception bsfexception reason_other_error javascript initialize the engine put the manager into the context manager map hashtable too public void initialize bsf manager mgr string lang vector declared beans throws bsf exception super initialize mgr lang declared beans initialize context and global scope object try context cx context enter global new importer top level cx scriptable bsf context to object new bsf functions mgr this global global put bsf global bsf for iterator it declared beans iterator it has next declare bean bsf declared bean it next catch throwable t finally context exit bsfmanager declaredbeans bsfexception declaredbeans importertoplevel toobject bsffunctions declaredbeans hasnext declarebean bsfdeclaredbean public void undeclare bean bsf declared bean bean throws bsf exception global delete bean name undeclarebean bsfdeclaredbean bsfexception returns the converter version used to check for possible incompatibilities public static string get version return revision 674365 non nls 1 getversion see com thoughtworks xstream converters converter can convert java lang class public boolean can convert class arg0 return arg0 equals collection property class arg0 equals map property class canconvert canconvert collectionproperty mapproperty public void marshal object arg0 hierarchical stream writer writer marshalling context context multi property prop multi property arg0 writer add attribute att name conversion help encode prop get name property iterator iter prop iterator while iter has next write item iter next context writer hierarchicalstreamwriter marshallingcontext multiproperty multiproperty addattribute att_name conversionhelp getname propertyiterator hasnext writeitem public object unmarshal hierarchical stream reader reader unmarshalling context context multi property prop multi property create collection context get required type prop set name conversion help decode reader get attribute att name while reader has more children reader move down j meter property sub prop j meter property read item reader context prop prop add property sub prop reader move up return prop hierarchicalstreamreader unmarshallingcontext multiproperty multiproperty createcollection getrequiredtype setname conversionhelp getattribute att_name hasmorechildren movedown jmeterproperty subprop jmeterproperty readitem addproperty subprop moveup param arg0 public multi property converter mapper arg0 super arg0 multipropertyconverter returns the converter version used to check for possible incompatibilities public static string get version return revision 674365 non nls 1 getversion see com thoughtworks xstream converters converter can convert java lang class public boolean can convert class arg0 return arg0 equals test element property class canconvert canconvert testelementproperty public void marshal object arg0 hierarchical stream writer writer marshalling context context test element property prop test element property arg0 writer add attribute conversion help att name conversion help encode prop get name class clazz prop get object value get class writer add attribute conversion help att element type test format22 mapper serialized class clazz clazz get name if test format22 test element te test element prop get object value conversion help save special properties te writer property iterator iter prop iterator while iter has next j meter property jmp iter next skip special properties if required if test format22 conversion help is special property jmp get name don t save empty comments if test element comments equals jmp get name jmp get string value length 0 write item jmp context writer todo clazz is probably always the same as testclass hierarchicalstreamwriter marshallingcontext testelementproperty testelementproperty addattribute conversionhelp att_name conversionhelp getname getobjectvalue getclass addattribute conversionhelp att_element_type testformat22 serializedclass getname testformat22 testelement testelement getobjectvalue conversionhelp savespecialproperties propertyiterator hasnext jmeterproperty testformat22 conversionhelp isspecialproperty getname testelement getname getstringvalue writeitem public object unmarshal hierarchical stream reader reader unmarshalling context context try test element property prop test element property create collection context get required type prop set name conversion help decode reader get attribute conversion help att name string element reader get attribute conversion help att element type boolean is header header classname equals element prop set object value mapper real class element new instance always decode test element te test element prop get object value no need to check version just process the attributes if present conversion help restore special properties te reader while reader has more children reader move down j meter property sub prop j meter property read item reader context prop if is header string name sub prop get name if test element name equals name sub prop set name header name non nls 1 must be same as header hname but that is built later prop add property sub prop reader move up return prop catch exception e log error couldn t unmarshall test element property e return new test element property error new config test element non nls 1 hierarchicalstreamreader unmarshallingcontext testelementproperty testelementproperty createcollection getrequiredtype setname conversionhelp getattribute conversionhelp att_name getattribute conversionhelp att_element_type isheader header_classname setobjectvalue realclass newinstance testelement testelement getobjectvalue conversionhelp restorespecialproperties hasmorechildren movedown jmeterproperty subprop jmeterproperty readitem isheader subprop getname testelement subprop setname addproperty subprop moveup testelementproperty testelementproperty configtestelement param arg0 public test element property converter mapper arg0 super arg0 testelementpropertyconverter returns the converter version used to check for possible incompatibilities public static string get version return revision 674365 non nls 1 getversion see com thoughtworks xstream converters converter can convert java lang class public boolean can convert class arg0 return test element class is assignable from arg0 canconvert canconvert testelement isassignablefrom public void marshal object arg0 hierarchical stream writer writer marshalling context context test element el test element arg0 if test format22 conversion help save special properties el writer property iterator iter el property iterator while iter has next j meter property jmp iter next skip special properties if required if test format22 conversion help is special property jmp get name don t save empty comments except for the test plan to maintain compatibility if test element comments equals jmp get name jmp get string value length 0 el get class equals test plan class write item jmp context writer hierarchicalstreamwriter marshallingcontext testelement testelement testformat22 conversionhelp savespecialproperties propertyiterator propertyiterator hasnext jmeterproperty testformat22 conversionhelp isspecialproperty getname testplan testelement getname getstringvalue getclass testplan writeitem public object unmarshal hierarchical stream reader reader unmarshalling context context string class attribute reader get attribute conversion help att class class type if class attribute null type mapper real class reader get node name else type mapper real class class attribute try test element el test element type new instance no need to check version just process the attributes if present conversion help restore special properties el reader while reader has more children reader move down j meter property prop j meter property read item reader context el el set property prop reader move up return el catch exception e log error test element not instantiable type e return null hierarchicalstreamreader unmarshallingcontext classattribute getattribute conversionhelp att_class classattribute realclass getnodename realclass classattribute testelement testelement newinstance conversionhelp restorespecialproperties hasmorechildren movedown jmeterproperty jmeterproperty readitem setproperty moveup testelement param arg0 public test element converter mapper arg0 super arg0 testelementconverter returns the converter version used to check for possible incompatibilities public static string get version return revision 674365 non nls 1 getversion see com thoughtworks xstream converters converter can convert java lang class public boolean can convert class arg0 return hash tree class is assignable from arg0 canconvert canconvert hashtree isassignablefrom public void marshal object arg0 hierarchical stream writer writer marshalling context context hash tree tree hash tree arg0 iterator iter tree list iterator while iter has next object item iter next write item item context writer write item tree get tree item context writer hierarchicalstreamwriter marshallingcontext hashtree hashtree hasnext writeitem writeitem gettree public object unmarshal hierarchical stream reader reader unmarshalling context context boolean is key true object current null hash tree tree hash tree create collection context get required type while reader has more children reader move down object item read item reader context tree if is key tree add item current item is key false else tree set current hash tree item is key true reader move up return tree hierarchicalstreamreader unmarshallingcontext iskey hashtree hashtree createcollection getrequiredtype hasmorechildren movedown readitem iskey iskey hashtree iskey moveup param arg0 public hash tree converter mapper arg0 super arg0 hashtreeconverter returns the converter version used to check for possible incompatibilities public static string get version return revision 712398 non nls 1 getversion param arg0 public test result wrapper converter mapper arg0 super arg0 testresultwrapperconverter see com thoughtworks xstream converters converter can convert java lang class public boolean can convert class arg0 return arg0 equals test result wrapper class canconvert canconvert testresultwrapper com thoughtworks xstream converters marshalling context public void marshal object arg0 hierarchical stream writer arg1 marshalling context arg2 not used as the test result element is generated by the result collector class marshallingcontext hierarchicalstreamwriter marshallingcontext testresult resultcollector read test results from jtl files and pass them to the visualiser directly if the result collector helper object is defined then pass the samples to that rather than adding them to the test result wrapper return the test result wrapper may be empty see com thoughtworks xstream converters converter unmarshal com thoughtworks xstream io hierarchical stream reader com thoughtworks xstream converters unmarshalling context public object unmarshal hierarchical stream reader reader unmarshalling context context test result wrapper results new test result wrapper collection samples new array list string ver reader get attribute version non nls 1 if ver null ver length 0 ver 1 0 non nls 1 results set version ver conversion help set in version ver make sure decoding follows input file final result collector helper result collector helper result collector helper context get save service resultcollector helper object while reader has more children reader move down sample result sample sample result read item reader context results if result collector helper null result collector helper add sample else samples add sample reader move up results set sample results samples return results resultcollector hierarchicalstreamreader unmarshallingcontext hierarchicalstreamreader unmarshallingcontext testresultwrapper testresultwrapper arraylist getattribute setversion conversionhelp setinversion resultcollectorhelper resultcollectorhelper resultcollectorhelper saveservice resultcollector_helper_object hasmorechildren movedown sampleresult sampleresult readitem resultcollectorhelper resultcollectorhelper moveup setsampleresults returns the converter version used to check for possible incompatibilities public static string get version return revision 674365 non nls 1 getversion see com thoughtworks xstream converters converter can convert java lang class public boolean can convert class arg0 return sample result class equals arg0 canconvert canconvert sampleresult public void marshal object obj hierarchical stream writer writer marshalling context context sample result res sample result obj sample save configuration save res get save config set attributes writer context res save save assertions writer context res save save sub results writer context res save save response headers writer context res save save request headers writer context res save save response data writer context res save save sampler data writer context res save hierarchicalstreamwriter marshallingcontext sampleresult sampleresult samplesaveconfiguration getsaveconfig setattributes saveassertions savesubresults saveresponseheaders saverequestheaders saveresponsedata savesamplerdata param writer param res param save protected void save sampler data hierarchical stream writer writer marshalling context context sample result res sample save configuration save if save save sampler data res write string writer tag sampler data res get sampler data if save save url final url url res geturl if url null write item url context writer savesamplerdata hierarchicalstreamwriter marshallingcontext sampleresult samplesaveconfiguration savesamplerdata writestring tag_sampler_data getsamplerdata saveurl writeitem param writer param res param save protected void save response data hierarchical stream writer writer marshalling context context sample result res sample save configuration save if save save response data res writer start node tag response data writer add attribute att class java lang string try if sample result text equals res get data type writer set value new string res get response data res get data encoding with default otherwise don t save anything no point catch unsupported encoding exception e writer set value unsupported encoding in response data can t record writer end node if save save file name writer start node tag response file writer add attribute att class java lang string writer set value res get result file name writer end node saveresponsedata hierarchicalstreamwriter marshallingcontext sampleresult samplesaveconfiguration saveresponsedata startnode tag_response_data addattribute att_class java_lang_string sampleresult getdatatype setvalue getresponsedata getdataencodingwithdefault unsupportedencodingexception setvalue endnode savefilename startnode tag_response_file addattribute att_class java_lang_string setvalue getresultfilename endnode param writer param res param save protected void save request headers hierarchical stream writer writer marshalling context context sample result res sample save configuration save if save save request headers write string writer tag request header res get request headers saverequestheaders hierarchicalstreamwriter marshallingcontext sampleresult samplesaveconfiguration saverequestheaders writestring tag_request_header getrequestheaders param writer param res param save protected void save response headers hierarchical stream writer writer marshalling context context sample result res sample save configuration save if save save response headers write string writer tag response header res get response headers saveresponseheaders hierarchicalstreamwriter marshallingcontext sampleresult samplesaveconfiguration saveresponseheaders writestring tag_response_header getresponseheaders param writer param context param res param save protected void save sub results hierarchical stream writer writer marshalling context context sample result res sample save configuration save if save save subresults sample result sub results res get sub results for int i 0 i sub results length i sub results i set save config save write item sub results i context writer savesubresults hierarchicalstreamwriter marshallingcontext sampleresult samplesaveconfiguration savesubresults sampleresult subresults getsubresults subresults subresults setsaveconfig writeitem subresults param writer param context param res param save protected void save assertions hierarchical stream writer writer marshalling context context sample result res sample save configuration save if save save assertions assertion result assertion results res get assertion results for int i 0 i assertion results length i write item assertion results i context writer saveassertions hierarchicalstreamwriter marshallingcontext sampleresult samplesaveconfiguration saveassertions assertionresult assertionresults getassertionresults assertionresults writeitem assertionresults param writer param res param save protected void set attributes hierarchical stream writer writer marshalling context context sample result res sample save configuration save if save save time writer add attribute att time long to string res get time if save save latency writer add attribute att latency long to string res get latency if save save timestamp writer add attribute att time stamp long to string res get time stamp if save save success writer add attribute att success boolean to string res is successful if save save label writer add attribute att label conversion help encode res get sample label if save save code writer add attribute att response code conversion help encode res get response code if save save message writer add attribute att response message conversion help encode res get response message if save save thread name writer add attribute att threadname conversion help encode res get thread name if save save data type writer add attribute att data type conversion help encode res get data type if save save encoding writer add attribute att data encoding conversion help encode res get data encoding no default if save save bytes writer add attribute att bytes string value of res get bytes if save save sample count writer add attribute att sample count string value of res get sample count writer add attribute att error count string value of res get error count if save save thread counts writer add attribute att grp thrds string value of res get group threads writer add attribute att all thrds string value of res get all threads sample event event sample event context get save service sample event object if save save hostname if event null writer add attribute att hostname event get hostname if event null for int i 0 i sample event get var count i writer add attribute sample event get var name i conversion help encode event get var value i setattributes hierarchicalstreamwriter marshallingcontext sampleresult samplesaveconfiguration savetime addattribute att_time tostring gettime savelatency addattribute att_latency tostring getlatency savetimestamp addattribute att_time_stamp tostring gettimestamp savesuccess addattribute att_success tostring issuccessful savelabel addattribute att_label conversionhelp getsamplelabel savecode addattribute att_response_code conversionhelp getresponsecode savemessage addattribute att_response_message conversionhelp getresponsemessage savethreadname addattribute att_threadname conversionhelp getthreadname savedatatype addattribute att_data_type conversionhelp getdatatype saveencoding addattribute att_data_encoding conversionhelp getdataencodingnodefault savebytes addattribute att_bytes valueof getbytes savesamplecount addattribute att_sample_count valueof getsamplecount addattribute att_error_count valueof geterrorcount savethreadcounts addattribute att_grp_thrds valueof getgroupthreads addattribute att_all_thrds valueof getallthreads sampleevent sampleevent saveservice sample_event_object savehostname addattribute att_hostname gethostname sampleevent getvarcount addattribute sampleevent getvarname conversionhelp getvarvalue param writer param tag param value protected void write string hierarchical stream writer writer string tag string value if value null writer start node tag writer add attribute att class java lang string writer set value value writer end node writestring hierarchicalstreamwriter startnode addattribute att_class java_lang_string setvalue endnode public object unmarshal hierarchical stream reader reader unmarshalling context context sample result res sample result create collection context get required type retrieve attributes reader context res while reader has more children reader move down object sub item read item reader context res retrieve item reader context res sub item reader move up if we have a file but no data then read the file string result file name res get result file name if result file name length 0 res get response data length 0 read file result file name res return res hierarchicalstreamreader unmarshallingcontext sampleresult sampleresult createcollection getrequiredtype retrieveattributes hasmorechildren movedown subitem readitem retrieveitem subitem moveup resultfilename getresultfilename resultfilename getresponsedata readfile resultfilename param reader param context param res return true if the item was processed for http result converter protected boolean retrieve item hierarchical stream reader reader unmarshalling context context sample result res object sub item string node name reader get node name if sub item instanceof assertion result res add assertion result assertion result sub item else if sub item instanceof sample result res store sub result sample result sub item else if node name equals tag response header res set response headers string sub item else if node name equals tag request header res set request headers string sub item else if node name equals tag response data final string response data string sub item if response data length 0 final string data encoding res get data encoding with default try res set response data response data get bytes data encoding catch unsupported encoding exception e res set response data can t support the char set data encoding get bytes res set data type sample result text else if node name equals tag sampler data res set sampler data string sub item else if node name equals tag response file res set result file name string sub item don t try restoring the url todo wy not else return false return true httpresultconverter retrieveitem hierarchicalstreamreader unmarshallingcontext sampleresult subitem nodename getnodename subitem assertionresult addassertionresult assertionresult subitem subitem sampleresult storesubresult sampleresult subitem nodename tag_response_header setresponseheaders subitem nodename tag_request_header setrequestheaders subitem nodename tag_response_data responsedata subitem responsedata dataencoding getdataencodingwithdefault setresponsedata responsedata getbytes dataencoding unsupportedencodingexception setresponsedata dataencoding getbytes setdatatype sampleresult nodename tag_sampler_data setsamplerdata subitem nodename tag_response_file setresultfilename subitem param reader param res protected void retrieve attributes hierarchical stream reader reader unmarshalling context context sample result res res set sample label conversion help decode reader get attribute att label res set data encoding conversion help decode reader get attribute att data encoding res set data type conversion help decode reader get attribute att data type string oldrc reader get attribute att response code old if oldrc null res set response code conversion help decode oldrc else res set response code conversion help decode reader get attribute att response code res set response message conversion help decode reader get attribute att response message res set successful converter get boolean reader get attribute att success true res set thread name conversion help decode reader get attribute att threadname res set stamp and time converter get long reader get attribute att time stamp converter get long reader get attribute att time res set latency converter get long reader get attribute att latency res set bytes converter get int reader get attribute att bytes res set sample count converter get int reader get attribute att sample count 1 default is 1 res set error count converter get int reader get attribute att error count 0 default is 0 res set group threads converter get int reader get attribute att grp thrds res set all threads converter get int reader get attribute att all thrds retrieveattributes hierarchicalstreamreader unmarshallingcontext sampleresult setsamplelabel conversionhelp getattribute att_label setdataencoding conversionhelp getattribute att_data_encoding setdatatype conversionhelp getattribute att_data_type getattribute att_response_code_old setresponsecode conversionhelp setresponsecode conversionhelp getattribute att_response_code setresponsemessage conversionhelp getattribute att_response_message setsuccessful getboolean getattribute att_success setthreadname conversionhelp getattribute att_threadname setstampandtime getlong getattribute att_time_stamp getlong getattribute att_time setlatency getlong getattribute att_latency setbytes getint getattribute att_bytes setsamplecount getint getattribute att_sample_count seterrorcount getint getattribute att_error_count setgroupthreads getint getattribute att_grp_thrds setallthreads getint getattribute att_all_thrds protected void read file string result file name sample result res file in null file input stream fis null try in new file result file name fis new file input stream in byte array output stream outstream new byte array output stream res get bytes byte buffer new byte 4096 int len while len fis read buffer 0 outstream write buffer 0 len outstream close res set response data outstream to byte array catch file not found exception e log warn e get localized message catch io exception e log warn e get localized message finally io utils close quietly fis readfile resultfilename sampleresult fileinputstream resultfilename fileinputstream bytearrayoutputstream bytearrayoutputstream getbytes setresponsedata tobytearray filenotfoundexception getlocalizedmessage ioexception getlocalizedmessage ioutils closequietly param arg0 public sample result converter mapper arg0 super arg0 sampleresultconverter static class my wrapper extends mapper wrapper public my wrapper mapper wrapped super wrapped mywrapper mapperwrapper mywrapper public boolean should serialize member class defined in string field name if sample save configuration class defined in return true these are new fields not saved unless true if field name equals node bytes return false if field name equals node url return false if field name equals node filename return false if field name equals node hostname return false if field name equals node thread count return false if field name equals node sample count return false these fields are not currently saved or restored if field name equals node delimiter return false if field name equals node printms return false return true shouldserializemember definedin fieldname samplesaveconfiguration definedin fieldname node_bytes fieldname node_url fieldname node_filename fieldname node_hostname fieldname node_thread_count fieldname node_sample_count fieldname node_delimiter fieldname node_printms public sample save configuration converter mapper arg0 super new my wrapper arg0 rp samplesaveconfigurationconverter mywrapper returns the converter version used to check for possible incompatibilities public static string get version return revision 674365 non nls 1 getversion see com thoughtworks xstream converters converter can convert java lang class public boolean can convert class arg0 return arg0 equals sample save configuration class canconvert canconvert samplesaveconfiguration public void marshal object obj hierarchical stream writer writer marshalling context context super marshal obj writer context save most things sample save configuration prop sample save configuration obj save the new fields but only if they are not the default create node writer prop save bytes node bytes create node writer prop save url node url create node writer prop save file name node filename create node writer prop save hostname node hostname create node writer prop save thread counts node thread count create node writer prop save sample count node sample count hierarchicalstreamwriter marshallingcontext samplesaveconfiguration samplesaveconfiguration createnode savebytes node_bytes createnode saveurl node_url createnode savefilename node_filename createnode savehostname node_hostname createnode savethreadcounts node_thread_count createnode savesamplecount node_sample_count helper method to simplify marshall routine private void create node hierarchical stream writer writer boolean save string node if save return writer start node node writer set value true writer end node createnode hierarchicalstreamwriter startnode setvalue endnode public object unmarshal hierarchical stream reader reader unmarshalling context context final class this class sample save configuration class final class required type context get required type if required type this class throw new illegal argument exception unexpected class required type get name sample save configuration result new sample save configuration result set bytes false maintain backward compatibility bytes was not in the jmx file while reader has more children reader move down string nn reader get node name if formatter equals nn skip formatter if present bug 42674 non nls 1 string field name mapper real member this class nn java lang reflect field field reflection provider get field this class field name class type field get type object value unmarshall field context result type field reflection provider write field result nn value this class reader move up return result hierarchicalstreamreader unmarshallingcontext thisclass samplesaveconfiguration requiredtype getrequiredtype requiredtype thisclass illegalargumentexception requiredtype getname samplesaveconfiguration samplesaveconfiguration setbytes hasmorechildren movedown getnodename fieldname realmember thisclass reflectionprovider getfield thisclass fieldname gettype unmarshallfield reflectionprovider writefield thisclass moveup constructors constructs an instance of vertical layout with a vertical vgap of 5 pixels horizontal centering and anchored to the top of the display area public vertical layout this 5 center top verticallayout verticallayout constructs a vertical layout instance with horizontal centering anchored to the top with the specified vgap param vgap an int value indicating the vertical seperation of the components public vertical layout int vgap this vgap center top verticallayout verticallayout constructs a vertical layout instance anchored to the top with the specified vgap and horizontal alignment param vgap an int value indicating the vertical seperation of the components param alignment an int value which is one of code right left center both code for the horizontal alignment public vertical layout int vgap int alignment this vgap alignment top verticallayout verticallayout constructs a vertical layout instance with the specified vgap horizontal alignment and anchoring param vgap an int value indicating the vertical seperation of the components param alignment an int value which is one of code right left center both code for the horizontal alignment param anchor an int value which is one of code top bottom center code indicating where the components are to appear if the display area exceeds the minimum necessary public vertical layout int vgap int alignment int anchor this vgap vgap this alignment alignment this anchor anchor verticallayout verticallayout lays out the container public void layout container container parent insets insets parent get insets notused dimension dim layout size parent false synchronized parent get tree lock int n parent get component count dimension pd parent get size int y 0 work out the total size for int i 0 i n i component c parent get component i dimension d c get preferred size y d height vgap y vgap otherwise there s a vgap too many work out the anchor paint if anchor top y insets top else if anchor center y pd height y 2 else y pd height y insets bottom do layout for int i 0 i n i component c parent get component i dimension d c get preferred size int x insets left int wid d width if alignment center x pd width d width 2 else if alignment right x pd width d width insets right else if alignment both wid pd width insets left insets right c set bounds x y wid d height y d height vgap layoutcontainer getinsets layoutsize gettreelock getcomponentcount getsize getcomponent getpreferredsize getcomponent getpreferredsize setbounds public dimension minimum layout size container parent return layout size parent true minimumlayoutsize layoutsize public dimension preferred layout size container parent return layout size parent false preferredlayoutsize layoutsize not used by this class public void add layout component string name component comp addlayoutcomponent not used by this class public void remove layout component component comp removelayoutcomponent public string to string return get class get name vgap vgap align alignment anchor anchor tostring getclass getname private dimension layout size container parent boolean minimum dimension dim new dimension 0 0 dimension d synchronized parent get tree lock int n parent get component count for int i 0 i n i component c parent get component i if c is visible d minimum c get minimum size c get preferred size dim width math max dim width d width dim height d height if i 0 dim height vgap insets insets parent get insets dim width insets left insets right dim height insets top insets bottom vgap vgap return dim layoutsize gettreelock getcomponentcount getcomponent isvisible getminimumsize getpreferredsize getinsets default constructor public auth manager set property new collection property auth list new array list authmanager setproperty collectionproperty auth_list arraylist public void clear super clear set property new collection property auth list new array list setproperty collectionproperty auth_list arraylist update an authentication record public void set int index string url string user string pass string domain string realm authorization auth new authorization url user pass domain realm if index 0 get auth objects set index new test element property auth get name auth else get auth objects add item auth getauthobjects testelementproperty getname getauthobjects additem public collection property get auth objects return collection property get property auth list collectionproperty getauthobjects collectionproperty getproperty auth_list public int get column count return column count getcolumncount column_count public string get column name int column return column resource names column getcolumnname column_resource_names public class get column class int column return column resource names column get class getcolumnclass column_resource_names getclass public authorization get auth object at int row return authorization get auth objects get row get object value getauthobjectat getauthobjects getobjectvalue public boolean is editable return true iseditable public class get gui class return org apache jmeter protocol http gui auth panel class getguiclass authpanel public collection get add list return null getaddlist return the record at index i public authorization get int i return authorization get auth objects get i get object value getauthobjects getobjectvalue public string get auth header forurl url url authorization auth get auth forurl url if auth null return null return auth to basic header getauthheaderforurl getauthforurl tobasicheader public authorization get auth forurl url url if is supported protocol url return null todo replace all this url2 mess with a proper method are equivalent url1 url2 that would also ignore case in protocol and host names etc use that method in the cookie manager too url url2 null try if url get port 1 obtain another url with an explicit port int port url get protocol equals ignore case http 80 443 only http and https are supported url2 new url url get protocol url get host port url get path else if url get port 80 url get protocol equals ignore case http url get port 443 url get protocol equals ignore case https url2 new url url get protocol url get host url get path catch malformedurl exception e log error internal error e this should never happen anyway we ll continue with url2 set to null string s1 url to string string s2 null if url2 null s2 url2 to string log debug target url strings to match against s1 and s2 todo should really return most specific i e longest match for property iterator iter get auth objects iterator iter has next authorization auth authorization iter next get object value string url auth geturl log debug checking match against auth n entry url if s1 starts with url s2 null s2 starts with url log debug matched return auth log debug did not match return null getauthforurl issupportedprotocol areequivalent cookiemanager getport getprotocol equalsignorecase getprotocol gethost getpath getport getprotocol equalsignorecase getport getprotocol equalsignorecase getprotocol gethost getpath malformedurlexception tostring tostring propertyiterator getauthobjects hasnext getobjectvalue startswith startswith public void add config element config element config addconfigelement configelement public void add auth authorization auth get auth objects add item auth addauth getauthobjects additem public void add auth get auth objects add item new authorization addauth getauthobjects additem public boolean expects modification return false expectsmodification public void uncompile todo is this used save the authentication data to a file public void save string auth file throws io exception file file new file auth file if file is absolute file new file system get property user dir auth file print writer writer new print writer new file writer file writer println j meter generated authorization file for int i 0 i get auth objects size i authorization auth authorization get auth objects get i get object value writer println auth to string writer flush writer close authfile ioexception authfile isabsolute getproperty authfile printwriter printwriter filewriter jmeter getauthobjects getauthobjects getobjectvalue tostring add authentication data from a file public void add file string auth file throws io exception file file new file auth file if file is absolute file new file system get property user dir file separator auth file if file can read throw new io exception the file you specified cannot be read buffered reader reader null boolean ok true try reader new buffered reader new file reader file string line while line reader read line null try if line starts with line trim length 0 non nls 1 continue string tokenizer st new string tokenizer line t non nls 1 string url st next token string user st next token string pass st next token string domain string realm if st has more tokens allow for old format file without the extra columnns domain st next token realm st next token authorization auth new authorization url user pass domain realm get auth objects add item auth catch no such element exception e log error error parsing auth line line ok false finally io utils close quietly reader if ok j meter utils report error to user one or more errors found when reading the auth file see the log file addfile authfile ioexception authfile isabsolute getproperty authfile canread ioexception bufferedreader bufferedreader filereader readline startswith stringtokenizer stringtokenizer nexttoken nexttoken nexttoken hasmoretokens nexttoken nexttoken getauthobjects additem nosuchelementexception ioutils closequietly jmeterutils reporterrortouser remove an authentication record public void remove int index get auth objects remove index getauthobjects return the number of records public int get auth count return get auth objects size getauthcount getauthobjects needs to be package protected for unit test static boolean is supported protocol url url string protocol url get protocol to lower case java util locale english return protocol equals http constants protocol http protocol equals http constants protocol https issupportedprotocol getprotocol tolowercase httpconstants protocol_http httpconstants protocol_https private static string out version 1 1 default for writing non nls 1 public static void set in version string v in version v outversion setinversion inversion public static void set out version string v out version v setoutversion outversion encode a string if necessary for output to a jtl file strings are only encoded if the output version is 1 0 but nulls are always converted to the empty string param p string to encode return encoded string will never be null public static string encode string p if p null nulls cannot be written using pretty print writer they cause an npe return non nls 1 only encode strings if out version 1 0 if 1 0 equals out version non nls 1 return p try string p1 url encoder encode p char set return p1 catch unsupported encoding exception e log warn system doesn t support char set e return p prettyprintwriter outversion outversion urlencoder char_set unsupportedencodingexception char_set public static string decode string p if 1 0 equals in version non nls 1 return p only decode strings if in version 1 0 if p null return null try return url decoder decode p char set catch unsupported encoding exception e log warn system doesn t support char set e return p inversion inversion urldecoder char_set unsupportedencodingexception char_set public static string cdata byte chars string encoding throws unsupported encoding exception string buffer buf new string buffer cdata buf append new string chars encoding buf append return buf to string unsupportedencodingexception stringbuffer stringbuffer tostring private static final map property to attribute new hash map private static void mapentry string prop string att property to attribute put prop att propertytoattribute hashmap propertytoattribute private static void save class test element el hierarchical stream writer writer string prop string clazz el get property as string prop if clazz length 0 writer add attribute string property to attribute get prop save service class to alias clazz saveclass testelement hierarchicalstreamwriter getpropertyasstring addattribute propertytoattribute saveservice classtoalias private static void restore class test element el hierarchical stream reader reader string prop string att string property to attribute get prop string alias reader get attribute att if alias null el set property prop save service alias to class alias restoreclass testelement hierarchicalstreamreader propertytoattribute getattribute setproperty saveservice aliastoclass private static void save item test element el hierarchical stream writer writer string prop boolean encode string item el get property as string prop if item length 0 if encode item conversion help encode item writer add attribute string property to attribute get prop item saveitem testelement hierarchicalstreamwriter getpropertyasstring conversionhelp addattribute propertytoattribute private static void restore item test element el hierarchical stream reader reader string prop boolean decode string att string property to attribute get prop string value reader get attribute att if value null if decode value conversion help decode value el set property prop value restoreitem testelement hierarchicalstreamreader propertytoattribute getattribute conversionhelp setproperty public static boolean is special property string name return property to attribute contains key name isspecialproperty propertytoattribute containskey public static void save special properties test element el hierarchical stream writer writer save class el writer test element gui class save class el writer test element test class save item el writer test element name true save item el writer test element enabled false savespecialproperties testelement hierarchicalstreamwriter saveclass testelement gui_class saveclass testelement test_class saveitem testelement saveitem testelement public static void restore special properties test element el hierarchical stream reader reader restore class el reader test element gui class restore class el reader test element test class restore item el reader test element name true restore item el reader test element enabled false restorespecialproperties testelement hierarchicalstreamreader restoreclass testelement gui_class restoreclass testelement test_class restoreitem testelement restoreitem testelement public memory impl super memoryimpl public long get max return this max getmax public void set max long value this max value setmax public long get free return this free getfree public void set free long value this free value setfree public long get total return this total gettotal public void set total long value this total value settotal private static final class x stream wrapper extends x stream private x stream wrapper reflection provider reflection provider super reflection provider xstreamwrapper xstream xstreamwrapper reflectionprovider reflectionprovider reflectionprovider override wrap mapper in order to insert the wrapper in the chain protected mapper wrapper wrap mapper mapper wrapper next provide our own aliasing using strings rather than classes return new mapper wrapper next translate alias to classname and then delegate to wrapped class public class real class string alias string full name alias to class alias return super real class full name null alias full name translate to alias and then delegate to wrapped class public string serialized class class type if type null return super serialized class null was type but that caused find bugs warning string alias class to alias type get name return alias null super serialized class type alias wrapmapper mapperwrapper wrapmapper mapperwrapper mapperwrapper realclass fullname aliastoclass realclass fullname fullname serializedclass serializedclass findbugs classtoalias getname serializedclass return new mapper wrapper next translate alias to classname and then delegate to wrapped class public class real class string alias string full name alias to class alias return super real class full name null alias full name mapperwrapper realclass fullname aliastoclass realclass fullname fullname translate to alias and then delegate to wrapped class public string serialized class class type if type null return super serialized class null was type but that caused find bugs warning string alias class to alias type get name return alias null super serialized class type alias serializedclass serializedclass findbugs classtoalias getname serializedclass helper method to simplify alias creation from properties private static void make alias string alias string clazz alias to class set property alias clazz object oldval class to alias set property clazz alias if oldval null log error duplicate alias detected for clazz alias oldval makealias aliastoclass setproperty classtoalias setproperty public static properties load properties throws io exception properties name map new properties file input stream fis null try fis new file input stream j meter utils getj meter home j meter utils get prop default saveservice properties saveservice properties file name map load fis finally j orphan utils close quietly fis return name map loadproperties ioexception namemap fileinputstream fileinputstream jmeterutils getjmeterhome jmeterutils getpropdefault saveservice_properties saveservice_properties_file namemap jorphanutils closequietly namemap private static void init props load the alias properties try properties name map load properties now create the aliases iterator it name map entry set iterator while it has next map entry me map entry it next string key string me get key string val string me get value if key starts with make alias key val else process special keys if key equals ignore case version non nls 1 properties version val log info using save service properties version properties version else if key equals ignore case file version non nls 1 file version extract version val log info using save service properties file version file version else if key equals ignore case file encoding non nls 1 file encoding val log info using save service properties file encoding file encoding else key key substring 1 remove the leading try final string trimmed value val trim if trimmed value equals collection non nls 1 trimmed value equals mapping non nls 1 register converter key jmxsaver true register converter key jtlsaver true else register converter key jmxsaver false register converter key jtlsaver false catch illegal access exception e1 log warn can t register a converter key e1 catch instantiation exception e1 log warn can t register a converter key e1 catch class not found exception e1 log warn can t register a converter key e1 catch illegal argument exception e1 log warn can t register a converter key e1 catch security exception e1 log warn can t register a converter key e1 catch invocation target exception e1 log warn can t register a converter key e1 catch no such method exception e1 log warn can t register a converter key e1 catch io exception e log fatal error bad saveservice properties file e throw new j meter error j meter requires the saveservice properties file to continue initprops namemap loadproperties namemap entryset hasnext getkey getvalue startswith _ makealias equalsignorecase _version propertiesversion saveservice propertiesversion equalsignorecase _file_version fileversion extractversion saveservice fileversion equalsignorecase _file_encoding fileencoding saveservice fileencoding _ trimmedvalue trimmedvalue trimmedvalue registerconverter registerconverter registerconverter registerconverter illegalaccessexception instantiationexception classnotfoundexception illegalargumentexception securityexception invocationtargetexception nosuchmethodexception ioexception fatalerror jmetererror jmeter register converter param key param jmxsaver param use mapper throws instantiation exception throws illegal access exception throws invocation target exception throws no such method exception throws class not found exception private static void register converter string key x stream jmxsaver boolean use mapper throws instantiation exception illegal access exception invocation target exception no such method exception class not found exception if use mapper jmxsaver register converter converter class for name key get constructor new class mapper class new instance new object jmxsaver get mapper else jmxsaver register converter converter class for name key new instance usemapper instantiationexception illegalaccessexception invocationtargetexception nosuchmethodexception classnotfoundexception registerconverter xstream usemapper instantiationexception illegalaccessexception invocationtargetexception nosuchmethodexception classnotfoundexception usemapper registerconverter forname getconstructor newinstance getmapper registerconverter forname newinstance for converters to use public static string alias to class string s string r alias to class get property s return r null s r aliastoclass aliastoclass getproperty for converters to use public static string class to alias string s string r class to alias get property s return r null s r classtoalias classtoalias getproperty called by save function public static void save tree hash tree tree output stream out throws io exception get the output writer to use output stream writer output stream writer get output stream writer out write xml header output stream writer use deprecated method to avoid duplicating code script wrapper wrapper new script wrapper wrapper test plan tree jmxsaver toxml wrapper output stream writer output stream writer write n ensure terminated properly output stream writer close savetree hashtree outputstream ioexception outputwriter outputstreamwriter outputstreamwriter getoutputstreamwriter writexmlheader outputstreamwriter scriptwrapper scriptwrapper testplan outputstreamwriter outputstreamwriter outputstreamwriter used by test code public static void save element object el output stream out throws io exception get the output writer to use output stream writer output stream writer get output stream writer out write xml header output stream writer use deprecated method to avoid duplicating code jmxsaver toxml el output stream writer output stream writer close saveelement outputstream ioexception outputwriter outputstreamwriter outputstreamwriter getoutputstreamwriter writexmlheader outputstreamwriter outputstreamwriter outputstreamwriter used by test code public static object load element input stream in throws io exception get the input reader to use input stream reader input stream reader get input stream reader in use deprecated method to avoid duplicating code object element jmxsaver fromxml input stream reader input stream reader close return element loadelement inputstream ioexception inputreader inputstreamreader inputstreamreader getinputstreamreader inputstreamreader inputstreamreader save a sample result to an xml output file using x stream param evt sample result wrapped in a sample event param writer output stream which must be created using link get file encoding string used by result collector sample occurred sample event event public synchronized static void save sample result sample event evt writer writer throws io exception data holder dh jtlsaver new data holder dh put sample event object evt this is effectively the same as saver toxml object writer except we get to provide the data holder don t know why there is no method for this in the x stream class jtlsaver marshal evt get result new xpp driver create writer writer dh writer write n sampleresult xstream sampleresult sampleevent getfileencoding resultcollector sampleoccurred sampleevent savesampleresult sampleevent ioexception dataholder newdataholder sample_event_object dataholder xstream getresult xppdriver createwriter param elem test element param writer output stream which must be created using link get file encoding string used by result collector record stats public synchronized static void save test element test element elem writer writer throws io exception jmxsaver toxml elem writer todo should this be jtlsaver only seems to be called by monitor health visualzer writer write n getfileencoding resultcollector recordstats savetestelement testelement ioexception monitorhealthvisualzer private static string extract version string rev if rev length revpfx length revsfx length return rev substring revpfx length rev length revsfx length return rev extractversion routines for test save service static boolean check property version return save service propversion equals save service properties version testsaveservice checkpropertyversion saveservice saveservice propertiesversion static boolean check file version return save service fileversion equals save service file version checkfileversion saveservice saveservice fileversion static boolean check versions versionsok true disable converter version checks as they are more of a nuisance than helpful check version boolean property converter class 493779 non nls 1 check version hash tree converter class 514283 non nls 1 check version integer property converter class 493779 non nls 1 check version long property converter class 493779 non nls 1 check version multi property converter class 514283 non nls 1 check version sample result converter class 571992 non nls 1 not built until later so need to use this method try check version class for name org apache jmeter protocol http util http result converter non nls 1 514283 non nls 1 catch class not found exception e versionsok false log warn e get localized message check version string property converter class 493779 non nls 1 check version test element converter class 549987 non nls 1 check version test element property converter class 549987 non nls 1 check version script wrapper converter class 514283 non nls 1 check version test result wrapper converter class 514283 non nls 1 check version sample save configuration converter class 549936 non nls 1 if propversion equals ignore case properties version log warn bad version expected propversion found properties version if fileversion equals ignore case file version log warn bad file version expected fileversion found file version if versionsok log info all converter versions present and correct return versionsok checkversions checkversion booleanpropertyconverter checkversion hashtreeconverter checkversion integerpropertyconverter checkversion longpropertyconverter checkversion multipropertyconverter checkversion sampleresultconverter checkversion forname httpresultconverter classnotfoundexception getlocalizedmessage checkversion stringpropertyconverter checkversion testelementconverter checkversion testelementpropertyconverter checkversion scriptwrapperconverter checkversion testresultwrapperconverter checkversion samplesaveconfigurationconverter equalsignorecase propertiesversion _version propertiesversion equalsignorecase fileversion _file_version fileversion read results from jtl file param reader of the file param result collector helper helper class to enable test result wrapper converter to deliver the samples throws exception public static void load test results input stream reader result collector helper result collector helper throws exception get the input reader to use input stream reader input stream reader get input stream reader reader data holder dh jtlsaver new data holder dh put resultcollector helper object result collector helper allow test result wrapper to feed back the samples this is effectively the same as saver fromxml input stream except we get to provide the data holder don t know why there is no method for this in the x stream class jtlsaver unmarshal new xpp driver create reader reader null dh input stream reader close resultcollectorhelper testresultwrapperconverter loadtestresults inputstream resultcollectorhelper resultcollectorhelper inputreader inputstreamreader inputstreamreader getinputstreamreader dataholder newdataholder resultcollector_helper_object resultcollectorhelper testresultwrapper inputstream dataholder xstream xppdriver createreader inputstreamreader load a test tree jmx file param reader on the jmx file return the loaded tree throws exception if there is a problem reading the file or processing it public static hash tree load tree input stream reader throws exception if reader mark supported reader new buffered input stream reader reader mark integer max value script wrapper wrapper null try get the input reader to use input stream reader input stream reader get input stream reader reader wrapper script wrapper jmxsaver fromxml input stream reader input stream reader close if wrapper null log error problem loading new style see above return null return wrapper test plan catch cannot resolve class exception e log warn problem loading new style e get localized message reader reset return old save service load sub tree reader catch no class def found error e log error missing class e return null catch conversion exception e log error conversion error e return null hashtree loadtree inputstream marksupported bufferedinputstream max_value scriptwrapper inputreader inputstreamreader inputstreamreader getinputstreamreader scriptwrapper inputstreamreader inputstreamreader testplan cannotresolveclassexception getlocalizedmessage oldsaveservice loadsubtree noclassdeffounderror conversionexception private static input stream reader get input stream reader input stream in stream check if we have a encoding to use from properties charset charset get file encoding charset if charset null return new input stream reader in stream charset else we use the default character set encoding of the jre return new input stream reader in stream inputstreamreader getinputstreamreader inputstream instream getfileencodingcharset inputstreamreader instream inputstreamreader instream private static output stream writer get output stream writer output stream out stream check if we have a encoding to use from properties charset charset get file encoding charset if charset null return new output stream writer out stream charset else we use the default character set encoding of the jre return new output stream writer out stream outputstreamwriter getoutputstreamwriter outputstream outstream getfileencodingcharset outputstreamwriter outstream outputstreamwriter outstream returns the file encoding specified in saveservice properties or the default param dflt value to return if file encoding was not provided return file encoding or default used by result collector when creating output files public static string get file encoding string dflt if file encoding null file encoding length 0 return file encoding else return dflt resultcollector getfileencoding fileencoding fileencoding fileencoding private static charset get file encoding charset check if we have a encoding to use from properties if file encoding null file encoding length 0 return charset for name file encoding else we use the default character set encoding of the jre return null getfileencodingcharset fileencoding fileencoding forname fileencoding private static void write xml header output stream writer writer throws io exception write xml header if we have the charset to use for encoding charset charset get file encoding charset if charset null we do not use get encoding method of writer since that returns the historical name string header xml header replace all ph charset name writer write header writer write n writexmlheader outputstreamwriter ioexception getfileencodingcharset getencoding xml_header replaceall public static boolean is save test plan format20 return is testplan format 20 issavetestplanformat20 is_testplan_format_20 public static boolean is save test log format20 return is testlog format 20 issavetestlogformat20 is_testlog_format_20 new test format more compressed class names public static boolean is save test plan format22 return is testplan format 22 issavetestplanformat22 is_testplan_format_22 simplify get message output from x stream conversion exception param ce conversion exception to analyse return string with details of error public static string c eto string conversion exception ce string msg x stream conversion exception at line ce get line number n ce get message n perhaps a missing jar see log file return msg getmessage xstream conversionexception conversionexception cetostring conversionexception xstream conversionexception nperhaps public static string get properties version return properties version getpropertiesversion propertiesversion public static string getversion return version handle the sslmanager action by displaying the ssl c lient manager dialog box the dialog box is not modal because those should be avoided if at all possible public void do action action event e if e get action command equals action names ssl manager this ssl manager client doaction actionevent getactioncommand actionnames ssl_manager sslmanager provide the list of action names that are available in this command public set get action names return ssl manager command command set getactionnames sslmanagercommand commandset called by ssl manager button raises ssl manager dialog i e a file chooser for pcsi12 p12 p12 files private void ssl manager ssl manager reset key store chooser new j file chooser j meter utils getj meter properties get property user dir non nls 1 key store chooser add choosable file filter new acceptpkcs12 file filter key store chooser set file selection mode j file chooser files only int ret val key store chooser show open dialog gui package get instance get main frame if j file chooser approve option ret val file selected file key store chooser get selected file try system set property ssl manager javax net ssl key store selected file get canonical path catch io exception e ignored key store chooser null ssl manager get instance sslmanager sslmanager filechooser sslmanager sslmanager keystorechooser jfilechooser jmeterutils getjmeterproperties getproperty keystorechooser addchoosablefilefilter acceptpkcs12filefilter keystorechooser setfileselectionmode jfilechooser files_only retval keystorechooser showopendialog guipackage getinstance getmainframe jfilechooser approve_option retval selectedfile keystorechooser getselectedfile setproperty sslmanager javax_net_ssl_key_store selectedfile getcanonicalpath ioexception keystorechooser sslmanager getinstance static private class acceptpkcs12 file filter extends file filter get the description that shows up in j file chooser filter menu return description public string get description return j meter utils get res string pkcs12 desc non nls 1 acceptpkcs12filefilter filefilter jfilechooser getdescription jmeterutils getresstring pkcs12_desc tests to see if the file ends with p12 or p12 param test file file to test return true if file is accepted false otherwise public boolean accept file test file return test file is directory test file get name ends with p12 non nls 1 test file get name ends with p12 non nls 1 testfile testfile testfile isdirectory testfile getname endswith testfile getname endswith private locale locale public locale change event object source super source localechangeevent public locale change event object source locale locale super source this locale locale localechangeevent public locale get locale return locale getlocale public abstract class multi property extends abstract property public multi property super multiproperty abstractproperty multiproperty public multi property string name super name multiproperty get the property iterator to iterate through the sub values of this j meter property return an iterator for the sub values of this property jmeterproperty public abstract property iterator iterator add a property to the collection public abstract void add property j meter property prop propertyiterator addproperty jmeterproperty public abstract void add property j meter property prop clear away all values in the property public abstract void clear addproperty jmeterproperty public void set running version boolean running super set running version running property iterator iter iterator while iter has next iter next set running version running setrunningversion setrunningversion propertyiterator hasnext setrunningversion protected void recover running version of sub elements test element owner property iterator iter iterator while iter has next j meter property prop iter next if owner is temporary prop iter remove else prop recover running version owner recoverrunningversionofsubelements testelement propertyiterator hasnext jmeterproperty istemporary recoverrunningversion public void merge in j meter property prop if prop get object value get object value return log debug merging in prop get class if prop instanceof multi property property iterator iter multi property prop iterator while iter has next j meter property item iter next add property item else add property prop mergein jmeterproperty getobjectvalue getobjectvalue getclass multiproperty propertyiterator multiproperty hasnext jmeterproperty addproperty addproperty public class once only controller gui extends abstract controller gui public once only controller gui init onceonlycontrollergui abstractcontrollergui onceonlycontrollergui public test element create test element once only controller oc new once only controller modify test element oc return oc testelement createtestelement onceonlycontroller onceonlycontroller modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element oc configure test element oc testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement public string get label resource return once only controller title non nls 1 getlabelresource once_only_controller_title private void init set layout new vertical layout 5 vertical layout both vertical layout top set border make border add make title panel setlayout verticallayout verticallayout verticallayout setborder makeborder maketitlepanel new j check box j meter utils get res string aggregate report error public table gui super init jcheckbox jmeterutils getresstring aggregate_report_error tablegui public string get label resource return report table getlabelresource report_table initialize the components and layout of this component private void init called from ctor so must not be overridable set layout new border layout 10 10 set border make border set background color white j panel pane new j panel pane set layout new border layout 10 10 pane set background color white pane add this get name panel border layout north mean check add change listener this vertical panel options new vertical panel color white mean check set background color white median check set background color white max check set background color white min check set background color white response rate check set background color white transfer rate check set background color white fiftypercent check set background color white nintypercent check set background color white error rate check set background color white options add mean check options add median check options add max check options add min check options add response rate check options add transfer rate check options add fiftypercent check options add nintypercent check options add error rate check add pane border layout north add options border layout center setlayout borderlayout setborder makeborder setbackground jpanel jpanel setlayout borderlayout setbackground getnamepanel borderlayout meancheck addchangelistener verticalpanel verticalpanel meancheck setbackground mediancheck setbackground maxcheck setbackground mincheck setbackground responseratecheck setbackground transferratecheck setbackground fiftypercentcheck setbackground nintypercentcheck setbackground errorratecheck setbackground meancheck mediancheck maxcheck mincheck responseratecheck transferratecheck fiftypercentcheck nintypercentcheck errorratecheck borderlayout borderlayout public j popup menu create popup menu j popup menu pop new j popup menu report menu factory add file menu pop report menu factory add edit menu pop true return pop jpopupmenu createpopupmenu jpopupmenu jpopupmenu reportmenufactory addfilemenu reportmenufactory addeditmenu public test element create test element table element new table modify test element element return element testelement createtestelement modifytestelement public void modify test element test element element this configure test element element table tb table element tb set50 percent string value of fiftypercent check is selected tb set90 percent string value of nintypercent check is selected tb set error rate string value of error rate check is selected tb set max string value of max check is selected tb set mean string value of mean check is selected tb set median string value of median check is selected tb set min string value of min check is selected tb set response rate string value of response rate check is selected tb set transfer rate string value of transfer rate check is selected modifytestelement testelement configuretestelement set50percent valueof fiftypercentcheck isselected set90percent valueof nintypercentcheck isselected seterrorrate valueof errorratecheck isselected setmax valueof maxcheck isselected setmean valueof meancheck isselected setmedian valueof mediancheck isselected setmin valueof mincheck isselected setresponserate valueof responseratecheck isselected settransferrate valueof transferratecheck isselected public void configure test element element super configure element table tb table element mean check set selected tb get mean median check set selected tb get median max check set selected tb get max min check set selected tb get min fiftypercent check set selected tb get50 percent nintypercent check set selected tb get90 percent error rate check set selected tb get error rate response rate check set selected tb get response rate transfer rate check set selected tb get transfer rate testelement meancheck setselected getmean mediancheck setselected getmedian maxcheck setselected getmax mincheck setselected getmin fiftypercentcheck setselected get50percent nintypercentcheck setselected get90percent errorratecheck setselected geterrorrate responseratecheck setselected getresponserate transferratecheck setselected gettransferrate public void state changed change event e modify test element report gui package get instance get current element statechanged changeevent modifytestelement reportguipackage getinstance getcurrentelement public result action super log debug thread current thread get name system out println me this get name thread current thread get name resultaction currentthread getname getname currentthread getname examine the sample s and take appropriate action see org apache jmeter samplers sample listener sample occurred org apache jmeter samplers sample event public void sample occurred sample event e sample result s e get result log debug s get sample label ok s is successful if s is successful if is stop test now s set stop test now true if is stop test s set stop test true if is stop thread s set stop thread true samplelistener sampleoccurred sampleevent sampleoccurred sampleevent sampleresult getresult getsamplelabel issuccessful issuccessful isstoptestnow setstoptestnow isstoptest setstoptest isstopthread setstopthread see org apache jmeter samplers sample listener sample started org apache jmeter samplers sample event public void sample started sample event e not used samplelistener samplestarted sampleevent samplestarted sampleevent see org apache jmeter samplers sample listener sample stopped org apache jmeter samplers sample event public void sample stopped sample event e not used samplelistener samplestopped sampleevent samplestopped sampleevent prevent instantiation of utility class private report file dialoger reportfiledialoger prompts the user to choose a file from their filesystems for our own devious uses this method maintains the last directory the user visited before dismissing the dialog this does not imply they actually chose a file from that directory only that they closed the dialog there it is the caller s responsibility to check to see if the selected file is non null return the j file chooser that interacted with the user after they are finished using it accept or otherwise public static j file chooser prompt to open file string exts j file chooser jfc null if lastjfc directory null string start j meter utils get prop default user dir if start equals jfc set current directory new file start clear file filters jfc add choosable file filter new j meter file filter exts int ret val jfc show open dialog report gui package get instance get main frame lastjfc directory jfc get current directory get absolute path if ret val j file chooser approve option return jfc else return null jfilechooser jfilechooser prompttoopenfile jfilechooser lastjfcdirectory jmeterutils getpropdefault setcurrentdirectory clearfilefilters addchoosablefilefilter jmeterfilefilter retval showopendialog reportguipackage getinstance getmainframe lastjfcdirectory getcurrentdirectory getabsolutepath retval jfilechooser approve_option private static void clear file filters file filter filters jfc get choosable file filters for int x 0 x filters length x jfc remove choosable file filter filters x clearfilefilters filefilter getchoosablefilefilters removechoosablefilefilter public static j file chooser prompt to open file return prompt to open file new string 0 jfilechooser prompttoopenfile prompttoopenfile prompts the user to choose a file from their filesystems for our own devious uses this method maintains the last directory the user visited before dismissing the dialog this does not imply they actually chose a file from that directory only that they closed the dialog there it is the caller s responsibility to check to see if the selected file is non null return the j file chooser that interacted with the user after they are finished using it accept or otherwise see prompt to open file public static j file chooser prompt to save file string filename return prompt to save file filename null jfilechooser prompttoopenfile jfilechooser prompttosavefile prompttosavefile get a j file chooser with a new file filter param filename param extensions return j file chooser public static j file chooser prompt to save file string filename string extensions if lastjfc directory null string start j meter utils get prop default user dir if start equals jfc new j file chooser new file start lastjfc directory jfc get current directory get absolute path string ext jmx if filename null jfc set selected file new file lastjfc directory filename int i 1 if i filename last index of 1 ext filename substring i clear file filters if extensions null jfc add choosable file filter new j meter file filter extensions else jfc add choosable file filter new j meter file filter new string ext int ret val jfc show save dialog report gui package get instance get main frame lastjfc directory jfc get current directory get absolute path if ret val j file chooser approve option return jfc else return null jfilechooser filefilter jfilechooser jfilechooser prompttosavefile lastjfcdirectory jmeterutils getpropdefault jfilechooser lastjfcdirectory getcurrentdirectory getabsolutepath setselectedfile lastjfcdirectory lastindexof clearfilefilters addchoosablefilefilter jmeterfilefilter addchoosablefilefilter jmeterfilefilter retval showsavedialog reportguipackage getinstance getmainframe lastjfcdirectory getcurrentdirectory getabsolutepath retval jfilechooser approve_option public void sample occurred sample event event try bsf manager mgr get manager if mgr null log error problem creating bsf manager return mgr declare bean sample event event sample event class sample result result event get result mgr declare bean sample result result sample result class process file or script mgr mgr terminate catch bsf exception e log warn problem in bsf script e sampleoccurred sampleevent bsfmanager getmanager declarebean sampleevent sampleevent sampleresult getresult declarebean sampleresult sampleresult processfileorscript bsfexception public void sample started sample event e samplestarted sampleevent public void sample stopped sample event e samplestopped sampleevent public void add sample result sample sampleresult public boolean is stats return false isstats private j meter property temp value todo why does null property have a value public null property string name super name jmeterproperty tempvalue nullproperty public null property super nullproperty see j meter property get string value public string get string value if temp value null return temp value get string value return jmeterproperty getstringvalue getstringvalue tempvalue tempvalue getstringvalue public void set object value object v setobjectvalue see j meter property get object value public object get object value return null jmeterproperty getobjectvalue getobjectvalue see j meter property is running version public boolean is running version return false jmeterproperty isrunningversion isrunningversion see j meter property is temporary test element public boolean is temporary test element owner return true jmeterproperty istemporary testelement istemporary testelement see j meter property merge in j meter property public void merge in j meter property prop temp value prop jmeterproperty mergein jmeterproperty mergein jmeterproperty tempvalue public final object clone return this see j meter property get boolean value public boolean get boolean value return false jmeterproperty getbooleanvalue getbooleanvalue see j meter property get double value public double get double value return 0 jmeterproperty getdoublevalue getdoublevalue see j meter property get float value public float get float value return 0 jmeterproperty getfloatvalue getfloatvalue see j meter property get int value public int get int value return 0 jmeterproperty getintvalue getintvalue see j meter property get long value public long get long value return 0 jmeterproperty getlongvalue getlongvalue see j meter property recover running version test element public void recover running version test element owner temp value null jmeterproperty recoverrunningversion testelement recoverrunningversion testelement tempvalue double saved value public double property string name double value super name this value value savedvalue doubleproperty public double property doubleproperty public void set value float value this value value setvalue protected void set number value number n value n double value setnumbervalue doublevalue protected void set number value string n throws number format exception value double parse double n setnumbervalue numberformatexception parsedouble see j meter property get string value public string get string value return double to string value jmeterproperty getstringvalue getstringvalue tostring see j meter property get object value public object get object value return new double value jmeterproperty getobjectvalue getobjectvalue public object clone double property prop double property super clone prop value value return prop doubleproperty doubleproperty see j meter property get boolean value public boolean get boolean value return value 0 true false jmeterproperty getbooleanvalue getbooleanvalue see j meter property get double value public double get double value return value jmeterproperty getdoublevalue getdoublevalue see j meter property get float value public float get float value return float value jmeterproperty getfloatvalue getfloatvalue see j meter property get int value public int get int value return int value jmeterproperty getintvalue getintvalue see j meter property get long value public long get long value return long value jmeterproperty getlongvalue getlongvalue see org apache jmeter testelement property j meter property set running version boolean public void set running version boolean running version saved value value super set running version running version jmeterproperty setrunningversion setrunningversion runningversion savedvalue setrunningversion runningversion see org apache jmeter testelement property j meter property recover running version org apache jmeter testelement test element public void recover running version test element owner value saved value jmeterproperty recoverrunningversion testelement recoverrunningversion testelement savedvalue private j panel create on error panel j panel panel new j panel panel set border border factory create titled border j meter utils get res string sampler on error action non nls 1 button group group new button group continue box new j radio button j meter utils get res string sampler on error continue non nls 1 group add continue box continue box set selected true panel add continue box stop thrd box new j radio button j meter utils get res string sampler on error stop thread non nls 1 group add stop thrd box panel add stop thrd box stop test box new j radio button j meter utils get res string sampler on error stop test non nls 1 group add stop test box panel add stop test box stop test now box new j radio button j meter utils get res string sampler on error stop test now non nls 1 group add stop test now box panel add stop test now box return panel jpanel createonerrorpanel jpanel jpanel setborder borderfactory createtitledborder jmeterutils getresstring sampler_on_error_action buttongroup buttongroup continuebox jradiobutton jmeterutils getresstring sampler_on_error_continue continuebox continuebox setselected continuebox stopthrdbox jradiobutton jmeterutils getresstring sampler_on_error_stop_thread stopthrdbox stopthrdbox stoptestbox jradiobutton jmeterutils getresstring sampler_on_error_stop_test stoptestbox stoptestbox stoptestnowbox jradiobutton jmeterutils getresstring sampler_on_error_stop_test_now stoptestnowbox stoptestnowbox create a new name panel with the default name public on error panel init namepanel onerrorpanel initialize the gui components and layout private void init set layout new border layout 5 0 add create on error panel setlayout borderlayout createonerrorpanel public void configure int error action stop test now box set selected error action on error test element on error stoptest now stop test box set selected error action on error test element on error stoptest stop thrd box set selected error action on error test element on error stopthread continue box set selected error action on error test element on error continue erroraction stoptestnowbox setselected erroraction onerrortestelement on_error_stoptest_now stoptestbox setselected erroraction onerrortestelement on_error_stoptest stopthrdbox setselected erroraction onerrortestelement on_error_stopthread continuebox setselected erroraction onerrortestelement on_error_continue public int get on error setting if stop test now box is selected return on error test element on error stoptest now if stop test box is selected return on error test element on error stoptest if stop thrd box is selected return on error test element on error stopthread defaults to continue return on error test element on error continue getonerrorsetting stoptestnowbox isselected onerrortestelement on_error_stoptest_now stoptestbox isselected onerrortestelement on_error_stoptest stopthrdbox isselected onerrortestelement on_error_stopthread onerrortestelement on_error_continue public test plan this test plan set functional mode false set serialized false testplan setfunctionalmode setserialized public test plan string name set name name set functional mode false set serialized false does not appear to be needed set property new collection property thread groups thread groups testplan setname setfunctionalmode setserialized setproperty collectionproperty thread_groups threadgroups create transient item private object read resolve thread groups new linked list return this readresolve threadgroups linkedlist public void prepare for pre compile get variables set running version true prepareforprecompile getvariables setrunningversion fetches the functional mode property return functional mode public boolean is functional mode return get property as boolean functional mode isfunctionalmode getpropertyasboolean functional_mode public void set user defined variables arguments vars set property new test element property user defined variables vars setuserdefinedvariables setproperty testelementproperty user_defined_variables public j meter property get user defined variables as property return get property user defined variables jmeterproperty getuserdefinedvariablesasproperty getproperty user_defined_variables public string get basedir return get property as string basedir getbasedir getpropertyasstring does not appear to be used yet public void set basedir string b set property basedir b setbasedir setproperty public arguments get arguments return get variables getarguments getvariables public map get user defined variables arguments args get variables return args get arguments as map getuserdefinedvariables getvariables getargumentsasmap private arguments get variables arguments args arguments get property user defined variables get object value if args null args new arguments set user defined variables args return args getvariables getproperty user_defined_variables getobjectvalue setuserdefinedvariables public void set functional mode boolean func mode set property new boolean property functional mode func mode functional mode func mode setfunctionalmode funcmode setproperty booleanproperty functional_mode funcmode functionalmode funcmode gets the static copy of the functional mode return mode public static boolean get functional mode return functional mode getfunctionalmode functionalmode public void set serialized boolean serializet gs set property new boolean property serialize threadgroups serializet gs setserialized serializetgs setproperty booleanproperty serialize_threadgroups serializetgs set the classpath for the test plan param text public void set test plan classpath string text set property classpaths text settestplanclasspath setproperty public void set test plan classpath array string text string buffer cat new string buffer for int idx 0 idx text length idx if idx 0 cat append classpath separator cat append text idx this set test plan classpath cat to string settestplanclasspatharray stringbuffer stringbuffer classpath_separator settestplanclasspath tostring public string get test plan classpath array return j orphan utils split this get test plan classpath classpath separator gettestplanclasspatharray jorphanutils gettestplanclasspath classpath_separator returns the classpath return classpath public string get test plan classpath return get property as string classpaths gettestplanclasspath getpropertyasstring fetch the serialize threadgroups property return serialized setting public boolean is serialized return get property as boolean serialize threadgroups isserialized getpropertyasboolean serialize_threadgroups public void add parameter string name string value get variables add argument name value addparameter getvariables addargument public void add test element test element tg super add test element tg if tg instanceof thread group is running version add thread group thread group tg addtestelement testelement addtestelement threadgroup isrunningversion addthreadgroup threadgroup adds a feature to the thread group attribute of the test plan object param group the feature to be added to the thread group attribute public void add thread group thread group group thread groups add group threadgroup testplan threadgroup addthreadgroup threadgroup threadgroups public void test ended try file server get file server close files catch io exception e log error problem closing files at end of test e testended fileserver getfileserver closefiles ioexception see org apache jmeter testelement test listener test ended java lang string public void test ended string host test ended testlistener testended testended testended see org apache jmeter testelement test listener test iteration start org apache jmeter engine event loop iteration event public void test iteration start loop iteration event event testlistener testiterationstart loopiterationevent testiterationstart loopiterationevent public void test started if get basedir null get basedir length 0 try file server get file server set basedir file server get file server get base dir get basedir catch io exception e log error failed to set file server base dir with get basedir e we set the classpath string paths this get test plan classpath array for int idx 0 idx paths length idx new driver addurl paths idx log info add paths idx to classpath teststarted getbasedir getbasedir fileserver getfileserver setbasedir fileserver getfileserver getbasedir getbasedir ioexception getbasedir gettestplanclasspatharray newdriver see org apache jmeter testelement test listener test started java lang string public void test started string host test started testlistener teststarted teststarted teststarted see org apache jmeter gui action command get action names public set get action names return commands getactionnames getactionnames see org apache jmeter gui action command do action action event public void do action action event e report tree node dragged nodes report copy get copied nodes report tree listener tree listener report gui package get instance get tree listener report tree node current node tree listener get current node if report dragn drop can add to current node for int i 0 i dragged nodes length i if dragged nodes i null report gui package get instance get tree model insert node into dragged nodes i current node current node get child count report gui package get instance get main frame repaint doaction actionevent doaction actionevent reporttreenode draggednodes reportcopy getcopiednodes reporttreelistener treelistener reportguipackage getinstance gettreelistener reporttreenode currentnode treelistener getcurrentnode reportdragndrop canaddto currentnode draggednodes draggednodes reportguipackage getinstance gettreemodel insertnodeinto draggednodes currentnode currentnode getchildcount reportguipackage getinstance getmainframe private object values public escape html escapehtml public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception string raw string compound variable values 0 execute return string escape utils escape html raw string sampleresult previousresult currentsampler invalidvariableexception rawstring compoundvariable stringescapeutils escapehtml rawstring public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters 1 values parameters to array setparameters invalidvariableexception checkparametercount toarray public string get reference key return key getreferencekey public list get argument desc return desc getargumentdesc default constructor for code java test code the java sampler uses the default constructor to instantiate an instance of the client class public java test get logger debug who ami t construct javatest javatest getlogger whoami tconstruct private void setup values java sampler context context sleep time context get long parameter sleep name default sleep time sleep mask context get long parameter mask name default sleep mask response message context get parameter response message name response message default response code context get parameter response code name response code default success context get parameter success name success default equals ignore case ok label context get parameter label name if label length 0 label context get parameter test element name default to name of element sampler data context get parameter sampler data name sampler data default result data context get parameter result data name result data default setupvalues javasamplercontext sleeptime getlongparameter sleep_name default_sleep_time sleepmask getlongparameter mask_name default_sleep_mask responsemessage getparameter response_message_name response_message_default responsecode getparameter response_code_name response_code_default getparameter success_name success_default equalsignorecase getparameter label_name getparameter testelement samplerdata getparameter sampler_data_name sampler_data_default resultdata getparameter result_data_name result_data_default do any initialization required by this client there is none as it is done in run test in order to be able to vary the data for each sample param context the context to run with this provides access to initialization parameters public void setup test java sampler context context get logger debug who ami tsetup test list parameters context runtest setuptest javasamplercontext getlogger whoami tsetuptest listparameters provide a list of parameters which this test supports any parameter names and associated values returned by this method will appear in the gui by default so the user doesn t have to remember the exact names the user can add other parameters which are not listed here if this method returns null then no parameters will be listed if the value for some parameter is null then that parameter will be listed in the gui with an empty value return a specification of the parameters used by this test which should be listed in the gui or null if no parameters should be listed public arguments get default parameters arguments params new arguments params add argument sleep name string value of default sleep time params add argument mask name default mask string params add argument label name params add argument response code name response code default params add argument response message name response message default params add argument success name success default params add argument sampler data name sampler data default params add argument result data name sampler data default return params getdefaultparameters addargument sleep_name valueof default_sleep_time addargument mask_name default_mask_string addargument label_name addargument response_code_name response_code_default addargument response_message_name response_message_default addargument success_name success_default addargument sampler_data_name sampler_data_default addargument result_data_name sampler_data_default perform a single sample br in this case this method will simply sleep for some amount of time this method returns a code sample result code object pre the following fields are always set response code default quot quot response message default quot quot label set from label name parameter if it exists else element name success default true pre the following fields are set from the user defined parameters if supplied pre sampler data response data pre see org apache jmeter samplers sample result sample start see org apache jmeter samplers sample result sample end see org apache jmeter samplers sample result set successful boolean see org apache jmeter samplers sample result set sample label string see org apache jmeter samplers sample result set response code string see org apache jmeter samplers sample result set response message string see org apache jmeter samplers sample result set response data byte see org apache jmeter samplers sample result set data type string param context the context to run with this provides access to initialization parameters return a sample result giving the results of this sample public sample result run test java sampler context context setup values context sample result results new sample result results set response code response code results set response message response message results set sample label label if sampler data null sampler data length 0 results set sampler data sampler data if result data null result data length 0 results set response data result data get bytes results set data type sample result text record sample start time results sample start long sleep sleep time if sleep time 0 sleep mask 0 only do the calculation if it is needed long start system current time millis generate a random ish offset value using the current time sleep sleep time start sleep mask try execute the sample in this case sleep for the specified time if any if sleep 0 thread sleep sleep results set successful success catch interrupted exception e get logger warn java test interrupted results set successful true catch exception e get logger error java test error during sample e results set successful false finally record end time and populate the results results sample end if get logger is debug enabled get logger debug who ami trun test t time t results get time list parameters context return results sampleresult responsecode responsemessage label_name samplerdata responsedata sampleresult samplestart sampleresult sampleend sampleresult setsuccessful sampleresult setsamplelabel sampleresult setresponsecode sampleresult setresponsemessage sampleresult setresponsedata sampleresult setdatatype sampleresult sampleresult runtest javasamplercontext setupvalues sampleresult sampleresult setresponsecode responsecode setresponsemessage responsemessage setsamplelabel samplerdata samplerdata setsamplerdata samplerdata resultdata resultdata setresponsedata resultdata getbytes setdatatype sampleresult samplestart sleeptime sleeptime sleepmask currenttimemillis sleeptime sleepmask setsuccessful interruptedexception getlogger javatest setsuccessful getlogger javatest setsuccessful sampleend getlogger isdebugenabled getlogger whoami truntest ttime gettime listparameters do any clean up required by this test in this case no clean up is necessary but some messages are logged for debugging purposes param context the context to run with this provides access to initialization parameters public void teardown test java sampler context context get logger debug who ami tteardown test list parameters context teardowntest javasamplercontext getlogger whoami tteardowntest listparameters dump a list of the parameters in this context to the debug log param context the context which contains the initialization parameters private void list parameters java sampler context context if get logger is debug enabled iterator args it context get parameter names iterator while args it has next string name string args it next get logger debug name context get parameter name listparameters javasamplercontext getlogger isdebugenabled argsit getparameternamesiterator argsit hasnext argsit getlogger getparameter generate a string identifier of this test for debugging purposes return a string identifier for this test instance private string who ami string buffer sb new string buffer sb append thread current thread to string sb append sb append integer to hex string hash code return sb to string whoami stringbuffer stringbuffer currentthread tostring tohexstring hashcode tostring public sample result sample entry e sample result res new sample result res set sample label get name res set sampler data my string property res sample start do something res set response data my string property to lower case get bytes res set data type sample result text res sample end res set successful true return res sampleresult sampleresult sampleresult setsamplelabel getname setsamplerdata mystringproperty samplestart setresponsedata mystringproperty tolowercase getbytes setdatatype sampleresult sampleend setsuccessful automagically show up in the gui a string property public void set my string property string s my string property s setmystringproperty mystringproperty public string get my string property return my string property getmystringproperty mystringproperty private int exec state store the operator public size assertion gui init execstate sizeassertiongui public string get label resource return size assertion title non nls 1 getlabelresource size_assertion_title public test element create test element size assertion el new size assertion modify test element el return el testelement createtestelement sizeassertion sizeassertion modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element el configure test element el string size string size get text long assertion size 0 try assertion size long parse long size string catch number format exception e assertion size long max value size assertion assertion size assertion el assertion set allowed size assertion size assertion set comp oper get state save scope settings assertion testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement sizestring gettext assertionsize assertionsize parselong sizestring numberformatexception assertionsize max_value sizeassertion sizeassertion setallowedsize assertionsize setcompoper getstate savescopesettings implements j metergui component clear gui public void clear gui super clear gui size set text non nls 1 equal button set selected true notequal button set selected false greaterthan button set selected false lessthan button set selected false greaterthanequal button set selected false lessthanequal button set selected false exec state size assertion equal jmeterguicomponent cleargui cleargui cleargui settext equalbutton setselected notequalbutton setselected greaterthanbutton setselected lessthanbutton setselected greaterthanequalbutton setselected lessthanequalbutton setselected execstate sizeassertion public void configure test element el super configure el size assertion assertion size assertion el size set text string value of assertion get allowed size set state assertion get comp oper show scope settings assertion testelement sizeassertion sizeassertion settext valueof getallowedsize setstate getcompoper showscopesettings set the state of the radio button public void set state int state if state size assertion equal equal button set selected true exec state state else if state size assertion notequal notequal button set selected true exec state state else if state size assertion greaterthan greaterthan button set selected true exec state state else if state size assertion lessthan lessthan button set selected true exec state state else if state size assertion greaterthanequal greaterthanequal button set selected true exec state state else if state size assertion lessthanequal lessthanequal button set selected true exec state state setstate sizeassertion equalbutton setselected execstate sizeassertion notequalbutton setselected execstate sizeassertion greaterthanbutton setselected execstate sizeassertion lessthanbutton setselected execstate sizeassertion greaterthanequalbutton setselected execstate sizeassertion lessthanequalbutton setselected execstate get the state of the radio button public int get state return exec state getstate execstate private void init set layout new vertical layout 5 vertical layout both vertical layout top set border make border add make title panel add create scope panel user input j panel size panel new j panel size panel set border border factory create titled border border factory create etched border j meter utils get res string size assertion size test non nls 1 size panel add new j label j meter utils get res string size assertion label non nls 1 size new j text field 5 size add focus listener this size panel add size size panel add create comparator button panel add size panel setlayout verticallayout verticallayout verticallayout setborder makeborder maketitlepanel createscopepanel user_input jpanel sizepanel jpanel sizepanel setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring size_assertion_size_test sizepanel jlabel jmeterutils getresstring size_assertion_label jtextfield addfocuslistener sizepanel sizepanel createcomparatorbuttonpanel sizepanel private box create comparator button panel button group group new button group equal button create comparator button size assertion equal group non nls 1 notequal button create comparator button size assertion notequal group non nls 1 greaterthan button create comparator button size assertion greaterthan group non nls 1 lessthan button create comparator button size assertion lessthan group non nls 1 greaterthanequal button create comparator button size assertion greaterthanequal group non nls 1 lessthanequal button create comparator button size assertion lessthanequal group non nls 1 equal button set selected true exec state integer parse int equal button get action command put the check boxes in a column in a panel box check panel box create vertical box j label compare label new j label j meter utils get res string size assertion comparator label non nls 1 check panel add compare label check panel add equal button check panel add notequal button check panel add greaterthan button check panel add lessthan button check panel add greaterthanequal button check panel add lessthanequal button return check panel createcomparatorbuttonpanel buttongroup buttongroup equalbutton createcomparatorbutton sizeassertion notequalbutton createcomparatorbutton sizeassertion greaterthanbutton createcomparatorbutton sizeassertion lessthanbutton createcomparatorbutton sizeassertion greaterthanequalbutton createcomparatorbutton sizeassertion lessthanequalbutton createcomparatorbutton sizeassertion equalbutton setselected execstate parseint equalbutton getactioncommand checkpanel createverticalbox jlabel comparelabel jlabel jmeterutils getresstring size_assertion_comparator_label checkpanel comparelabel checkpanel equalbutton checkpanel notequalbutton checkpanel greaterthanbutton checkpanel lessthanbutton checkpanel greaterthanequalbutton checkpanel lessthanequalbutton checkpanel private j radio button create comparator button string name int value button group group j radio button button new j radio button name button set action command string value of value button add action listener this group add button return button jradiobutton createcomparatorbutton buttongroup jradiobutton jradiobutton setactioncommand valueof addactionlistener public void focus lost focus event e boolean is invalid false string size string size get text if size string null try long assertion size long parse long size string if assertion size 0 is invalid true catch number format exception ex is invalid true if is invalid j option pane show message dialog null j meter utils get res string size assertion input error non nls 1 error j option pane error message focuslost focusevent isinvalid sizestring gettext sizestring assertionsize parselong sizestring assertionsize isinvalid numberformatexception isinvalid isinvalid joptionpane showmessagedialog jmeterutils getresstring size_assertion_input_error joptionpane error_message public void focus gained focus event e focusgained focusevent public void action performed action event e int comparator integer parse int e get action command exec state comparator actionperformed actionevent parseint getactioncommand execstate public class test throughput controller extends j meter test case public test throughput controller string name super name testthroughputcontroller jmetertestcase testthroughputcontroller public void test by number throws exception throughput controller sub 1 new throughput controller sub 1 set style throughput controller bynumber sub 1 set max throughput 2 sub 1 add test element new test sampler one sub 1 add test element new test sampler two loop controller loop new loop controller loop set loops 5 loop add test element new test sampler zero loop add test element sub 1 loop add iteration listener sub 1 loop add test element new test sampler three loop controller test new loop controller test set loops 2 test add test element loop string order new string zero one two three zero one two three zero three zero three zero three zero three zero three zero three zero three zero three sub 1 test started test set running version true sub 1 set running version true loop set running version true test initialize for int counter 0 counter order length counter test element sampler test next assert not null sampler assert equals counter counter order counter sampler get name assert null test next sub 1 test ended testbynumber throughputcontroller sub_1 throughputcontroller sub_1 setstyle throughputcontroller sub_1 setmaxthroughput sub_1 addtestelement testsampler sub_1 addtestelement testsampler loopcontroller loopcontroller setloops addtestelement testsampler addtestelement sub_1 additerationlistener sub_1 addtestelement testsampler loopcontroller loopcontroller setloops addtestelement sub_1 teststarted setrunningversion sub_1 setrunningversion setrunningversion testelement assertnotnull assertequals getname assertnull sub_1 testended public void test by number zero throws exception throughput controller sub 1 new throughput controller sub 1 set style throughput controller bynumber sub 1 set max throughput 0 sub 1 add test element new test sampler one sub 1 add test element new test sampler two loop controller controller new loop controller controller set loops 5 controller add test element new test sampler zero controller add test element sub 1 controller add iteration listener sub 1 controller add test element new test sampler three string order new string zero three zero three zero three zero three zero three int counter 0 controller set running version true sub 1 set running version true sub 1 test started controller initialize for int i 0 i 3 i test element sampler null while sampler controller next null assert equals counter counter i i order counter sampler get name counter assert equals counter order length counter 0 sub 1 test ended testbynumberzero throughputcontroller sub_1 throughputcontroller sub_1 setstyle throughputcontroller sub_1 setmaxthroughput sub_1 addtestelement testsampler sub_1 addtestelement testsampler loopcontroller loopcontroller setloops addtestelement testsampler addtestelement sub_1 additerationlistener sub_1 addtestelement testsampler setrunningversion sub_1 setrunningversion sub_1 teststarted testelement assertequals getname assertequals sub_1 testended public void test by percent33 throws exception throughput controller sub 1 new throughput controller sub 1 set style throughput controller bypercent sub 1 set percent throughput 33 33f sub 1 add test element new test sampler one sub 1 add test element new test sampler two loop controller controller new loop controller controller set loops 6 controller add test element new test sampler zero controller add test element sub 1 controller add iteration listener sub 1 controller add test element new test sampler three expected results established using the dda algorithm see http www siggraph org education materials hyper graph scanline outprims drawline htm string order new string zero 0 1 vs 1 1 0 is closer to 33 33 three zero 0 2 vs 1 2 50 0 is closer to 33 33 one two three zero 1 3 vs 2 3 33 33 is closer to 33 33 three zero 1 4 vs 2 4 25 0 is closer to 33 33 three zero 1 5 vs 2 5 40 0 is closer to 33 33 one two three zero 2 6 vs 3 6 33 33 is closer to 33 33 three etc int counter 0 controller set running version true sub 1 set running version true sub 1 test started controller initialize for int i 0 i 3 i test element sampler null while sampler controller next null assert equals counter counter i i order counter sampler get name counter assert equals counter order length counter 0 sub 1 test ended testbypercent33 throughputcontroller sub_1 throughputcontroller sub_1 setstyle throughputcontroller sub_1 setpercentthroughput sub_1 addtestelement testsampler sub_1 addtestelement testsampler loopcontroller loopcontroller setloops addtestelement testsampler addtestelement sub_1 additerationlistener sub_1 addtestelement testsampler hypergraph setrunningversion sub_1 setrunningversion sub_1 teststarted testelement assertequals getname assertequals sub_1 testended public void test by percent zero throws exception throughput controller sub 1 new throughput controller sub 1 set style throughput controller bypercent sub 1 set percent throughput 0 0f sub 1 add test element new test sampler one sub 1 add test element new test sampler two loop controller controller new loop controller controller set loops 150 controller add test element new test sampler zero controller add test element sub 1 controller add iteration listener sub 1 controller add test element new test sampler three string order new string zero three int counter 0 controller set running version true sub 1 set running version true sub 1 test started controller initialize for int i 0 i 3 i test element sampler null while sampler controller next null assert equals counter counter i i order counter order length sampler get name counter assert equals counter 150 order length counter 0 sub 1 test ended testbypercentzero throughputcontroller sub_1 throughputcontroller sub_1 setstyle throughputcontroller sub_1 setpercentthroughput sub_1 addtestelement testsampler sub_1 addtestelement testsampler loopcontroller loopcontroller setloops addtestelement testsampler addtestelement sub_1 additerationlistener sub_1 addtestelement testsampler setrunningversion sub_1 setrunningversion sub_1 teststarted testelement assertequals getname assertequals sub_1 testended public void test by percent100 throws exception throughput controller sub 1 new throughput controller sub 1 set style throughput controller bypercent sub 1 set percent throughput 100 0f sub 1 add test element new test sampler one sub 1 add test element new test sampler two loop controller controller new loop controller controller set loops 150 controller add test element new test sampler zero controller add test element sub 1 controller add iteration listener sub 1 controller add test element new test sampler three string order new string zero one two three int counter 0 controller set running version true sub 1 set running version true sub 1 test started controller initialize for int i 0 i 3 i test element sampler null while sampler controller next null assert equals counter counter i i order counter order length sampler get name counter assert equals counter 150 order length counter 0 sub 1 test ended testbypercent100 throughputcontroller sub_1 throughputcontroller sub_1 setstyle throughputcontroller sub_1 setpercentthroughput sub_1 addtestelement testsampler sub_1 addtestelement testsampler loopcontroller loopcontroller setloops addtestelement testsampler addtestelement sub_1 additerationlistener sub_1 addtestelement testsampler setrunningversion sub_1 setrunningversion sub_1 teststarted testelement assertequals getname assertequals sub_1 testended private constructor to prevent instantiation private report menu factory reportmenufactory public static void add edit menu j popup menu menu boolean removable add separator menu if removable menu add make menu item j meter utils get res string remove remove remove key strokes remove menu add make menu item j meter utils get res string cut cut cut key strokes cut menu add make menu item j meter utils get res string copy copy copy key strokes copy menu add make menu item j meter utils get res string paste paste paste key strokes paste menu add make menu item j meter utils get res string paste insert paste insert paste insert addeditmenu jpopupmenu addseparator makemenuitem jmeterutils getresstring keystrokes makemenuitem jmeterutils getresstring keystrokes makemenuitem jmeterutils getresstring keystrokes makemenuitem jmeterutils getresstring keystrokes makemenuitem jmeterutils getresstring paste_insert public static void add file menu j popup menu menu add separator menu menu add make menu item j meter utils get res string open open open menu add make menu item j meter utils get res string save as save as save as j menu item save picture make menu item j meter utils get res string save as image save image save graphics key strokes save graphics menu add save picture if report gui package get instance get current gui instanceof printable save picture set enabled false j menu item disabled make menu item j meter utils get res string disable disable disable j menu item enabled make menu item j meter utils get res string enable enable enable boolean is enabled report gui package get instance get tree listener get current node is enabled if is enabled disabled set enabled true enabled set enabled false else disabled set enabled false enabled set enabled true menu add enabled menu add disabled add separator menu menu add make menu item j meter utils get res string help help help addfilemenu jpopupmenu addseparator makemenuitem jmeterutils getresstring makemenuitem jmeterutils getresstring save_as save_as jmenuitem savepicture makemenuitem jmeterutils getresstring save_as_image save_graphics keystrokes save_graphics savepicture reportguipackage getinstance getcurrentgui savepicture setenabled jmenuitem makemenuitem jmeterutils getresstring jmenuitem makemenuitem jmeterutils getresstring isenabled reportguipackage getinstance gettreelistener getcurrentnode isenabled isenabled setenabled setenabled setenabled setenabled addseparator makemenuitem jmeterutils getresstring public static j menu make menus string categories string label string action command j menu add menu new j menu label for int i 0 i categories length i add menu add make menu categories i action command return add menu jmenu makemenus actioncommand jmenu addmenu jmenu addmenu makemenu actioncommand addmenu public static j popup menu get default controller menu j popup menu pop new j popup menu pop add menu factory make menus menu add controller j meter utils get res string add non nls 1 action names add pop add make menus menu parent controller j meter utils get res string insert parent non nls 1 action names add parent menu factory add edit menu pop true menu factory add file menu pop return pop jpopupmenu getdefaultcontrollermenu jpopupmenu jpopupmenu menufactory makemenus menu_add_controller jmeterutils getresstring actionnames makemenus menu_parent_controller jmeterutils getresstring insert_parent actionnames add_parent menufactory addeditmenu menufactory addfilemenu public static j popup menu get default config element menu j popup menu pop new j popup menu menu factory add edit menu pop true menu factory add file menu pop return pop jpopupmenu getdefaultconfigelementmenu jpopupmenu jpopupmenu menufactory addeditmenu menufactory addfilemenu public static j popup menu get default visualizer menu j popup menu pop new j popup menu menu factory add edit menu pop true menu factory add file menu pop return pop jpopupmenu getdefaultvisualizermenu jpopupmenu jpopupmenu menufactory addeditmenu menufactory addfilemenu public static j popup menu get default timer menu j popup menu pop new j popup menu menu factory add edit menu pop true menu factory add file menu pop return pop jpopupmenu getdefaulttimermenu jpopupmenu jpopupmenu menufactory addeditmenu menufactory addfilemenu public static j popup menu get default assertion menu j popup menu pop new j popup menu menu factory add edit menu pop true menu factory add file menu pop return pop jpopupmenu getdefaultassertionmenu jpopupmenu jpopupmenu menufactory addeditmenu menufactory addfilemenu public static j popup menu get default extractor menu j popup menu pop new j popup menu menu factory add edit menu pop true menu factory add file menu pop return pop jpopupmenu getdefaultextractormenu jpopupmenu jpopupmenu menufactory addeditmenu menufactory addfilemenu public static j menu make menu string category string action command return make menu collection menu map get category action command j meter utils get res string category jmenu makemenu actioncommand makemenu menumap actioncommand jmeterutils getresstring public static j menu make menu collection menu info string action command string menu name iterator iter menu info iterator j menu menu new j menu menu name while iter has next menu info info menu info iter next menu add make menu item info get label info get class name action command return menu jmenu makemenu menuinfo actioncommand menuname menuinfo jmenu jmenu menuname hasnext menuinfo menuinfo makemenuitem getlabel getclassname actioncommand public static void set enabled j menu menu if menu get sub elements length 0 menu set enabled false setenabled jmenu getsubelements setenabled public static j menu item make menu item string label string name string action command j menu item new menu choice new j menu item label new menu choice set name name new menu choice add action listener report action router get instance if action command null new menu choice set action command action command return new menu choice jmenuitem makemenuitem actioncommand jmenuitem newmenuchoice jmenuitem newmenuchoice setname newmenuchoice addactionlistener reportactionrouter getinstance actioncommand newmenuchoice setactioncommand actioncommand newmenuchoice public static j menu item make menu item string label string name string action command key stroke accel j menu item item make menu item label name action command item set accelerator accel return item jmenuitem makemenuitem actioncommand keystroke jmenuitem makemenuitem actioncommand setaccelerator private static void initialize menus try list gui classes class finder find classes that extend j meter utils get search paths new class j metergui component class test bean class controllers new linked list config elements new linked list listeners new linked list post processors new linked list pre processors new linked list tables new linked list report page new linked list non test elements new linked list menu map put config elements config elements menu map put controllers controllers menu map put listeners listeners menu map put non test elements non test elements menu map put post processors post processors menu map put pre processors pre processors menu map put report page report page menu map put tables tables collections sort gui classes iterator iter gui classes iterator while iter has next string name string iter next j meter tree node and test beangui are special gui classes and aren t intended to be added to menus todo find a better way of checking this if name ends with j meter tree node name ends with test beangui continue don t try to instantiate these j metergui component item try class c class for name name if test bean class is assignable from c item new test beangui c else item j metergui component c new instance catch no class def found error e log warn missing jar could not create name e continue catch throwable e log warn could not instantiate name e continue if elements to skip contains name elements to skip contains item get static label log info skipping name continue else elements to skip add name collection categories item get menu categories if categories null log debug name participates in no menus continue if categories contains post processors post processors add new menu info item get static label name if categories contains pre processors pre processors add new menu info item get static label name if categories contains controllers controllers add new menu info item get static label name if categories contains non test elements non test elements add new menu info item get static label name if categories contains listeners listeners add new menu info item get static label name if categories contains config elements config elements add new menu info item get static label name if categories contains tables tables add new menu info item get static label name if categories contains report page report page add new menu info item get static label name catch exception e log error e initializemenus guiclasses classfinder findclassesthatextend jmeterutils getsearchpaths jmeterguicomponent testbean linkedlist configelements linkedlist linkedlist postprocessors linkedlist preprocessors linkedlist linkedlist reportpage linkedlist nontestelements linkedlist menumap config_elements configelements menumap menumap menumap non_test_elements nontestelements menumap post_processors postprocessors menumap pre_processors preprocessors menumap report_page reportpage menumap guiclasses guiclasses hasnext jmetertreenode testbeangui endswith jmetertreenode endswith testbeangui jmeterguicomponent forname testbean isassignablefrom testbeangui jmeterguicomponent newinstance noclassdeffounderror elementstoskip elementstoskip getstaticlabel elementstoskip getmenucategories post_processors postprocessors menuinfo getstaticlabel pre_processors preprocessors menuinfo getstaticlabel menuinfo getstaticlabel non_test_elements nontestelements menuinfo getstaticlabel menuinfo getstaticlabel config_elements configelements menuinfo getstaticlabel menuinfo getstaticlabel report_page reportpage menuinfo getstaticlabel private static void add separator j popup menu menu menu element elements menu get sub elements if elements length 0 elements elements length 1 instanceof j popup menu separator menu add separator addseparator jpopupmenu menuelement getsubelements jpopupmenu addseparator public csv read csvread see org apache jmeter functions function execute sample result sampler public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception string my value non nls 1 string file name org apache jmeter engine util compound variable values 0 execute string column or next org apache jmeter engine util compound variable values 1 execute log debug execute file name column or next process csvread filename alias if column or next starts with non nls 1 file wrapper open file name column or next all done so return return non nls 1 if argument is next go to the next line if column or next equals next column or next equals next non nls 1 non nls 2 file wrapper end row file name all done now so return the empty string this allows the caller to append csvread file next to the last instance of csvread file col n b it is important not to read any further lines at this point otherwise the wrong line can be retrieved when using multiple threads return non nls 1 try int column index integer parse int column or next what column is wanted my value file wrapper get column file name column index catch number format exception e log warn thread current thread get name can t parse column number column or next e to string catch index out of bounds exception e log warn thread current thread get name invalid column number column or next at row file wrapper get current row file name e to string log debug execute value my value return my value sampleresult sampleresult previousresult currentsampler invalidvariableexception myvalue filename compoundvariable columnornext compoundvariable filename columnornext __csvread columnornext startswith filewrapper filename columnornext columnornext columnornext filewrapper endrow filename __csvread __csvread columnindex parseint columnornext myvalue filewrapper getcolumn filename columnindex numberformatexception currentthread getname columnornext tostring indexoutofboundsexception currentthread getname columnornext filewrapper getcurrentrow filename tostring myvalue myvalue see org apache jmeter functions function get argument desc public list get argument desc return desc getargumentdesc getargumentdesc see org apache jmeter functions function get reference key public string get reference key return key getreferencekey getreferencekey see org apache jmeter functions function set parameters collection public synchronized void set parameters collection parameters throws invalid variable exception log debug set parameter collection size parameters size values parameters to array if log is debug enabled for int i 0 i parameters size i log debug i compound variable values i execute check parameter count parameters 2 need to reset the containers for repeated runs about the only way for functions to detect that a run is starting seems to be the set parameters call file wrapper clear all todo only clear the relevant entry if possible setparameters setparameters invalidvariableexception setparameter toarray isdebugenabled compoundvariable checkparametercount setparameters filewrapper clearall public class record controller extends logic controller gui public string get label resource return record controller title non nls 1 recordcontroller logiccontrollergui getlabelresource record_controller_title public test element create test element recording controller con new recording controller this configure test element con return con testelement createtestelement recordingcontroller recordingcontroller configuretestelement p b n b set parameters and execute are called from different threads so both must be synchronized unless there are no parameters to save b p see function execute sample result sampler setparameters sampleresult public string execute throws invalid variable exception j meter context context j meter context service get context sample result previous result context get previous result sampler current sampler context get current sampler return execute previous result current sampler invalidvariableexception jmetercontext jmetercontextservice getcontext sampleresult previousresult getpreviousresult currentsampler getcurrentsampler previousresult currentsampler p b n b set parameters and execute are called from different threads so both must be synchronized unless there are no parameters to save b p see function set parameters collection br note this is always called even if no parameters are provided versions of j meter after 2 3 1 setparameters setparameters jmeter abstract public void set parameters collection parameters throws invalid variable exception see function get reference key abstract public string get reference key setparameters invalidvariableexception getreferencekey getreferencekey abstract public string get reference key protected j meter variables get variables return j meter context service get context get variables getreferencekey jmetervariables getvariables jmetercontextservice getcontext getvariables utility method to check parameter counts param parameters collection of parameters param min minimum number of parameters allowed param max maximum number of parameters allowed throws invalid variable exception if the number of parameters is incorrect protected void check parameter count collection parameters int min int max throws invalid variable exception int num parameters size if num max num min throw new invalid variable exception get reference key called with wrong number of parameters actual num min max expected min expected min and max invalidvariableexception checkparametercount invalidvariableexception invalidvariableexception getreferencekey utility method to check parameter counts param parameters collection of parameters param count number of parameters expected throws invalid variable exception if the number of parameters is incorrect protected void check parameter count collection parameters int count throws invalid variable exception int num parameters size if num count throw new invalid variable exception get reference key called with wrong number of parameters actual num expected count invalidvariableexception checkparametercount invalidvariableexception invalidvariableexception getreferencekey utility method to check parameter counts param parameters collection of parameters param minimum number of parameters expected throws invalid variable exception if the number of parameters is incorrect protected void check min parameter count collection parameters int minimum throws invalid variable exception int num parameters size if num minimum throw new invalid variable exception get reference key called with wrong number of parameters actual num expected at least minimum invalidvariableexception checkminparametercount invalidvariableexception invalidvariableexception getreferencekey private transient boolean has init file false public bean shell test element super init hasinitfile beanshelltestelement protected abstract string get init file property getinitfileproperty protected bean shell interpreter get bean shell interpreter if is reset interpreter try bsh interpreter reset catch class not found exception e log error cannot reset bean shell e to string try bsh interpreter set props j meter utils getj meter properties catch j meter exception e log error cannot set props object e to string return bsh interpreter beanshellinterpreter getbeanshellinterpreter isresetinterpreter bshinterpreter classnotfoundexception beanshell tostring bshinterpreter jmeterutils getjmeterproperties jmeterexception tostring bshinterpreter private void init parameters ensure variables are not null filename script try string init file name j meter utils get property get init file property has init file init file name null bsh interpreter new bean shell interpreter init file name log catch class not found exception e log error cannot find bean shell e to string initfilename jmeterutils getproperty getinitfileproperty hasinitfile initfilename bshinterpreter beanshellinterpreter initfilename classnotfoundexception beanshell tostring protected object read resolve init return this readresolve public object clone bean shell test element o bean shell test element super clone o init return o beanshelltestelement beanshelltestelement protected object process file or script bean shell interpreter bsh throws j meter exception string file name get filename bsh set file name get filename non nls 1 set params as a single line bsh set parameters get parameters non nls 1 and set as an array bsh set bsh args non nls 1 j orphan utils split get parameters non nls 1 if file name length 0 return bsh eval get script return bsh source file name processfileorscript beanshellinterpreter jmeterexception filename getfilename filename getfilename getparameters jorphanutils getparameters filename getscript filename return the script test bean version must be overridden for subclasses that don t implement test bean otherwise the clone method won t work return the script to execute public string get script return script testbean testbean getscript set the script test bean version must be overridden for subclasses that don t implement test bean otherwise the clone method won t work param s the script to execute may be blank public void set script string s script s testbean testbean setscript public void thread started if bsh interpreter null has init file return try bsh interpreter eval no log thread started non nls 1 catch j meter exception ignored log debug get class get name ignored get localized message non nls 1 threadstarted bshinterpreter hasinitfile bshinterpreter evalnolog threadstarted jmeterexception getclass getname getlocalizedmessage public void thread finished if bsh interpreter null has init file return try bsh interpreter eval no log thread finished non nls 1 catch j meter exception ignored log debug get class get name ignored get localized message non nls 1 threadfinished bshinterpreter hasinitfile bshinterpreter evalnolog threadfinished jmeterexception getclass getname getlocalizedmessage public void test ended if bsh interpreter null has init file return try bsh interpreter eval no log test ended non nls 1 catch j meter exception ignored log debug get class get name ignored get localized message non nls 1 testended bshinterpreter hasinitfile bshinterpreter evalnolog testended jmeterexception getclass getname getlocalizedmessage public void test ended string host if bsh interpreter null has init file return try bsh interpreter eval new string buffer test ended non nls 1 append host append non nls 1 to string non nls 1 catch j meter exception ignored log debug get class get name ignored get localized message non nls 1 testended bshinterpreter hasinitfile bshinterpreter stringbuffer testended tostring jmeterexception getclass getname getlocalizedmessage public void test iteration start loop iteration event event not implemented testiterationstart loopiterationevent public void test started if bsh interpreter null has init file return try bsh interpreter eval no log test started non nls 1 catch j meter exception ignored log debug get class get name ignored get localized message non nls 1 teststarted bshinterpreter hasinitfile bshinterpreter evalnolog teststarted jmeterexception getclass getname getlocalizedmessage public void test started string host if bsh interpreter null has init file return try bsh interpreter eval new string buffer test started non nls 1 append host append non nls 1 to string non nls 1 catch j meter exception ignored log debug get class get name ignored get localized message non nls 1 teststarted bshinterpreter hasinitfile bshinterpreter stringbuffer teststarted tostring jmeterexception getclass getname getlocalizedmessage public string get parameters return parameters getparameters public void set parameters string s parameters s setparameters public string get filename return filename getfilename public void set filename string s filename s setfilename public boolean is reset interpreter return reset interpreter isresetinterpreter resetinterpreter public void set reset interpreter boolean b reset interpreter b setresetinterpreter resetinterpreter parses the response data using regular expressions and saving the results into variables for use later in the test see org apache jmeter processor post processor process public void process init template j meter context context get thread context sample result previous result context get previous result if previous result null return log debug regex extractor processing result fetch some variables j meter variables vars context get variables string ref name get ref name int match number get match number final string default value get default value if default value length 0 only replace default if it is provided vars put ref name default value perl5 matcher matcher j meter utils get matcher string input string use url previous result get url as string bug 39707 use headers previous result get response headers use code previous result get response code bug 43451 use message previous result get response message bug 43451 use unescaped body string escape utils unescape html previous result get response data as string previous result get response data as string bug 36898 if log is debug enabled log debug input input string pattern matcher input input new pattern matcher input input string string regex get regex if log is debug enabled log debug regex regex try pattern pattern j meter utils get pattern cache get pattern regex perl5 compiler read only mask list matches new array list int x 0 boolean done false do if matcher contains input pattern log debug regex extractor match found matches add matcher get match else done true x while x match number done int prev count 0 string prev string vars get ref name ref match nr if prev string null vars remove ref name ref match nr ensure old value is not left defined try prev count integer parse int prev string catch number format exception e1 log warn could not parse prev string e1 int match count 0 number of refname n variable sets to keep try match result match if match number 0 original match behaviour match get correct match matches match number if match null vars put ref name generate result match save groups vars ref name match else refname has already been set to the default if present remove groups vars ref name else 0 means we save all the matches remove groups vars ref name remove any single matches match count matches size vars put ref name ref match nr integer to string match count save the count for int i 1 i match count i match get correct match matches i if match null final string refname n new string buffer ref name append underscore append i to string vars put refname n generate result match save groups vars refname n match remove any left over variables for int i match count 1 i prev count i final string refname n new string buffer ref name append underscore append i to string vars remove refname n remove groups vars refname n catch runtime exception e log warn error while generating result catch malformed cache pattern exception e log warn error in pattern regex postprocessor inittemplate jmetercontext getthreadcontext sampleresult previousresult getpreviousresult previousresult regexextractor jmetervariables getvariables refname getrefname matchnumber getmatchnumber defaultvalue getdefaultvalue defaultvalue refname defaultvalue perl5matcher jmeterutils getmatcher inputstring useurl previousresult geturlasstring useheaders previousresult getresponseheaders usecode previousresult getresponsecode usemessage previousresult getresponsemessage useunescapedbody stringescapeutils unescapehtml previousresult getresponsedataasstring previousresult getresponsedataasstring isdebugenabled inputstring patternmatcherinput patternmatcherinput inputstring getregex isdebugenabled jmeterutils getpatterncache getpattern perl5compiler read_only_mask arraylist regexextractor getmatch matchnumber prevcount prevstring refname ref_match_nr prevstring refname ref_match_nr prevcount parseint prevstring numberformatexception prevstring matchcount refname_n matchresult matchnumber getcorrectmatch matchnumber refname generateresult savegroups refname removegroups refname removegroups refname matchcount refname ref_match_nr tostring matchcount matchcount getcorrectmatch refname_n stringbuffer refname tostring refname_n generateresult savegroups refname_n matchcount prevcount refname_n stringbuffer refname tostring refname_n removegroups refname_n runtimeexception malformedcachepatternexception creates the variables br basename gn where n 0 of groups br basename g number of groups apart from g0 private void save groups j meter variables vars string basename match result match string buffer buf new string buffer buf append basename buf append g non nls 1 int pfxlen buf length string prev string vars get buf to string int previous 0 if prev string null try previous integer parse int prev string catch number format exception e log warn could not parse prev string e note match groups includes group 0 final int groups match groups for int x 0 x groups x buf append x vars put buf to string match group x buf set length pfxlen vars put buf to string integer to string groups 1 for int i groups i previous i buf append i vars remove buf to string remove the remaining gn vars buf set length pfxlen basename_gn basename_g savegroups jmetervariables matchresult stringbuffer stringbuffer _g prevstring tostring prevstring parseint prevstring numberformatexception prevstring tostring setlength tostring tostring tostring _gn setlength removes the variables br basename gn where n 0 of groups br basename g number of groups apart from g0 private void remove groups j meter variables vars string basename string buffer buf new string buffer buf append basename buf append g non nls 1 int pfxlen buf length how many groups are there int groups try groups integer parse int vars get buf to string catch number format exception e groups 0 vars remove buf to string remove the group count for int i 0 i groups i buf append i vars remove buf to string remove the g0 g1 gn vars buf set length pfxlen basename_gn basename_g removegroups jmetervariables stringbuffer stringbuffer _g parseint tostring numberformatexception tostring tostring setlength public object clone regex extractor cloned regex extractor super clone cloned template this template return cloned regexextractor regexextractor private string generate result match result match string buffer result new string buffer for int a 0 a template length a log debug regex extractor template piece a template a if template a instanceof string result append template a else result append match group integer template a int value log debug regex extractor result result to string return result to string generateresult matchresult stringbuffer stringbuffer regexextractor intvalue tostring tostring private void init template if template null return list pieces new array list list combined new linked list string raw template get template pattern matcher matcher j meter utils get matcher pattern template pattern j meter utils get pattern cache get pattern d non nls 1 perl5 compiler read only mask perl5 compiler singleline mask log debug pattern template pattern log debug template raw template util split pieces matcher template pattern raw template pattern matcher input input new pattern matcher input raw template boolean starts with is first element group raw template log debug template split into pieces size pieces starts with starts with if starts with pieces remove 0 remove initial empty entry iterator iter pieces iterator while iter has next boolean match exists matcher contains input template pattern if starts with if match exists combined add new integer matcher get match group 1 combined add iter next else combined add iter next if match exists combined add new integer matcher get match group 1 if matcher contains input template pattern log debug template does end with template pattern combined add new integer matcher get match group 1 template combined to array inittemplate arraylist linkedlist rawtemplate gettemplate patternmatcher jmeterutils getmatcher templatepattern jmeterutils getpatterncache getpattern perl5compiler read_only_mask perl5compiler singleline_mask templatepattern rawtemplate templatepattern rawtemplate patternmatcherinput patternmatcherinput rawtemplate startswith isfirstelementgroup rawtemplate startswith startswith hasnext matchexists templatepattern startswith matchexists getmatch matchexists getmatch templatepattern getmatch toarray private boolean is first element group string raw data try pattern pattern j meter utils get pattern cache get pattern d non nls 1 perl5 compiler read only mask perl5 compiler singleline mask return j meter utils get matcher contains raw data pattern catch runtime exception e log error e return false isfirstelementgroup rawdata jmeterutils getpatterncache getpattern perl5compiler read_only_mask perl5compiler singleline_mask jmeterutils getmatcher rawdata runtimeexception grab the appropriate result from the list param matches list of matches param entry the entry number in the list return match result private match result get correct match list matches int entry int match size matches size if match size 0 entry match size return null if entry 0 random match return match result matches get j meter utils get random int match size return match result matches get entry 1 matchresult matchresult getcorrectmatch matchsize matchsize matchsize matchresult jmeterutils getrandomint matchsize matchresult public void set regex string regex set property regex regex setregex setproperty public string get regex return get property as string regex getregex getpropertyasstring public void set ref name string ref name set property refname ref name setrefname refname setproperty refname public string get ref name return get property as string refname getrefname getpropertyasstring set which match to use this can be any positive number indicating the exact match to use or 0 which is interpreted as meaning random param match number public void set match number int match number set property new integer property match number match number matchnumber setmatchnumber matchnumber setproperty integerproperty match_number matchnumber public void set match number string match number set property match number match number setmatchnumber matchnumber setproperty match_number matchnumber public int get match number return get property as int match number getmatchnumber getpropertyasint match_number public string get match number as string return get property as string match number getmatchnumberasstring getpropertyasstring match_number sets the value of the variable if no matches are found param default value public void set default value string default value set property default default value defaultvalue setdefaultvalue defaultvalue setproperty defaultvalue public string get default value return get property as string default getdefaultvalue getpropertyasstring public void set template string template set property template template settemplate setproperty public string get template return get property as string template gettemplate getpropertyasstring public boolean use headers return use hdrs equals ignore case get property as string match against useheaders use_hdrs equalsignorecase getpropertyasstring match_against allow for property not yet being set probably only applies to test cases public boolean use body string prop get property as string match against return prop length 0 use body equals ignore case prop non nls 1 usebody getpropertyasstring match_against use_body equalsignorecase public boolean use unescaped body string prop get property as string match against return use body unescaped equals ignore case prop non nls 1 useunescapedbody getpropertyasstring match_against use_body_unescaped equalsignorecase public boolean use url string prop get property as string match against return use url equals ignore case prop useurl getpropertyasstring match_against use_url equalsignorecase public boolean use code string prop get property as string match against return use code equals ignore case prop usecode getpropertyasstring match_against use_code equalsignorecase public boolean use message string prop get property as string match against return use message equals ignore case prop usemessage getpropertyasstring match_against use_message equalsignorecase public void set use field string action command set property match against action command setusefield actioncommand setproperty match_against actioncommand constructor for the login config object public login config loginconfig loginconfig sets the username attribute of the login config object param username the new username value public void set username string username set property new string property config test element username username loginconfig setusername setproperty stringproperty configtestelement sets the password attribute of the login config object param password the new password value public void set password string password set property new string property config test element password password loginconfig setpassword setproperty stringproperty configtestelement gets the username attribute of the login config object return the username value public string get username return get property as string config test element username loginconfig getusername getpropertyasstring configtestelement gets the password attribute of the login config object return the password value public string get password return get property as string config test element password loginconfig getpassword getpropertyasstring configtestelement public string to string return get username get password non nls 1 tostring getusername getpassword protected form char set finder super formcharsetfinder add form action urls and their corresponding encodings for all forms on the page param html the html to parse for form encodings param form encodings the map where form encodings should be added param page encoding the encoding used for the whole page throws html parse exception public void add form actions and char set string html map form encodings string page encoding throws html parse exception if log is debug enabled log debug parsing html of html parser html parser null try html parser new parser html parser set inputhtml html catch exception e throw new html parse exception e now parse the dom tree try we start to iterate through the elements parse nodes html parser elements form encodings page encoding log debug end parse nodes catch parser exception e throw new html parse exception e formencodings pageencoding htmlparseexception addformactionsandcharset formencodings pageencoding htmlparseexception isdebugenabled htmlparser htmlparser htmlparser setinputhtml htmlparseexception parsenodes htmlparser formencodings pageencoding parsenodes parserexception htmlparseexception recursively parse all nodes to pick up all form encodings param e the nodes to be parsed param form encodings the map where we should add form encodings found param page encoding the encoding used for the page where the nodes are present private void parse nodes final node iterator e map form encodings string page encoding throws html parse exception parser exception while e has more nodes node node e next node a url is always in a tag if node instanceof tag continue tag tag tag node only check form tags if tag instanceof form tag find the action form url string action tag get attribute action string accept char set tag get attribute accept charset if action null action length 0 we use the page encoding where the form resides as the default encoding for the form string form char set page encoding check if we found an accept charset attribute on the form if accept char set null string char sets j orphan utils split accept char set just use the first one of the possible many charsets if char sets length 0 form char set char sets 0 trim if form char set length 0 form char set null if form char set null synchronized form encodings form encodings put action form char set second if the tag was a composite tag recursively parse its children if tag instanceof composite tag composite tag composite composite tag tag parse nodes composite elements form encodings page encoding formencodings pageencoding parsenodes nodeiterator formencodings pageencoding htmlparseexception parserexception hasmorenodes nextnode formtag getattribute acceptcharset getattribute formcharset pageencoding acceptcharset charsets jorphanutils acceptcharset charsets formcharset charsets formcharset formcharset formcharset formencodings formencodings formcharset compositetag compositetag compositetag parsenodes formencodings pageencoding public class loopback http client socket factory implements protocol socket factory public loopback http client socket factory super loopbackhttpclientsocketfactory protocolsocketfactory loopbackhttpclientsocketfactory public socket create socket string host int port inet address client host int client port throws io exception unknown host exception return new loopbackhttp socket host port client host client port createsocket inetaddress clienthost clientport ioexception unknownhostexception loopbackhttpsocket clienthost clientport public socket create socket string host int port throws io exception unknown host exception return new loopbackhttp socket host port createsocket ioexception unknownhostexception loopbackhttpsocket public socket create socket string host int port inet address local address int local port http connection params params throws io exception unknown host exception connect timeout exception int timeout params get connection timeout if timeout 0 return new loopbackhttp socket host port local address local port else return new loopbackhttp socket host port local address local port timeout createsocket inetaddress localaddress localport httpconnectionparams ioexception unknownhostexception connecttimeoutexception getconnectiontimeout loopbackhttpsocket localaddress localport loopbackhttpsocket localaddress localport convenience method to set up the necessary http client protocol and url handler only works for http client because it s not possible or at least very difficult to provide a different socket factory for the httpurl connection class public static void setup final string loopback loopback non nls 1 this ensures tha http client knows about the protocol protocol register protocol loopback new protocol loopback new loopback http client socket factory 1 now allow the url handling to work url stream handler factory ushf new url stream handler factory public url stream handler createurl stream handler string protocol if protocol equals ignore case loopback return new url stream handler protected url connection open connection url u throws io exception return null not needed for http client return null java net url seturl stream handler factory ushf httpclient httpclient httpurlconnection httpclient registerprotocol loopbackhttpclientsocketfactory urlstreamhandlerfactory urlstreamhandlerfactory urlstreamhandler createurlstreamhandler equalsignorecase urlstreamhandler urlconnection openconnection ioexception httpclient seturlstreamhandlerfactory url stream handler factory ushf new url stream handler factory public url stream handler createurl stream handler string protocol if protocol equals ignore case loopback return new url stream handler protected url connection open connection url u throws io exception return null not needed for http client return null urlstreamhandlerfactory urlstreamhandlerfactory urlstreamhandler createurlstreamhandler equalsignorecase urlstreamhandler urlconnection openconnection ioexception httpclient if protocol equals ignore case loopback return new url stream handler protected url connection open connection url u throws io exception return null not needed for http client equalsignorecase urlstreamhandler urlconnection openconnection ioexception httpclient see org apache jmeter gui action command get action names public set get action names return commands getactionnames getactionnames public void do action action event e j meter tree listener tree listener gui package get instance get tree listener j meter tree node nodes tree listener get selected nodes set copied nodes nodes doaction actionevent jmetertreelistener treelistener guipackage getinstance gettreelistener jmetertreenode treelistener getselectednodes setcopiednodes public static j meter tree node get copied nodes for int i 0 i copied nodes length i if copied nodes i null return null return clone tree nodes copied nodes jmetertreenode getcopiednodes copiednodes copiednodes clonetreenodes copiednodes public static j meter tree node get copied node if copied node null return null return clone tree node copied node jmetertreenode getcopiednode copiednode clonetreenode copiednode public static void set copied node j meter tree node node copied node clone tree node node setcopiednode jmetertreenode copiednode clonetreenode public static j meter tree node clone tree node j meter tree node node j meter tree node tree node j meter tree node node clone tree node set user object test element node get user object clone clone children tree node node return tree node jmetertreenode clonetreenode jmetertreenode jmetertreenode treenode jmetertreenode treenode setuserobject testelement getuserobject clonechildren treenode treenode public static void set copied nodes j meter tree node nodes copied nodes new j meter tree node nodes length for int i 0 i nodes length i copied nodes i clone tree node nodes i setcopiednodes jmetertreenode copiednodes jmetertreenode copiednodes clonetreenode public static j meter tree node clone tree nodes j meter tree node nodes j meter tree node tree nodes new j meter tree node nodes length for int i 0 i nodes length i tree nodes i clone tree node nodes i return tree nodes jmetertreenode clonetreenodes jmetertreenode jmetertreenode treenodes jmetertreenode treenodes clonetreenode treenodes private static void clone children j meter tree node to j meter tree node from enumeration enum from from children while enum from has more elements j meter tree node child j meter tree node enum from next element j meter tree node child clone j meter tree node child clone child clone set user object test element child get user object clone to add child clone clone children j meter tree node to get last child child clonechildren jmetertreenode jmetertreenode enumfrom enumfrom hasmoreelements jmetertreenode jmetertreenode enumfrom nextelement jmetertreenode childclone jmetertreenode childclone setuserobject testelement getuserobject childclone clonechildren jmetertreenode getlastchild the constructor is used by gui and samplers to generate request objects public standard generator super init standardgenerator param file public standard generator string file filename file init standardgenerator initialize the generator it should create the following objects p ol li listed hash tree li li thread group li li file object li li writer li ol private void init called from ctor so must not be overridable generate request listedhashtree threadgroup generaterequest create the file writer to save the jmx file protected void init stream try this output new file output stream file catch io exception exception log error exception get message filewriter initstream fileoutputstream ioexception getmessage see org apache jmeter protocol http util accesslog generator close public void close j orphan utils close quietly output j orphan utils close quietly writer jorphanutils closequietly jorphanutils closequietly see org apache jmeter protocol http util accesslog generator set host java lang string public void set host string host sample set domain host sethost sethost setdomain see org apache jmeter protocol http util accesslog generator set label java lang string public void set label string label setlabel setlabel see org apache jmeter protocol http util accesslog generator set method java lang string public void set method string post get sample set method post get setmethod setmethod post_get setmethod post_get public void set params nv pair params for int idx 0 idx params length idx sample add argument params idx get name params idx get value setparams nvpair addargument getname getvalue see org apache jmeter protocol http util accesslog generator set path java lang string public void set path string path sample set path path setpath setpath setpath see org apache jmeter protocol http util accesslog generator set port int public void set port int port sample set port port setport setport setport see org apache jmeter protocol http util accesslog generator set query string java lang string public void set query string string querystring sample parse arguments querystring setquerystring setquerystring parsearguments see org apache jmeter protocol http util accesslog generator set source logs java lang string public void set source logs string sourcefile setsourcelogs setsourcelogs see org apache jmeter protocol http util accesslog generator set target java lang object public void set target object target settarget settarget see org apache jmeter protocol http util accesslog generator generate request public object generate request sample http sampler factory new instance return sample generaterequest generaterequest httpsamplerfactory newinstance save must be called to write the jmx file otherwise it will not be saved public void save no implementation at this time since we bypass the idea of having a console tool to generate test plans instead i decided to have a sampler that uses the generator and parser directly reset the http sampler to make sure it is a new instance public void reset sample null generate request httpsampler generaterequest see command get action names public set get action names return commands getactionnames getactionnames see command do action action event public void do action action event e j meter tree node dragged nodes copy get copied nodes j meter tree listener tree listener gui package get instance get tree listener j meter tree node current node tree listener get current node if menu factory can add to current node dragged nodes for int i 0 i dragged nodes length i if dragged nodes i null add node current node dragged nodes i else toolkit get default toolkit beep gui package get instance get main frame repaint doaction actionevent doaction actionevent jmetertreenode draggednodes getcopiednodes jmetertreelistener treelistener guipackage getinstance gettreelistener jmetertreenode currentnode treelistener getcurrentnode menufactory canaddto currentnode draggednodes draggednodes draggednodes addnode currentnode draggednodes getdefaulttoolkit guipackage getinstance getmainframe private void add node j meter tree node parent j meter tree node node try add this node j meter tree node new node gui package get instance get tree model add component node get test element parent add all the child nodes of the node we are adding for int i 0 i node get child count i add node new node j meter tree node node get child at i catch illegal user action exception iuae log error iuae non nls 1 j meter utils report error to user iuae get message addnode jmetertreenode jmetertreenode jmetertreenode newnode guipackage getinstance gettreemodel addcomponent gettestelement getchildcount addnode newnode jmetertreenode getchildat illegaluseractionexception jmeterutils reporterrortouser getmessage private transient test case test instance null public j unit sampler testcase test_instance junitsampler method tries to get the set up and tear down method for the class param tc private void init method objects test case tc if this check start up tear down get do not set up tear down if setup method null setup method get method tc setup if tdown method null tdown method get method tc teardown this check start up tear down true setup teardown initmethodobjects testcase checkstartupteardown getdonotsetupteardown setup_method setup_method getmethod tdown_method tdown_method getmethod checkstartupteardown sets the classname attribute of the java config object param classname the new classname value public void set classname string classname set property classname classname javaconfig setclassname setproperty gets the classname attribute of the java config object return the classname value public string get classname return get property as string classname javaconfig getclassname getpropertyasstring set the string label used to create an instance of the test with the string constructor param constr public void set constructor string string constr set property constructorstring constr setconstructorstring setproperty get the string passed to the string constructor public string get constructor string return get property as string constructorstring getconstructorstring getpropertyasstring return the name of the method to test public string get method return get property as string method getmethod getpropertyasstring method should add the j unit testxxx method to the list at the end since the sequence matters param method name public void set method string method name set property method method name junit methodname setmethod methodname setproperty methodname get the success message public string get success return get property as string success getsuccess getpropertyasstring set the success message param success public void set success string success set property success success setsuccess setproperty get the success code defined by the user public string get success code return get property as string successcode getsuccesscode getpropertyasstring set the succes code the success code should be unique param code public void set success code string code set property successcode code setsuccesscode setproperty get the failure message public string get failure return get property as string failure getfailure getpropertyasstring set the failure message param fail public void set failure string fail set property failure fail setfailure setproperty the failure code is used by other components public string get failure code return get property as string failurecode getfailurecode getpropertyasstring provide some unique code to denote a type of failure param code public void set failure code string code set property failurecode code setfailurecode setproperty return the descriptive error for the test public string get error return get property as string error geterror getpropertyasstring provide a descriptive error for the test method for a description of the difference between failure and error please refer to the following url http junit sourceforge net doc faq faq htm tests 9 param error public void set error string error set property error error tests_9 seterror setproperty return the error code for the test method it should be an unique error code public string get error code return get property as string errorcode geterrorcode getpropertyasstring provide an unique error code for when the test does not pass the assert test param code public void set error code string code set property errorcode code seterrorcode setproperty return the comma separated string for the filter public string get filter string return get property as string filter getfilterstring getpropertyasstring set the filter string in comman separated format param text public void set filter string string text set property filter text setfilterstring setproperty if the sample shouldn t call setup teardown the method returns true it s meant for onetimesetup and onetimeteardown public boolean get do not set up tear down return get property as boolean dosetup getdonotsetupteardown getpropertyasboolean set the setup teardown option param setup public void set do not set up tear down boolean setup set property dosetup string value of setup setdonotsetupteardown setproperty valueof if append error is not set by default it is set to false which means users have to explicitly set the sampler to append the assert errors because of how junit works there should only be one error public boolean get append error return get property as boolean append error false getappenderror getpropertyasboolean append_error public void set append error boolean error set property append error string value of error setappenderror setproperty append_error valueof if append exception is not set by default it is set to false users have to explicitly set it to true to see the exceptions in the result tree public boolean get append exception return get property as boolean append exception false getappendexception getpropertyasboolean append_exception public void set append exception boolean exc set property append exception string value of exc setappendexception setproperty append_exception valueof public sample result sample entry entry sample result sresult new sample result string rlabel get constructor string if rlabel length 0 rlabel j unit sampler class get name sresult set sample label get name bug 41522 don t use rlabel here final string method name get method final string class name get classname sresult set sampler data class name method name check to see if the test class is null if it is we create a new instance this should only happen at the start of a test run if this test instance null this test instance test case get class instance class name rlabel if this test instance null init method objects this test instance create a new test result test result tr new test result this test instance set name method name try if get do not set up tear down setup method null try setup method invoke this test instance new class 0 catch invocation target exception e tr add failure this test instance new assertion failed error e get message catch illegal access exception e tr add failure this test instance new assertion failed error e get message catch illegal argument exception e tr add failure this test instance new assertion failed error e get message final method m get method this test instance method name final test case the clazz this test instance tr start test this test instance sresult sample start do not use test case run test result method since it will call set up and tear down doing that will result in calling the set up and tear down method twice and the elapsed time will include setup and teardown protectable p new protectable public void protect throws throwable m invoke the clazz new class 0 tr run protected the clazz p tr end test this test instance sresult sample end if get do not set up tear down tdown method null tdown method invoke test instance new class 0 catch invocation target exception e log warn e get message sresult set response code get error code sresult set response message get error sresult set response data e get message get bytes sresult set successful false catch illegal access exception e log warn e get message sresult set response code get error code sresult set response message get error sresult set response data e get message get bytes sresult set successful false catch comparison failure e sresult set response code get error code sresult set response message get error sresult set response data e get message get bytes sresult set successful false catch illegal argument exception e sresult set response code get error code sresult set response message get error sresult set response data e get message get bytes sresult set successful false catch exception e sresult set response code get error code sresult set response message get error sresult set response data e get message get bytes sresult set successful false catch throwable e sresult set response code get error code sresult set response message get error sresult set response data e get message get bytes sresult set successful false if tr was successful sresult set successful false string buffer buf new string buffer buf append get failure enumeration en tr errors while en has more elements object item en next element if get append error item instanceof test failure buf append trace buf append test failure item trace buf append failure buf append test failure item to string else if get append exception item instanceof throwable buf append throwable item get message sresult set response message buf to string sresult set request headers buf to string sresult set response code get failure code else this means there s no failures sresult set successful true sresult set response message get success sresult set response code get success code sresult set response data not applicable get bytes else we should log a warning but allow the test to keep running sresult set successful false this should be externalized to the properties sresult set response message failed to create an instance of the class sresult set bytes 0 sresult set content type text sresult set data type not applicable sresult set request headers not applicable return sresult sampleresult sampleresult sampleresult getconstructorstring junitsampler getname setsamplelabel getname methodname getmethod classname getclassname setsamplerdata classname methodname test_instance test_instance testcase getclassinstance classname test_instance initmethodobjects test_instance testresult testresult testresult test_instance setname methodname getdonotsetupteardown setup_method setup_method test_instance invocationtargetexception addfailure test_instance assertionfailederror getmessage illegalaccessexception addfailure test_instance assertionfailederror getmessage illegalargumentexception addfailure test_instance assertionfailederror getmessage getmethod test_instance methodname testcase theclazz test_instance starttest test_instance samplestart testcase testresult setup teardown setup teardown theclazz runprotected theclazz endtest test_instance sampleend getdonotsetupteardown tdown_method tdown_method test_instance invocationtargetexception getmessage setresponsecode geterrorcode setresponsemessage geterror setresponsedata getmessage getbytes setsuccessful illegalaccessexception getmessage setresponsecode geterrorcode setresponsemessage geterror setresponsedata getmessage getbytes setsuccessful comparisonfailure setresponsecode geterrorcode setresponsemessage geterror setresponsedata getmessage getbytes setsuccessful illegalargumentexception setresponsecode geterrorcode setresponsemessage geterror setresponsedata getmessage getbytes setsuccessful setresponsecode geterrorcode setresponsemessage geterror setresponsedata getmessage getbytes setsuccessful setresponsecode geterrorcode setresponsemessage geterror setresponsedata getmessage getbytes setsuccessful wassuccessful setsuccessful stringbuffer stringbuffer getfailure hasmoreelements nextelement getappenderror testfailure testfailure testfailure tostring getappendexception getmessage setresponsemessage tostring setrequestheaders tostring setresponsecode getfailurecode setsuccessful setresponsemessage getsuccess setresponsecode getsuccesscode setresponsedata getbytes setsuccessful setresponsemessage setbytes setcontenttype setdatatype setrequestheaders will include setup and teardown protectable p new protectable public void protect throws throwable m invoke the clazz new class 0 theclazz if the method is not able to create a new instance of the class it returns null and logs all the exceptions at warning level public static object get class instance string class name string label object testclass null if class name null constructor con null constructor str con null class theclazz null object str params null object params null try theclazz thread current thread get context class loader load class class name trim catch class not found exception e log warn class not found exception e get message if theclazz null first we see if the class declares a string constructor if it is doesn t we look for empty constructor try str con theclazz get declared constructor new class string class we have to check and make sure the constructor is accessible if we didn t it would throw an exception and cause a npe if label null label length 0 label class name if str con get modifiers modifier public str params new object label else str con null catch no such method exception e log info string constructor e get message try con theclazz get declared constructor new class 0 if con null params new object catch no such method exception e log info empty constructor e get message try if the string constructor is not null we use it if the string constructor is null we use the empty constructor to get a new instance if str con null testclass str con new instance str params else if con null testclass con new instance params catch invocation target exception e log warn e get message catch instantiation exception e log info e get message catch illegal access exception e log info e get message return testclass getclassinstance classname classname strcon strparams currentthread getcontextclassloader loadclass classname classnotfoundexception classnotfoundexception getmessage strcon getdeclaredconstructor classname strcon getmodifiers strparams strcon nosuchmethodexception getmessage getdeclaredconstructor nosuchmethodexception getmessage strcon strcon newinstance strparams newinstance invocationtargetexception getmessage instantiationexception getmessage illegalaccessexception getmessage param clazz param method return the method or null if an error occurred public method get method object clazz string method if clazz null method null log info class clazz get class get name method name is method try return clazz get class get method method new class 0 catch no such method exception e log warn e get message return null getmethod getclass getname getclass getmethod nosuchmethodexception getmessage public method get run test method object clazz if clazz null log info class clazz get class get name method name is runtest try class param test result class return clazz get class get method runtest param catch no such method exception e log warn e get message return null getruntestmethod getclass getname testresult getclass getmethod nosuchmethodexception getmessage create a new loop control panel as a standalone component public loop control panel this true loopcontrolpanel loopcontrolpanel create a new loop control panel as either a standalone or an embedded component param display name indicates whether or not this component should display its name if true this is a standalone component if false this component is intended to be used as a subpanel for another component public loop control panel boolean display name this display name display name init set state 1 loopcontrolpanel displayname loopcontrolpanel displayname displayname displayname setstate a newly created component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui param element the test element to configure public void configure test element element super configure element if element instanceof loop controller set state loop controller element get loop string else set state 1 testelement testelement loopcontroller setstate loopcontroller getloopstring setstate implements j metergui component create test element public test element create test element loop controller lc new loop controller modify test element lc return lc jmeterguicomponent createtestelement testelement createtestelement loopcontroller loopcontroller modifytestelement implements j metergui component modify test element test element public void modify test element test element lc configure test element lc if lc instanceof loop controller if loops get text length 0 loop controller lc set loops loops get text else loop controller lc set loops 1 jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement loopcontroller gettext loopcontroller setloops gettext loopcontroller setloops implements j metergui component clear gui public void clear gui super clear gui loops set text 1 non nls 1 infinite set selected false jmeterguicomponent cleargui cleargui cleargui settext setselected invoked when an action occurs this implementation assumes that the target component is the infinite loops checkbox param event the event that has occurred public void action performed action event event if infinite is selected loops set text non nls 1 loops set enabled false else loops set enabled true new focus requester loops actionperformed actionevent isselected settext setenabled setenabled focusrequester public string get label resource return loop controller title non nls 1 getlabelresource loop_controller_title initialize the gui components and layout for this component private void init the loop controller panel can be displayed standalone or inside another panel for standalone we want to display the title name etc everything however if we want to display it within another panel we just display the loop count fields not the title and name standalone if display name set layout new border layout 0 5 set border make border add make title panel border layout north j panel main panel new j panel new border layout main panel add create loop count panel border layout north add main panel border layout center else embedded set layout new border layout add create loop count panel border layout north displayname setlayout borderlayout setborder makeborder maketitlepanel borderlayout jpanel mainpanel jpanel borderlayout mainpanel createloopcountpanel borderlayout mainpanel borderlayout setlayout borderlayout createloopcountpanel borderlayout create a gui panel containing the components related to the number of loops which should be executed return a gui panel containing the loop count components private j panel create loop count panel j panel loop panel new j panel new border layout 5 0 loop label j label loops label new j label j meter utils get res string iterator num non nls 1 loop panel add loops label border layout west j panel loop sub panel new j panel new border layout 5 0 text field loops new j text field 1 5 non nls 1 loops set name loops loops label set label for loops loop sub panel add loops border layout center forever checkbox infinite new j check box j meter utils get res string infinite non nls 1 infinite set action command infinite infinite add action listener this loop sub panel add infinite border layout west loop panel add loop sub panel border layout center loop panel add box create horizontal strut loops label get preferred size width loops get preferred size width infinite get preferred size width border layout north return loop panel jpanel createloopcountpanel jpanel looppanel jpanel borderlayout jlabel loopslabel jlabel jmeterutils getresstring iterator_num looppanel loopslabel borderlayout jpanel loopsubpanel jpanel borderlayout jtextfield setname loopslabel setlabelfor loopsubpanel borderlayout jcheckbox jmeterutils getresstring setactioncommand addactionlistener loopsubpanel borderlayout looppanel loopsubpanel borderlayout looppanel createhorizontalstrut loopslabel getpreferredsize getpreferredsize getpreferredsize borderlayout looppanel set the number of loops which should be reflected in the gui the loop count parameter should contain the string representation of an integer this integer will be treated as the number of loops if this integer is less than 0 the number of loops will be assumed to be infinity param loop count the string representation of the number of loops private void set state string loop count if loop count starts with non nls 1 set state 1 else loops set text loop count infinite set selected false loops set enabled true loopcount loopcount setstate loopcount loopcount startswith setstate settext loopcount setselected setenabled set the number of loops which should be reflected in the gui if the loop count is less than 0 the number of loops will be assumed to be infinity param loop count the number of loops private void set state int loop count if loop count 1 infinite set selected true loops set enabled false loops set text non nls 1 else infinite set selected false loops set enabled true loops set text integer to string loop count loopcount loopcount setstate loopcount loopcount setselected setenabled settext setselected setenabled settext tostring loopcount public class gaussian random timer extends random timer implements serializable public long delay return long math abs this random next gaussian get range super delay gaussianrandomtimer randomtimer nextgaussian getrange public string to string return j meter utils get res string gaussian timer memo non nls 1 tostring jmeterutils getresstring gaussian_timer_memo public abstract property string name if name null throw new illegal argument exception name cannot be null this name name abstractproperty illegalargumentexception public abstract property this abstractproperty protected boolean is equal type j meter property prop if this get class equals prop get class return true else return false isequaltype jmeterproperty getclass getclass see j meter property is running version public boolean is running version return running version jmeterproperty isrunningversion isrunningversion runningversion see j meter property get name public string get name return name jmeterproperty getname getname public void set name string name if name null throw new illegal argument exception name cannot be null this name name setname illegalargumentexception see j meter property set running version boolean public void set running version boolean running version this running version running version jmeterproperty setrunningversion setrunningversion runningversion runningversion runningversion protected property iterator get iterator collection values return new property iterator impl values propertyiterator getiterator propertyiteratorimpl public object clone try abstract property prop abstract property super clone prop name name prop running version running version return prop catch clone not supported exception e throw new assertion error e clone should never return null abstractproperty abstractproperty runningversion runningversion clonenotsupportedexception assertionerror returns 0 if string is invalid or null see j meter property get int value public int get int value string val get string value if val null return 0 try return integer parse int val catch number format exception e return 0 jmeterproperty getintvalue getintvalue getstringvalue parseint numberformatexception returns 0 if string is invalid or null see j meter property get long value public long get long value string val get string value if val null return 0 try return long parse long val catch number format exception e return 0 jmeterproperty getlongvalue getlongvalue getstringvalue parselong numberformatexception returns 0 if string is invalid or null see j meter property get double value public double get double value string val get string value if val null return 0 try return double parse double val catch number format exception e log error tried to parse a non number string to an integer e return 0 jmeterproperty getdoublevalue getdoublevalue getstringvalue parsedouble numberformatexception returns 0 if string is invalid or null see j meter property get float value public float get float value string val get string value if val null return 0 try return float parse float val catch number format exception e log error tried to parse a non number string to an integer e return 0 jmeterproperty getfloatvalue getfloatvalue getstringvalue parsefloat numberformatexception returns false if string is invalid or null see j meter property get boolean value public boolean get boolean value string val get string value if val null return false return boolean value of val boolean value jmeterproperty getbooleanvalue getbooleanvalue getstringvalue valueof booleanvalue determines if the two objects are equal by comparing names and values return true if names are equal and values are equal or both null public boolean equals object o if o instanceof j meter property return false if this o return true j meter property jpo j meter property o if name equals jpo get name return false string s1 get string value string s2 jpo get string value return s1 null s2 null s1 equals s2 jmeterproperty jmeterproperty jmeterproperty getname getstringvalue getstringvalue public int hash code int result 17 result result 37 name hash code name cannot be null string s get string value result result 37 s null 0 s hash code return result hashcode hashcode getstringvalue hashcode compares two j meter property object values n b does not compare names param arg0 j meter property to compare against return 0 if equal values or both values null 1 otherwise see comparable compare to object public int compare to object arg0 if arg0 instanceof j meter property we don t expect the string values to ever be null but as in bug 19499 sometimes they are so have null compare less than any other value log a warning so we can try to find the root cause of the null value string val get string value string val2 j meter property arg0 get string value if val null log warn warning unexpected null value for property name if val2 null two null values return equal return 0 else return 1 return val compare to val2 else return 1 jmeterproperty jmeterproperty compareto compareto jmeterproperty getstringvalue jmeterproperty getstringvalue compareto get the property type for this property used to convert raw values into j meter properties protected class get property type return get class jmeterproperties getpropertytype getclass protected j meter property get blank property try j meter property prop j meter property get property type new instance if prop instanceof null property return new string property return prop catch exception e return new string property jmeterproperty getblankproperty jmeterproperty jmeterproperty getpropertytype newinstance nullproperty stringproperty stringproperty protected static j meter property get blank property object item if item null return new null property if item instanceof string return new string property item to string else if item instanceof boolean return new boolean property boolean item boolean value else if item instanceof float return new float property float item float value else if item instanceof double return new double property double item double value else if item instanceof integer return new integer property integer item int value else if item instanceof long return new long property long item long value else if item instanceof long return new long property long item long value else return new string property item to string jmeterproperty getblankproperty nullproperty stringproperty tostring booleanproperty booleanvalue floatproperty floatvalue doubleproperty doublevalue integerproperty intvalue longproperty longvalue longproperty longvalue stringproperty tostring protected collection normalize list collection coll iterator iter coll iterator collection new coll null while iter has next object item iter next if new coll null try new coll collection coll get class new instance catch exception e log error bad collection e return coll new coll add convert object item if new coll null return new coll else return coll normalizelist newcoll hasnext newcoll newcoll getclass newinstance newcoll convertobject newcoll newcoll given a map it converts the map into a collection of j meter property objects appropriate for a map property object protected map normalize map map coll iterator iter coll entry set iterator map new coll null while iter has next map entry entry map entry iter next object item entry get key object prop entry get value if new coll null try new coll map coll get class new instance catch exception e log error bad collection e return coll new coll put item convert object prop if new coll null return new coll else return coll jmeterproperty mapproperty normalizemap entryset newcoll hasnext getkey getvalue newcoll newcoll getclass newinstance newcoll convertobject newcoll newcoll public static j meter property create property object item j meter property prop make property item if prop null prop get blank property item return prop jmeterproperty createproperty jmeterproperty makeproperty getblankproperty create a j meter property from an object param item object to be turned into a propery return the j meter property protected static j meter property make property object item if item instanceof j meter property return j meter property item if item instanceof test element return new test element property test element item get name test element item if item instanceof collection return new collection property item hash code collection item if item instanceof map return new map property item hash code map item return null jmeterproperty jmeterproperty jmeterproperty makeproperty jmeterproperty jmeterproperty testelement testelementproperty testelement getname testelement collectionproperty hashcode mapproperty hashcode protected j meter property convert object object item j meter property prop make property item if prop null prop get blank property prop set name item hash code prop set object value item return prop jmeterproperty convertobject jmeterproperty makeproperty getblankproperty setname hashcode setobjectvalue provides the string representation of the property return the string value public string to string n b other classes rely on this returning just the string return get string value tostring getstringvalue see org apache jmeter testelement property j meter property merge in org apache jmeter testelement property j meter property public void merge in j meter property prop jmeterproperty mergein jmeterproperty mergein jmeterproperty private string variable non nls 1 public time function super timefunction public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception string datetime if format length 0 default to milliseconds datetime long to string system current time millis else resolve any aliases string fmt string aliases get format if fmt null fmt format not found simple date format df new simple date format fmt not synchronised so can t be shared datetime df format new date if variable length 0 j meter variables vars get variables if vars null vars will be null on test plan vars put variable datetime return datetime sampleresult previousresult currentsampler invalidvariableexception tostring currenttimemillis simpledateformat simpledateformat jmetervariables getvariables testplan public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters 0 2 object values parameters to array int count values length if count 0 format compound variable values 0 execute if count 1 variable compound variable values 1 execute trim setparameters invalidvariableexception checkparametercount toarray compoundvariable compoundvariable see org apache jmeter functions function get reference key public string get reference key return key getreferencekey getreferencekey see org apache jmeter functions function get argument desc public list get argument desc return desc getargumentdesc getargumentdesc public package test string arg0 super arg0 packagetest create the csv read function and set its parameters private static csv read setcsv read params string p1 string p2 throws exception csv read cr new csv read collection parms new linked list if p1 null parms add new compound variable p1 if p2 null parms add new compound variable p2 cr set parameters parms return cr csvread csvread setcsvreadparams csvread csvread linkedlist compoundvariable compoundvariable setparameters create the string from file function and set its parameters private static string from file sff params string p1 string p2 string p3 string p4 throws exception string from file sff new string from file collection parms new linked list if p1 null parms add new compound variable p1 if p2 null parms add new compound variable p2 if p3 null parms add new compound variable p3 if p4 null parms add new compound variable p4 sff set parameters parms return sff stringfromfile stringfromfile sffparams stringfromfile stringfromfile linkedlist compoundvariable compoundvariable compoundvariable compoundvariable setparameters create the split file function and set its parameters private static split function split params string p1 string p2 string p3 throws exception split function split new split function collection parms new linked list parms add new compound variable p1 if p2 null parms add new compound variable p2 if p3 null parms add new compound variable p3 split set parameters parms return split splitfile splitfunction splitparams splitfunction splitfunction linkedlist compoundvariable compoundvariable compoundvariable setparameters create the bean shell function and set its parameters private static bean shell bshf params string p1 string p2 string p3 throws exception bean shell bsh new bean shell bsh set parameters make params p1 p2 p3 return bsh beanshell beanshell bshfparams beanshell beanshell setparameters makeparams private static collection make params string p1 string p2 string p3 collection parms new linked list if p1 null parms add new compound variable p1 if p2 null parms add new compound variable p2 if p3 null parms add new compound variable p3 return parms makeparams linkedlist compoundvariable compoundvariable compoundvariable public static test suite throws exception test suite allsuites new test suite function package test if bean shell interpreter is interpreter present final string msg bean shell jar not present tests ignored log warn msg else test suite bsh new test suite bean shell bsh add test new package test bsh1 allsuites add test bsh test suite suite new test suite single threaded suite add test new package test csv params suite add test new package test csv no file suite add test new package test csv setup suite add test new package test csv run suite add test new package test cs valias suite add test new package test csv blank line allsuites add test suite reset files suite add test new package test csv setup test suite par new active test suite parallel par add test new package test csv thread1 par add test new package test csv thread2 allsuites add test par test suite sff new test suite string from file sff add test new package test sff test1 sff add test new package test sff test2 sff add test new package test sff test3 sff add test new package test sff test4 sff add test new package test sff test5 allsuites add test sff test suite split new test suite split function split add test new package test split test1 allsuites add test split test suite xpath new test suite x path xpath add test new package test x pathtest columns xpath add test new package test x pathtest default xpath add test new package test x pathtest null xpath add test new package test x pathtestrow num xpath add test new package test x path empty xpath add test new package test x path file1 xpath add test new package test x path file2 xpath add test new package test x path no file allsuites add test xpath test suite random new test suite random random add test new package test random test1 allsuites add test random allsuites add test new package test x path setup1 test suite par2 new active test suite parallelx path1 par2 add test new package test x path thread1 par2 add test new package test x path thread2 allsuites add test par2 allsuites add test new package test x path setup2 test suite par3 new active test suite parallelx path2 par3 add test new package test x path thread1 par3 add test new package test x path thread2 allsuites add test par3 test suite variable new test suite variable variable add test new package test variable test1 allsuites add test variable test suite eval new test suite eval eval add test new package test eval test1 eval add test new package test eval test2 allsuites add test eval test suite int sum new test suite sums int sum add test new package test sum test allsuites add test int sum return allsuites testsuite testsuite packagetest beanshellinterpreter isinterpreterpresent beanshell testsuite testsuite beanshell addtest packagetest addtest testsuite testsuite singlethreaded addtest packagetest csvparams addtest packagetest csvnofile addtest packagetest csvsetup addtest packagetest csvrun addtest packagetest csvalias addtest packagetest csvblankline addtest addtest packagetest csvsetup testsuite activetestsuite addtest packagetest csvthread1 addtest packagetest csvthread2 addtest testsuite testsuite stringfromfile addtest packagetest sfftest1 addtest packagetest sfftest2 addtest packagetest sfftest3 addtest packagetest sfftest4 addtest packagetest sfftest5 addtest testsuite testsuite splitfunction addtest packagetest splittest1 addtest testsuite testsuite xpath addtest packagetest xpathtestcolumns addtest packagetest xpathtestdefault addtest packagetest xpathtestnull addtest packagetest xpathtestrownum addtest packagetest xpathempty addtest packagetest xpathfile1 addtest packagetest xpathfile2 addtest packagetest xpathnofile addtest testsuite testsuite addtest packagetest randomtest1 addtest addtest packagetest xpathsetup1 testsuite activetestsuite parallelxpath1 addtest packagetest xpaththread1 addtest packagetest xpaththread2 addtest addtest packagetest xpathsetup2 testsuite activetestsuite parallelxpath2 addtest packagetest xpaththread1 addtest packagetest xpaththread2 addtest testsuite testsuite addtest packagetest variabletest1 addtest testsuite testsuite addtest packagetest evaltest1 addtest packagetest evaltest2 addtest testsuite intsum testsuite intsum addtest packagetest sumtest addtest intsum public void set up jmctx j meter context service get context jmctx set variables new j meter variables vars jmctx get variables setup jmetercontextservice getcontext setvariables jmetervariables getvariables public void bsh1 throws exception string fn testfiles bean shell test bsh bean shell bsh try bsh bshf params null null null fail expected invalid variable exception catch invalid variable exception e try bsh bshf params fail expected invalid variable exception catch invalid variable exception e try bsh bshf params null assert equals bsh execute catch invalid variable exception e fail bean shell not present bsh bshf params 1 null null assert equals 1 bsh execute bsh bshf params 1 1 var null assert equals 2 bsh execute assert equals 2 vars get var check some initial variables bsh bshf params return thread name null null assert equals thread current thread get name bsh execute bsh bshf params return log get class get name null null assert equals log get class get name bsh execute check source works bsh bshf params source testfiles bean shell test bsh null null assert equals 9876 bsh execute check persistence bsh bshf params scr1 null null vars put scr1 var1 11 assert equals 11 bsh execute vars put scr1 var2 22 assert equals 22 bsh execute vars put scr1 x var1 assert equals 11 bsh execute vars put scr1 x assert equals 12 bsh execute vars put var1 test vars put scr1 vars get var1 assert equals test bsh execute check init file functioning j meter utils getj meter properties set property bean shell init file fn bsh bshf params scr2 null null vars put scr2 getprop bean shell init file assert equals fn bsh execute check that bsh has read the file vars put scr2 getprop avavaav default assert equals default bsh execute vars put scr2 i assert equals 1 bsh execute vars put scr2 i assert equals 2 bsh execute beanshelltest beanshell bshfparams invalidvariableexception invalidvariableexception bshfparams invalidvariableexception invalidvariableexception bshfparams assertequals invalidvariableexception beanshell bshfparams assertequals bshfparams assertequals assertequals bshfparams threadname assertequals currentthread getname bshfparams getclass getname assertequals getclass getname bshfparams beanshelltest assertequals bshfparams assertequals assertequals assertequals assertequals assertequals jmeterutils getjmeterproperties setproperty beanshell init_file bshfparams beanshell init_file assertequals assertequals assertequals assertequals public void split test1 throws exception split function split null string src try split split params a b c null null fail expected invalid variable exception wrong number of parameters catch invalid variable exception e ok src a b c split split params src var1 null assert equals src split execute assert equals src vars get var1 assert equals 3 vars get var1 n assert equals a vars get var1 1 assert equals b vars get var1 2 assert equals c vars get var1 3 assert null vars get var1 4 split split params src var2 assert equals src split execute assert equals src vars get var2 assert equals 3 vars get var2 n assert equals a vars get var2 1 assert equals b vars get var2 2 assert equals c vars get var2 3 assert null vars get var2 4 src a b c split split params src var3 assert equals src split execute assert equals src vars get var3 assert equals 3 vars get var3 n assert equals a vars get var3 1 assert equals b vars get var3 2 assert equals c vars get var3 3 assert null vars get var3 4 src a b split split params src var4 assert equals src split execute assert equals src vars get var4 assert equals 4 vars get var4 n assert equals a vars get var4 1 assert equals b vars get var4 2 assert equals vars get var4 3 assert null vars get var4 5 src a c vars put var src split split params var var null assert equals src split execute assert equals 3 vars get var n assert equals a vars get var 1 assert equals vars get var 2 assert equals c vars get var 3 assert null vars get var 4 src a b vars put var src split split params var var null assert equals src split execute assert equals 2 vars get var n assert equals a vars get var 1 assert equals b vars get var 2 assert null vars get var 3 src a c vars put var src split split params var var5 null assert equals src split execute assert equals 4 vars get var5 n assert equals a vars get var5 1 assert equals vars get var5 2 assert equals c vars get var5 3 assert equals vars get var5 4 assert null vars get var5 5 splittest1 splitfunction splitparams invalidvariableexception invalidvariableexception splitparams assertequals assertequals assertequals var1_n assertequals var1_1 assertequals var1_2 assertequals var1_3 assertnull var1_4 splitparams assertequals assertequals assertequals var2_n assertequals var2_1 assertequals var2_2 assertequals var2_3 assertnull var2_4 splitparams assertequals assertequals assertequals var3_n assertequals var3_1 assertequals var3_2 assertequals var3_3 assertnull var3_4 splitparams assertequals assertequals assertequals var4_n assertequals var4_1 assertequals var4_2 assertequals var4_3 assertnull var4_5 splitparams assertequals assertequals var_n assertequals var_1 assertequals var_2 assertequals var_3 assertnull var_4 splitparams assertequals assertequals var_n assertequals var_1 assertequals var_2 assertnull var_3 splitparams assertequals assertequals var5_n assertequals var5_1 assertequals var5_2 assertequals var5_3 assertequals var5_4 assertnull var5_5 public void sff test1 throws exception string from file sff1 sff params testfiles sff test txt 1 3 assert equals uno sff1 execute assert equals dos sff1 execute assert equals tres sff1 execute assert equals cuatro sff1 execute assert equals cinco sff1 execute assert equals one sff1 execute assert equals two sff1 execute sff1 execute sff1 execute assert equals five sff1 execute assert equals eins sff1 execute sff1 execute sff1 execute sff1 execute assert equals fuenf sff1 execute try sff1 execute fail should have thrown j meter stop thread exception catch j meter stop thread exception e expected sfftest1 stringfromfile sffparams sfftest assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals jmeterstopthreadexception jmeterstopthreadexception public void sff test2 throws exception string from file sff sff params testfiles sff test1 txt null null assert equals uno sff execute assert equals dos sff execute assert equals tres sff execute assert equals cuatro sff execute assert equals cinco sff execute assert equals uno sff execute restarts assert equals dos sff execute assert equals tres sff execute assert equals cuatro sff execute assert equals cinco sff execute sfftest2 stringfromfile sffparams sfftest1 assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals public void sff test3 throws exception string from file sff sff params testfiles sff test1 txt assert equals uno sff execute assert equals dos sff execute assert equals tres sff execute assert equals cuatro sff execute assert equals cinco sff execute assert equals uno sff execute restarts assert equals dos sff execute assert equals tres sff execute assert equals cuatro sff execute assert equals cinco sff execute sfftest3 stringfromfile sffparams sfftest1 assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals public void sff test4 throws exception string from file sff sff params xxtestfiles sff test1 txt assert equals string from file err ind sff execute assert equals string from file err ind sff execute sfftest4 stringfromfile sffparams sfftest1 assertequals stringfromfile err_ind assertequals stringfromfile err_ind test that only loops twice public void sff test5 throws exception string from file sff sff params testfiles sff test1 txt 2 assert equals uno sff execute assert equals dos sff execute assert equals tres sff execute assert equals cuatro sff execute assert equals cinco sff execute assert equals uno sff execute assert equals dos sff execute assert equals tres sff execute assert equals cuatro sff execute assert equals cinco sff execute try sff execute fail should have thrown j meter stop thread exception catch j meter stop thread exception e expected sfftest5 stringfromfile sffparams sfftest1 assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals jmeterstopthreadexception jmeterstopthreadexception private static class baton void pass done try system out println wait thread current thread get name wait 1000 catch interrupted exception e system out println e system out println wait thread current thread get name currentthread getname interruptedexception currentthread getname void done system out println done thread current thread get name notify all currentthread getname notifyall public void csv thread1 throws exception thread current thread set name one synchronized baton assert equals b1 cr1 execute null null assert equals cr4 execute null null assert equals b2 cr1 execute null null baton pass assert equals cr4 execute null null assert equals b4 cr1 execute null null assert equals cr4 execute null null baton pass assert equals b3 cr1 execute null null assert equals cr4 execute null null baton done csvthread1 currentthread setname assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals public void csv thread2 throws exception thread current thread set name two thread sleep 500 allow other thread to start synchronized baton assert equals b3 cr1 execute null null assert equals cr4 execute null null baton pass assert equals b1 cr1 execute null null assert equals cr4 execute null null assert equals b2 cr1 execute null null baton pass assert equals cr4 execute null null assert equals b4 cr1 execute null null baton done csvthread2 currentthread setname assertequals assertequals assertequals assertequals assertequals assertequals assertequals public void csv run throws exception assert equals b1 cr1 execute null null assert equals c1 cr2 execute null null assert equals d1 cr3 execute null null assert equals cr4 execute null null assert equals b2 cr1 execute null null assert equals c2 cr2 execute null null assert equals d2 cr3 execute null null assert equals cr4 execute null null assert equals b3 cr1 execute null null assert equals c3 cr2 execute null null assert equals d3 cr3 execute null null assert equals cr4 execute null null assert equals b4 cr1 execute null null assert equals c4 cr2 execute null null assert equals d4 cr3 execute null null assert equals cr4 execute null null assert equals b1 cr1 execute null null assert equals c1 cr2 execute null null assert equals d1 cr3 execute null null assert equals a1 cr5 execute null null assert equals cr6 execute null null assert equals a2 cr5 execute null null csvrun assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals public void csv params throws exception try setcsv read params null null fail should have failed catch invalid variable exception e try setcsv read params null fail should have failed catch invalid variable exception e try setcsv read params null fail should have failed catch invalid variable exception e csvparams setcsvreadparams invalidvariableexception setcsvreadparams invalidvariableexception setcsvreadparams invalidvariableexception public void csv setup throws exception cr1 setcsv read params testfiles test csv 1 cr2 setcsv read params testfiles test csv 2 cr3 setcsv read params testfiles test csv 3 cr4 setcsv read params testfiles test csv next cr5 setcsv read params 0 cr6 setcsv read params next csvsetup setcsvreadparams setcsvreadparams setcsvreadparams setcsvreadparams setcsvreadparams setcsvreadparams public void cs valias throws exception cr1 setcsv read params testfiles test csv a cr2 setcsv read params a 1 cr3 setcsv read params a next cr4 setcsv read params testfiles test csv b cr5 setcsv read params b 2 cr6 setcsv read params b next string s s cr1 execute null null open as a assert equals s s cr2 execute null null col 1 line 1 a assert equals b1 s s cr4 execute null null open as b assert equals s s cr5 execute null null col2 line 1 assert equals c1 s s cr3 execute null null a next assert equals s s cr2 execute null null col 1 line 2 a assert equals b2 s s cr5 execute null null col2 line 1 b assert equals c1 s s cr6 execute null null b next assert equals s s cr5 execute null null col2 line 2 b assert equals c2 s csvalias setcsvreadparams setcsvreadparams setcsvreadparams setcsvreadparams setcsvreadparams setcsvreadparams assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals assertequals public void csv no file throws exception string s cr1 setcsv read params xtestfiles test csv 1 log info expecting file not found s cr1 execute null null assert equals s cr2 setcsv read params xtestfiles test csv next log info expecting no entry for file s cr2 execute null null assert equals s cr3 setcsv read params xtestfiles test csv abc log info expecting file not found s cr3 execute null null assert equals s cr4 setcsv read params abc 1 log info expecting cannot open file s cr4 execute null null assert equals s csvnofile setcsvreadparams assertequals setcsvreadparams assertequals setcsvreadparams assertequals setcsvreadparams assertequals check blank lines are treated as eof public void csv blank line throws exception csv read csv1 setcsv read params testfiles testblank csv 1 csv read csv2 setcsv read params testfiles testblank csv next string s for int i 1 i 2 i s csv1 execute null null assert equals b1 s s csv2 execute null null assert equals s s csv1 execute null null assert equals b2 s s csv2 execute null null assert equals s csvblankline csvread setcsvreadparams csvread setcsvreadparams assertequals assertequals assertequals assertequals public void x pathtest null throws exception try new x path file container nosuch xml fail should not find the file catch file not found exception e xpathtestnull xpathfilecontainer filenotfoundexception public void x pathtestrow num throws exception x path file container f new x path file container build xml project target name assert not null f assert equals expected 4 lines 4 f size int my row f next row assert equals 0 my row assert equals 1 f get next row my row f next row assert equals 1 my row assert equals 2 f get next row my row f next row assert equals 2 my row assert equals 3 f get next row my row f next row assert equals 3 my row assert equals 0 f get next row my row f next row assert equals 0 my row assert equals 1 f get next row xpathtestrownum xpathfilecontainer xpathfilecontainer assertnotnull assertequals myrow nextrow assertequals myrow assertequals getnextrow myrow nextrow assertequals myrow assertequals getnextrow myrow nextrow assertequals myrow assertequals getnextrow myrow nextrow assertequals myrow assertequals getnextrow myrow nextrow assertequals myrow assertequals getnextrow public void x pathtest columns throws exception x path file container f new x path file container build xml project target name assert not null f assert true not empty f size 0 int last 0 for int i 0 i f size i last f next row log debug found i f getx path string last assert equals last 1 f size xpathtestcolumns xpathfilecontainer xpathfilecontainer assertnotnull asserttrue nextrow getxpathstring assertequals public void x pathtest default throws exception x path file container f new x path file container build xml project default assert not null f assert true not empty f size 0 assert equals install f getx path string 0 xpathtestdefault xpathfilecontainer xpathfilecontainer assertnotnull asserttrue assertequals getxpathstring public void x path empty throws exception x path xp setupx path string val xp execute assert equals val val xp execute assert equals val val xp execute assert equals val xpathempty xpath setupxpath assertequals assertequals assertequals public void x path no file throws exception x path xp setupx path no such file string val xp execute assert equals val todo should check that error has been logged xpathnofile xpath setupxpath assertequals public void x path file1 throws exception x path xp setupx path testfiles x path test xml user username assert equals u1 xp execute assert equals u2 xp execute assert equals u3 xp execute assert equals u4 xp execute assert equals u5 xp execute assert equals u1 xp execute xpathfile1 xpath setupxpath xpathtest assertequals assertequals assertequals assertequals assertequals assertequals public void x path file2 throws exception x path xp1 setupx path testfiles x path test xml user username x path xp1a setupx path testfiles x path test xml user username x path xp2 setupx path testfiles x path test xml user password x path xp2a setupx path testfiles x path test xml user password assert equals u1 xp1 execute assert equals p1 xp2 execute assert equals p2 xp2 execute assert equals u2 xp1a execute assert equals u3 xp1 execute assert equals u4 xp1 execute assert equals p3 xp2a execute xpathfile2 xpath setupxpath xpathtest xpath setupxpath xpathtest xpath setupxpath xpathtest xpath setupxpath xpathtest assertequals assertequals assertequals assertequals assertequals assertequals assertequals private static x path sxp1 sxp2 use same x path for both threads public void x path setup1 throws exception sxp1 setupx path testfiles x path test xml user username sxp2 sxp1 xpath xpath xpathsetup1 setupxpath xpathtest use different x path for both threads public void x path setup2 throws exception sxp1 setupx path testfiles x path test xml user username sxp2 setupx path testfiles x path test xml user username xpath xpathsetup2 setupxpath xpathtest setupxpath xpathtest public void x path thread1 throws exception thread current thread set name x path one synchronized baton assert equals u1 sxp1 execute assert equals u2 sxp1 execute baton pass assert equals u5 sxp1 execute baton pass assert equals u2 sxp1 execute baton done xpaththread1 currentthread setname xpathone assertequals assertequals assertequals assertequals public void x path thread2 throws exception thread current thread set name x path two thread sleep 500 synchronized baton assert equals u3 sxp2 execute assert equals u4 sxp2 execute baton pass assert equals u1 sxp2 execute baton pass assert equals u3 sxp2 execute baton done xpaththread2 currentthread setname xpathtwo assertequals assertequals assertequals assertequals private x path setupx path string file string expr throws exception collection parms new linked list parms add new compound variable file parms add new compound variable expr x path xp new x path xp set parameters parms return xp xpath setupxpath linkedlist compoundvariable compoundvariable xpath xpath setparameters public void random test1 throws exception random r new random collection parms make params 0 10000000000 var r set parameters parms string s r execute null null randomtest1 makeparams setparameters public void variable test1 throws exception variable r new variable vars put a 1 a1 vars put a 2 a2 vars put one 1 vars put two 2 vars put v a collection parms string s parms make params v null null r set parameters parms s r execute null null assert equals a s parms make params x null null r set parameters parms s r execute null null assert equals x s parms make params a x null null r set parameters parms s r execute null null assert equals a x s parms make params a 1 null null r set parameters parms s r execute null null assert equals a1 s parms make params a 2 null null r set parameters parms s r execute null null assert equals a2 s parms make params a two null null r set parameters parms s r execute null null assert equals a2 s parms make params v one null null r set parameters parms s r execute null null assert equals a1 s variabletest1 a_1 a_2 makeparams setparameters assertequals makeparams setparameters assertequals makeparams setparameters assertequals makeparams a_1 setparameters assertequals makeparams a_2 setparameters assertequals makeparams a_ setparameters assertequals makeparams _ setparameters assertequals public void eval test1 throws exception eval function eval new eval function vars put query select column from table vars put column name vars put table customers collection parms string s parms make params query null null eval set parameters parms s eval execute null null assert equals select name from customers s evaltest1 evalfunction evalfunction makeparams setparameters assertequals public void eval test2 throws exception eval var function eval var new eval var function vars put query select column from table vars put column name vars put table customers collection parms string s parms make params query null null eval var set parameters parms s eval var execute null null assert equals select name from customers s evaltest2 evalvarfunction evalvar evalvarfunction makeparams evalvar setparameters evalvar assertequals public void sum test throws exception int sum is new int sum check invalid parameter counts is 2 check sum is 3 new string 1 2 check sum no var is 3 new string 1 2 check sum is 1 new string 1 1 1 1 2 1 check sum no var is 1 new string 1 1 1 1 2 1 string max int val integer to string integer max value string min int val integer to string integer min value check sum is max int val new string max int val 0 check sum is min int val new string max int val 1 wrap round check is null prevent accidental use below long sum ls new long sum check invalid parameter counts ls 2 check sum ls 3 new string 1 2 check sum ls 1 new string 1 1 1 1 1 0 check sum no var ls 3 new string 1 2 check sum no var ls 1 new string 1 1 1 1 1 0 string maxintval 1 long to string 1 long integer max value check sum ls max int val new string max int val 0 check sum ls maxintval 1 new string max int val 1 no wrap round check string max long val long to string long max value string min long val long to string long min value check sum ls max long val new string max long val 0 check sum ls min long val new string max long val 1 wrap round check sumtest intsum intsum checkinvalidparametercounts checksum checksumnovar checksum checksumnovar maxintval tostring max_value minintval tostring min_value checksum maxintval maxintval checksum minintval maxintval longsum longsum checkinvalidparametercounts checksum checksum checksumnovar checksumnovar maxintval_1 tostring max_value checksum maxintval maxintval checksum maxintval_1 maxintval maxlongval tostring max_value minlongval tostring min_value checksum maxlongval maxlongval checksum minlongval maxlongval perform a sum and check the results private void check sum abstract function func string value string addends throws exception collection parms new linked list for int i 0 i addends length i parms add new compound variable addends i parms add new compound variable result func set parameters parms assert equals value func execute null null assert equals value vars get object result checksum abstractfunction linkedlist compoundvariable compoundvariable setparameters assertequals assertequals getobject perform a sum and check the results private void check sum no var abstract function func string value string addends throws exception collection parms new linked list for int i 0 i addends length i parms add new compound variable addends i func set parameters parms assert equals value func execute null null checksumnovar abstractfunction linkedlist compoundvariable setparameters assertequals see command do action action event public void do action action event e doaction actionevent doaction actionevent see command get action names abstract public set get action names getactionnames getactionnames param e protected void popup should save action event e log debug popup should save if report gui package get instance get report plan file null if j option pane show confirm dialog report gui package get instance get main frame j meter utils get res string should save j meter utils get res string warning j option pane yes no option j option pane question message j option pane yes option report action router get instance do action now new action event e get source e getid report save save popupshouldsave actionevent popupshouldsave reportguipackage getinstance getreportplanfile joptionpane showconfirmdialog reportguipackage getinstance getmainframe jmeterutils getresstring should_save jmeterutils getresstring joptionpane yes_no_option joptionpane question_message joptionpane yes_option reportactionrouter getinstance doactionnow actionevent getsource reportsave create wrapped output stream toe emulate the requested cps param out output stream param cps characters per second public slow output stream output stream out int cps super out pauser new cps pauser cps outputstream slowoutputstream outputstream cpspauser also handles write byte public void write byte b int off int len throws io exception pauser pause len out write b off len ioexception public void write int b throws io exception pauser pause 1 out write b ioexception protected bean shell bean info support class bean class super bean class property descriptor p p property reset interpreter p set value not undefined boolean true p set value default boolean false p set value not expression boolean true p set value not other boolean true create property group reset group new string reset interpreter p property parameters p set value not undefined boolean true p set value default create property group parameter group new string parameters p property filename p set value not undefined boolean true p set value default create property group filename group new string filename p property script p set value not undefined boolean true p set value default p set property editor class text area editor class create property group scripting new string script beanshellbeaninfosupport beanclass beanclass propertydescriptor resetinterpreter setvalue not_undefined setvalue setvalue not_expression setvalue not_other createpropertygroup resetgroup resetinterpreter setvalue not_undefined setvalue createpropertygroup parametergroup setvalue not_undefined setvalue createpropertygroup filenamegroup setvalue not_undefined setvalue setpropertyeditorclass textareaeditor createpropertygroup public class dynamic class loader extends url class loader public dynamic class loader url urls super urls dynamicclassloader urlclassloader dynamicclassloader public dynamic class loader url urls class loader parent super urls parent dynamicclassloader classloader public dynamic class loader url urls class loader parent url stream handler factory factory super urls parent factory dynamicclassloader classloader urlstreamhandlerfactory make the addurl method visible public void addurl url url super addurl url param urls list of ur ls to add to the thread s classloader public static void update loader url urls dynamic class loader loader dynamic class loader thread current thread get context class loader for int i 0 i urls length i loader addurl urls i urls updateloader dynamicclassloader dynamicclassloader currentthread getcontextclassloader private j check box use req msg id as correl id public jms config gui init jcheckbox usereqmsgidascorrelid jmsconfiggui clears all fields public void clear gui renamed from clear super clear gui queueu connection factory set text non nls 1 send queue set text non nls 1 receive queue set text non nls 1 j combo box one way get component list get 1 set selected item j meter utils get res string jms request non nls 1 timeout set text non nls 1 soap xml set text non nls 1 initial context factory set text non nls 1 provider url set text non nls 1 jms properties panel clear jndi properties panel clear cleargui cleargui queueuconnectionfactory settext sendqueue settext receivequeue settext jcombobox oneway getcomponentlist setselecteditem jmeterutils getresstring jms_request settext soapxml settext initialcontextfactory settext providerurl settext jmspropertiespanel jndipropertiespanel public test element create test element org activemq jndi activemq initial context factory config test element element new config test element jms sampler sampler new jms sampler this configure test element sampler transfer sampler return sampler testelement createtestelement activemqinitialcontextfactory configtestelement configtestelement jmssampler jmssampler configuretestelement private void transfer jms sampler element element set queue connection factory queueu connection factory get text element set send queue send queue get text element set receive queue receive queue get text boolean is oneway one way get text equals j meter utils get res string jms request non nls 1 element set is oneway is oneway element set non persistent use non persistent delivery is selected element set use req msg id as correl id use req msg id as correl id is selected element set timeout timeout get text element set content soap xml get text element set initial context factory initial context factory get text element set context provider provider url get text arguments jndi args arguments jndi properties panel create test element element setjndi properties jndi args arguments args arguments jms properties panel create test element element setjms properties args jmssampler setqueueconnectionfactory queueuconnectionfactory gettext setsendqueue sendqueue gettext setreceivequeue receivequeue gettext isoneway oneway gettext jmeterutils getresstring jms_request setisoneway isoneway setnonpersistent usenonpersistentdelivery isselected setusereqmsgidascorrelid usereqmsgidascorrelid isselected settimeout gettext setcontent soapxml gettext setinitialcontextfactory initialcontextfactory gettext setcontextprovider providerurl gettext jndiargs jndipropertiespanel createtestelement setjndiproperties jndiargs jmspropertiespanel createtestelement setjmsproperties param element public void modify test element test element element jms sampler sampler jms sampler element this configure test element sampler transfer sampler element set property jms sampler queue connection factory jndi queueu connection factory get text element set property jms sampler send queue send queue get text element set property jms sampler receive queue receive queue get text boolean is oneway one way get text equals j meter utils get res string jms request element set property new boolean property jms sampler is one way is oneway element set property jms sampler timeout timeout get text element set property jms sampler xml data soap xml get text element set property jms sampler jndi initial context factory initial context factory get text element set property jms sampler jndi context provider url provider url get text arguments jndi args arguments jndi properties panel create test element element set property new test element property jms sampler jndi properties jndi args arguments args arguments jms properties panel create test element element set property new test element property jms sampler jms properties args modifytestelement testelement jmssampler jmssampler configuretestelement setproperty jmssampler queue_connection_factory_jndi queueuconnectionfactory gettext setproperty jmssampler send_queue sendqueue gettext setproperty jmssampler receive_queue receivequeue gettext isoneway oneway gettext jmeterutils getresstring jms_request setproperty booleanproperty jmssampler is_one_way isoneway setproperty jmssampler gettext setproperty jmssampler xml_data soapxml gettext setproperty jmssampler jndi_initial_context_factory initialcontextfactory gettext setproperty jmssampler jndi_context_provider_url providerurl gettext jndiargs jndipropertiespanel createtestelement setproperty testelementproperty jmssampler jndi_properties jndiargs jmspropertiespanel createtestelement setproperty testelementproperty jmssampler jms_properties param el public void configure test element el super configure el jms sampler sampler jms sampler el queueu connection factory set text sampler get queue connection factory send queue set text sampler get send queue receive queue set text sampler get receive queue j combo box box j combo box one way get component list get 1 string selected null if sampler is oneway selected j meter utils get res string jms request non nls 1 else selected j meter utils get res string jms requestreply non nls 1 box set selected item selected use non persistent delivery set selected sampler is non persistent use req msg id as correl id set selected sampler is use req msg id as correl id timeout set text string value of sampler get timeout soap xml set text sampler get content initial context factory set text sampler get initial context factory provider url set text sampler get context provider jms properties panel configure sampler getjms properties test element el get property jms sampler jms properties get object value jndi properties panel configure sampler getjndi properties test element el get property jms sampler jndi properties get object value testelement jmssampler jmssampler queueuconnectionfactory settext getqueueconnectionfactory sendqueue settext getsendqueue receivequeue settext getreceivequeue jcombobox jcombobox oneway getcomponentlist isoneway jmeterutils getresstring jms_request jmeterutils getresstring jms_requestreply setselecteditem usenonpersistentdelivery setselected isnonpersistent usereqmsgidascorrelid setselected isusereqmsgidascorrelid settext valueof gettimeout soapxml settext getcontent initialcontextfactory settext getinitialcontextfactory providerurl settext getcontextprovider jmspropertiespanel getjmsproperties testelement getproperty jmssampler jms_properties getobjectvalue jndipropertiespanel getjndiproperties testelement getproperty jmssampler jndi_properties getobjectvalue initializes the configuration screen private void init set layout new border layout set border make border add make title panel border layout north box main panel box create vertical box j panel jms queueing panel new j panel new border layout jms queueing panel set border border factory create titled border border factory create etched border j meter utils get res string jms queueing non nls 1 j panel qcf panel new j panel new border layout 5 0 qcf panel add queueu connection factory border layout center jms queueing panel add qcf panel border layout north j panel send queue panel new j panel new border layout 5 0 send queue panel add send queue jms queueing panel add send queue panel border layout center j panel receive queue panel new j panel new border layout 5 0 receive queue panel add receive queue jms queueing panel add receive queue panel border layout south j panel jndi panel createjndi panel j panel message panel new j panel new border layout message panel set border border factory create titled border border factory create etched border j meter utils get res string jms message title non nls 1 use req msg id as correl id new j check box j meter utils get res string jms use req msgid as correlid false non nls 1 j panel message north panel new j panel new border layout j panel oneway panel new horizontal panel oneway panel add one way oneway panel add use req msg id as correl id message north panel add oneway panel border layout north use non persistent delivery new j check box j meter utils get res string jms use non persistent delivery false non nls 1 j panel timeout panel new horizontal panel timeout panel add timeout timeout panel add use non persistent delivery message north panel add timeout panel border layout south message panel add message north panel border layout north j panel soap xml panel new j panel new border layout soap xml panel add soap xml message panel add soap xml panel border layout center jms properties panel new arguments panel j meter utils get res string jms props non nls 1 message panel add jms properties panel border layout south main panel add jms queueing panel border layout north main panel add message panel border layout center main panel add jndi panel border layout south add main panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout mainpanel createverticalbox jpanel jmsqueueingpanel jpanel borderlayout jmsqueueingpanel setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring jms_queueing jpanel qcfpanel jpanel borderlayout qcfpanel queueuconnectionfactory borderlayout jmsqueueingpanel qcfpanel borderlayout jpanel sendqueuepanel jpanel borderlayout sendqueuepanel sendqueue jmsqueueingpanel sendqueuepanel borderlayout jpanel receivequeuepanel jpanel borderlayout receivequeuepanel receivequeue jmsqueueingpanel receivequeuepanel borderlayout jpanel jndipanel createjndipanel jpanel messagepanel jpanel borderlayout messagepanel setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring jms_message_title usereqmsgidascorrelid jcheckbox jmeterutils getresstring jms_use_req_msgid_as_correlid jpanel messagenorthpanel jpanel borderlayout jpanel onewaypanel horizontalpanel onewaypanel oneway onewaypanel usereqmsgidascorrelid messagenorthpanel onewaypanel borderlayout usenonpersistentdelivery jcheckbox jmeterutils getresstring jms_use_non_persistent_delivery jpanel timeoutpanel horizontalpanel timeoutpanel timeoutpanel usenonpersistentdelivery messagenorthpanel timeoutpanel borderlayout messagepanel messagenorthpanel borderlayout jpanel soapxmlpanel jpanel borderlayout soapxmlpanel soapxml messagepanel soapxmlpanel borderlayout jmspropertiespanel argumentspanel jmeterutils getresstring jms_props messagepanel jmspropertiespanel borderlayout mainpanel jmsqueueingpanel borderlayout mainpanel messagepanel borderlayout mainpanel jndipanel borderlayout mainpanel borderlayout creates the panel for the jndi configuration return the jndi panel private j panel createjndi panel j panel jndi panel new j panel new border layout jndi panel set border border factory create titled border border factory create etched border j meter utils get res string jms jndi props non nls 1 j panel context panel new j panel new border layout 10 0 context panel add initial context factory jndi panel add context panel border layout north j panel provider panel new j panel new border layout 10 0 provider panel add provider url jndi panel add provider panel border layout south jndi properties panel new arguments panel j meter utils get res string jms jndi props non nls 1 jndi panel add jndi properties panel return jndi panel jpanel createjndipanel jpanel jndipanel jpanel borderlayout jndipanel setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring jms_jndi_props jpanel contextpanel jpanel borderlayout contextpanel initialcontextfactory jndipanel contextpanel borderlayout jpanel providerpanel jpanel borderlayout providerpanel providerurl jndipanel providerpanel borderlayout jndipropertiespanel argumentspanel jmeterutils getresstring jms_jndi_props jndipanel jndipropertiespanel jndipanel public string get label resource return jms point to point non nls 1 todo probably wrong getlabelresource jms_point_to_point wrap an ssl socket with slow input and output streams param sock ssl socket to be wrapped param cps characters per second to emulate public slowssl socket final ssl socket sock final int cps if cps 0 throw new illegal argument exception speed cps 0 ssl sock sock cps cps sslsocket sslsocket slowsslsocket sslsocket illegalargumentexception sslsock override so we can intercept the stream public output stream get output stream throws io exception return new slow output stream ssl sock get output stream cps outputstream getoutputstream ioexception slowoutputstream sslsock getoutputstream override so we can intercept the stream public input stream get input stream throws io exception return new slow input stream ssl sock get input stream cps inputstream getinputstream ioexception slowinputstream sslsock getinputstream forward all the ssl socket methods to the input socket public void add handshake completed listener handshake completed listener arg0 ssl sock add handshake completed listener arg0 sslsocket addhandshakecompletedlistener handshakecompletedlistener sslsock addhandshakecompletedlistener public boolean get enable session creation return ssl sock get enable session creation getenablesessioncreation sslsock getenablesessioncreation public string get enabled cipher suites return ssl sock get enabled cipher suites getenabledciphersuites sslsock getenabledciphersuites public string get enabled protocols return ssl sock get enabled protocols getenabledprotocols sslsock getenabledprotocols public boolean get need client auth return ssl sock get need client auth getneedclientauth sslsock getneedclientauth public ssl session get session return ssl sock get session sslsession getsession sslsock getsession public string get supported cipher suites return ssl sock get supported cipher suites getsupportedciphersuites sslsock getsupportedciphersuites public string get supported protocols return ssl sock get supported protocols getsupportedprotocols sslsock getsupportedprotocols public boolean get use client mode return ssl sock get use client mode getuseclientmode sslsock getuseclientmode public boolean get want client auth return ssl sock get want client auth getwantclientauth sslsock getwantclientauth public void remove handshake completed listener handshake completed listener arg0 ssl sock remove handshake completed listener arg0 removehandshakecompletedlistener handshakecompletedlistener sslsock removehandshakecompletedlistener public void set enable session creation boolean arg0 ssl sock set enable session creation arg0 setenablesessioncreation sslsock setenablesessioncreation public void set enabled cipher suites string arg0 ssl sock set enabled cipher suites arg0 setenabledciphersuites sslsock setenabledciphersuites public void set enabled protocols string arg0 ssl sock set enabled protocols arg0 setenabledprotocols sslsock setenabledprotocols public void set need client auth boolean arg0 ssl sock set need client auth arg0 setneedclientauth sslsock setneedclientauth public void set use client mode boolean arg0 ssl sock set use client mode arg0 setuseclientmode sslsock setuseclientmode public void set want client auth boolean arg0 ssl sock set want client auth arg0 setwantclientauth sslsock setwantclientauth public void start handshake throws io exception ssl sock start handshake starthandshake ioexception sslsock starthandshake also forward all the socket methods public void bind socket address bindpoint throws io exception ssl sock bind bindpoint socketaddress ioexception sslsock public synchronized void close throws io exception ssl sock close ioexception sslsock public void connect socket address endpoint int timeout throws io exception ssl sock connect endpoint timeout socketaddress ioexception sslsock public void connect socket address endpoint throws io exception ssl sock connect endpoint socketaddress ioexception sslsock public socket channel get channel return ssl sock get channel socketchannel getchannel sslsock getchannel public inet address get inet address return ssl sock get inet address inetaddress getinetaddress sslsock getinetaddress public boolean get keep alive throws socket exception return ssl sock get keep alive getkeepalive socketexception sslsock getkeepalive public inet address get local address return ssl sock get local address inetaddress getlocaladdress sslsock getlocaladdress public int get local port return ssl sock get local port getlocalport sslsock getlocalport public socket address get local socket address return ssl sock get local socket address socketaddress getlocalsocketaddress sslsock getlocalsocketaddress public boolean getoob inline throws socket exception return ssl sock getoob inline getoobinline socketexception sslsock getoobinline public int get port return ssl sock get port getport sslsock getport public synchronized int get receive buffer size throws socket exception return ssl sock get receive buffer size getreceivebuffersize socketexception sslsock getreceivebuffersize public socket address get remote socket address return ssl sock get remote socket address socketaddress getremotesocketaddress sslsock getremotesocketaddress public boolean get reuse address throws socket exception return ssl sock get reuse address getreuseaddress socketexception sslsock getreuseaddress public synchronized int get send buffer size throws socket exception return ssl sock get send buffer size getsendbuffersize socketexception sslsock getsendbuffersize public int get so linger throws socket exception return ssl sock get so linger getsolinger socketexception sslsock getsolinger public synchronized int get so timeout throws socket exception return ssl sock get so timeout getsotimeout socketexception sslsock getsotimeout public boolean get tcp no delay throws socket exception return ssl sock get tcp no delay gettcpnodelay socketexception sslsock gettcpnodelay public int get traffic class throws socket exception return ssl sock get traffic class gettrafficclass socketexception sslsock gettrafficclass public boolean is bound return ssl sock is bound isbound sslsock isbound public boolean is closed return ssl sock is closed isclosed sslsock isclosed public boolean is connected return ssl sock is connected isconnected sslsock isconnected public boolean is input shutdown return ssl sock is input shutdown isinputshutdown sslsock isinputshutdown public boolean is output shutdown return ssl sock is output shutdown isoutputshutdown sslsock isoutputshutdown public void send urgent data int data throws io exception ssl sock send urgent data data sendurgentdata ioexception sslsock sendurgentdata public void set keep alive boolean on throws socket exception ssl sock set keep alive on setkeepalive socketexception sslsock setkeepalive public void setoob inline boolean on throws socket exception ssl sock setoob inline on setoobinline socketexception sslsock setoobinline public synchronized void set receive buffer size int size throws socket exception ssl sock set receive buffer size size setreceivebuffersize socketexception sslsock setreceivebuffersize public void set reuse address boolean on throws socket exception ssl sock set reuse address on setreuseaddress socketexception sslsock setreuseaddress public synchronized void set send buffer size int size throws socket exception ssl sock set send buffer size size setsendbuffersize socketexception sslsock setsendbuffersize public void set so linger boolean on int linger throws socket exception ssl sock set so linger on linger setsolinger socketexception sslsock setsolinger public synchronized void set so timeout int timeout throws socket exception ssl sock set so timeout timeout setsotimeout socketexception sslsock setsotimeout public void set tcp no delay boolean on throws socket exception ssl sock set tcp no delay on settcpnodelay socketexception sslsock settcpnodelay public void set traffic class int tc throws socket exception ssl sock set traffic class tc settrafficclass socketexception sslsock settrafficclass public void shutdown input throws io exception ssl sock shutdown input shutdowninput ioexception sslsock shutdowninput public void shutdown output throws io exception ssl sock shutdown output shutdownoutput ioexception sslsock shutdownoutput public string to string return ssl sock to string tostring sslsock tostring public map property string name map value super name log info map value this value normalize map value log info normalized map this value mapproperty normalizemap public map property super mapproperty public boolean equals object o if o instanceof map property if value null return value equals j meter property o get object value return false mapproperty jmeterproperty getobjectvalue public void set object value object v if v instanceof map set map map v setobjectvalue setmap public void add property j meter property prop add property prop get name prop addproperty jmeterproperty addproperty getname public j meter property get string key return j meter property value get key jmeterproperty jmeterproperty figures out what kind of properties this collection is holding and returns the class type see abstract property get property type protected class get property type if value size 0 return value iterator next get class return null property class abstractproperty getpropertytype getpropertytype valueiterator getclass nullproperty see j meter property get string value public string get string value return value to string jmeterproperty getstringvalue getstringvalue tostring see j meter property get object value public object get object value return value jmeterproperty getobjectvalue getobjectvalue public object clone map property prop map property super clone prop value clone map return prop mapproperty mapproperty clonemap private map clone map try map new col map value get class new instance property iterator iter value iterator while iter has next j meter property item iter next new col put item get name item clone return new col catch exception e log error couldn t clone map e return value clonemap newcol getclass newinstance propertyiterator valueiterator hasnext jmeterproperty newcol getname newcol public property iterator value iterator return get iterator value values propertyiterator valueiterator getiterator public void add property string name j meter property prop if value contains key name value put name prop addproperty jmeterproperty containskey public void set map map new map value normalize map new map setmap newmap normalizemap newmap see j meter property recover running version test element public void recover running version test element owner if saved value null value saved value recover running version of sub elements owner jmeterproperty recoverrunningversion testelement recoverrunningversion testelement savedvalue savedvalue recoverrunningversionofsubelements public void clear value clear see multi property iterator public property iterator iterator return value iterator multiproperty propertyiterator valueiterator public void set running version boolean running super set running version running if running saved value value else saved value null setrunningversion setrunningversion savedvalue savedvalue create a new j meter file filter which allows the specified extensions if the array of extensions contains no elements any file will be allowed this constructor will also return all directories param extensions non null array of allowed file extensions public j meter file filter string extensions this extensions true jmeter jmeterfilefilter create a new j meter file filter which allows the specified extensions if the array of extensions contains no elements any file will be allowed param extensions non null array of allowed file extensions param allow should directories be returned public j meter file filter string extensions boolean allow exts extensions allow dirs allow jmeter jmeterfilefilter allowdirs determine if the specified file is allowed by this filter the file will be allowed if it is a directory or if the end of the filename matches one of the extensions allowed by this filter the filename is converted to lower case before making the comparison param f the file being tested return true if the file should be allowed false otherwise public boolean accept file f return allow dirs f is directory accept f get name to lower case todo why lower case ok to use the default locale allowdirs isdirectory getname tolowercase determine if the specified filename is allowed by this filter the file will be allowed if the end of the filename matches one of the extensions allowed by this filter the comparison is case sensitive if no extensions were provided for this filter the file will always be allowed param filename the filename to test return true if the file should be allowed false otherwise public boolean accept string filename if exts length 0 return true for int i 0 i exts length i if filename ends with exts i return true return false endswith get a description for this filter return a description for this filter public string get description return j meter arrays as list exts to string getdescription jmeter aslist tostring public default report summary super defaultreportsummary add a page summary to the report public void add page summary page summary summary this pages add summary pagesummary addpagesummary pagesummary current implementation simply iterates over the page summaries and adds the times public long get elapsed time long elpased time 0 iterator itr this pages iterator while itr has next elpased time page summary itr next get elapsed time return elpased time getelapsedtime elpasedtime hasnext elpasedtime pagesummary getelapsedtime elpasedtime the current implementation calls array list to array object public page summary get pages summaries page summary ps new page summary this pages size return page summary this pages to array ps arraylist toarray pagesummary getpagessummaries pagesummary pagesummary pagesummary toarray remove a page summary public void remove page summary page summary summary this pages remove summary pagesummary removepagesummary pagesummary private object values public split function splitfunction public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception j meter variables vars get variables string string to split compound variable values 0 execute string var name prefix compound variable values 1 execute trim string split string if values length 2 split string provided split string compound variable values 2 execute if log is debug enabled log debug split string to split using split string into var name prefix string parts j orphan utils split string to split split string non nls 1 vars put var name prefix string to split vars put var name prefix n parts length non nls 1 non nls 2 for int i 1 i parts length i if log is debug enabled log debug parts i 1 vars put var name prefix i parts i 1 non nls 1 vars remove var name prefix parts length 1 return string to split sampleresult previousresult currentsampler invalidvariableexception jmetervariables getvariables stringtosplit compoundvariable varnameprefix compoundvariable splitstring splitstring compoundvariable isdebugenabled stringtosplit splitstring varnameprefix jorphanutils stringtosplit splitstring varnameprefix stringtosplit varnameprefix _n isdebugenabled varnameprefix _ varnameprefix _ stringtosplit public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters min parameter count max parameter count values parameters to array setparameters invalidvariableexception checkparametercount min_parameter_count max_parameter_count toarray public string get reference key return key getreferencekey public list get argument desc return desc getargumentdesc public class abstract test element bean info implements bean info public bean info get additional bean info return new bean info 0 abstracttestelementbeaninfo beaninfo beaninfo getadditionalbeaninfo beaninfo see java beans bean info get bean descriptor public bean descriptor get bean descriptor return null beaninfo getbeandescriptor beandescriptor getbeandescriptor see java beans bean info get default event index public int get default event index return 0 beaninfo getdefaulteventindex getdefaulteventindex see java beans bean info get default property index public int get default property index return 0 beaninfo getdefaultpropertyindex getdefaultpropertyindex see java beans bean info get event set descriptors public event set descriptor get event set descriptors return new event set descriptor 0 beaninfo geteventsetdescriptors eventsetdescriptor geteventsetdescriptors eventsetdescriptor see java beans bean info get icon int public image get icon int icon kind return null beaninfo geticon geticon iconkind see java beans bean info get method descriptors public method descriptor get method descriptors return new method descriptor 0 beaninfo getmethoddescriptors methoddescriptor getmethoddescriptors methoddescriptor see java beans bean info get property descriptors public property descriptor get property descriptors return new property descriptor 0 beaninfo getpropertydescriptors propertydescriptor getpropertydescriptors propertydescriptor private static final long serial versionuid 233l public sorted hash tree super new tree map equivalent to new tree map comparator null serialversionuid sortedhashtree treemap treemap non null comparators don t appear to be used at present public sorted hash tree comparator comper super new tree map comper sortedhashtree treemap public sorted hash tree object key this data put key new sorted hash tree sortedhashtree sortedhashtree public sorted hash tree object key comparator comper this comper data put key new sorted hash tree comper sortedhashtree sortedhashtree public sorted hash tree collection keys this iterator it keys iterator while it has next data put it next new sorted hash tree sortedhashtree hasnext sortedhashtree public sorted hash tree collection keys comparator comper this comper iterator it keys iterator while it has next data put it next new sorted hash tree comper sortedhashtree hasnext sortedhashtree public sorted hash tree object keys this for int x 0 x keys length x data put keys x new sorted hash tree sortedhashtree sortedhashtree public sorted hash tree object keys comparator comper this comper for int x 0 x keys length x data put keys x new sorted hash tree comper sortedhashtree sortedhashtree protected hash tree create new tree comparator comparator tree map data comparator return new sorted hash tree comparator hashtree createnewtree treemap sortedhashtree protected hash tree create new tree object key comparator comparator tree map data comparator return new sorted hash tree key comparator hashtree createnewtree treemap sortedhashtree protected hash tree create new tree collection values comparator comparator tree map data comparator return new sorted hash tree values comparator hashtree createnewtree treemap sortedhashtree private object values public set property setproperty public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception string property name compound variable values 0 execute string property value compound variable values 1 execute boolean return value false should we return original value if values length 2 return value compound variable values 2 execute equals ignore case true non nls 1 if return value only obtain and cast the return if needed return string j meter utils set property property name property value else j meter utils set property property name property value return sampleresult previousresult currentsampler invalidvariableexception propertyname compoundvariable propertyvalue compoundvariable returnvalue returnvalue compoundvariable equalsignorecase returnvalue jmeterutils setproperty propertyname propertyvalue jmeterutils setproperty propertyname propertyvalue public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters min parameter count max parameter count values parameters to array setparameters invalidvariableexception checkparametercount min_parameter_count max_parameter_count toarray public string get reference key return key getreferencekey public list get argument desc return desc getargumentdesc private static final logger log logging manager get logger for class protected j tidyhtml parser super loggingmanager getloggerforclass jtidyhtmlparser protected boolean is reusable return true isreusable public iterator get embedded resourceur ls byte html url base url url collection urls throws html parse exception document dom null try dom document getdom html catch sax exception se throw new html parse exception se now parse the dom tree scan nodes dom urls base url return urls iterator getembeddedresourceurls baseurl urlcollection htmlparseexception saxexception htmlparseexception scannodes baseurl scan nodes recursively looking for embedded resources param node initial node param urls container for ur ls param base url used to create absolute ur ls return new base url private url scan nodes node node url collection urls url base url throws html parse exception if node null return base url string name node get node name int type node get node type switch type case node document node scan nodes document node get document element urls base url break case node element node named node map attrs node get attributes if name equals ignore case tag base string tmp get value attrs att href if tmp null try base url conversion utils make relativeurl base url tmp catch malformedurl exception e throw new html parse exception e break if name equals ignore case tag image name equals ignore case tag embed urls addurl get value attrs att src base url break if name equals ignore case tag applet urls addurl get value attrs code base url break if name equals ignore case tag input string src get value attrs att src string typ get value attrs att type if src null typ equals ignore case att is image urls addurl src base url break if name equals ignore case tag link get value attrs att rel equals ignore case stylesheet urls addurl get value attrs att href base url break if name equals ignore case tag script urls addurl get value attrs att src base url break if name equals ignore case tag frame urls addurl get value attrs att src base url break string back get value attrs att background if back null urls addurl back base url if name equals ignore case tag bgsound urls addurl get value attrs att src base url break string style get value attrs att style if style null html parsing utils extract styleur ls base url urls style node list children node get child nodes if children null int len children get length for int i 0 i len i base url scan nodes children item i urls base url break case node text node break return base url urls baseurl urls scannodes urlcollection baseurl htmlparseexception baseurl getnodename getnodetype document_node scannodes getdocumentelement baseurl element_node namednodemap getattributes equalsignorecase tag_base getvalue att_href baseurl conversionutils makerelativeurl baseurl malformedurlexception htmlparseexception equalsignorecase tag_image equalsignorecase tag_embed getvalue att_src baseurl equalsignorecase tag_applet getvalue baseurl equalsignorecase tag_input getvalue att_src getvalue att_type equalsignorecase att_is_image baseurl equalsignorecase tag_link getvalue att_rel equalsignorecase getvalue att_href baseurl equalsignorecase tag_script getvalue att_src baseurl equalsignorecase tag_frame getvalue att_src baseurl getvalue att_background baseurl equalsignorecase tag_bgsound getvalue att_src baseurl getvalue att_style htmlparsingutils extractstyleurls baseurl nodelist getchildnodes getlength baseurl scannodes baseurl text_node baseurl private string get value named node map attrs string attname string v null node n attrs get named item attname if n null v n get node value return v getvalue namednodemap getnameditem getnodevalue returns code tidy code as html parser return a code tidy code html parser private static tidy get tidy parser log debug start get parser tidy tidy new tidy tidy set char encoding org w3c tidy configuration utf8 tidy set quiet true tidy set show warnings false if log is debug enabled log debug get parser tidy parser created tidy log debug end get parser return tidy gettidyparser getparser setcharencoding setquiet setshowwarnings isdebugenabled getparser getparser returns a node representing a whole xml given an xml document param text an xml document as a byte array return a node representing a whole xml throws sax exception indicates an error parsing the xml document private static node getdom byte text throws sax exception log debug start getdom node node get tidy parser parsedom new byte array input stream text null if log is debug enabled log debug node node log debug end getdom return node saxexception saxexception gettidyparser bytearrayinputstream isdebugenabled public final class key strokes prevent instantiation private key strokes keystrokes keystrokes check if an event matches the key stroke definition param e event param k keystroke return true if event matches the keystroke definition public static boolean matches key event e key stroke k final int modifiers ex e get modifiers ex e get modifiers hack to get full modifier value return e get key code k get key code modifiers ex k get modifiers keystroke keyevent keystroke modifiersex getmodifiersex getmodifiers getkeycode getkeycode modifiersex getmodifiers one builder for all requests in a thread private static final thread local my builder new thread local protected object initial value return new sax builder threadlocal mybuilder threadlocal initialvalue saxbuilder returns the result of the assertion here it checks wether the sample took to long to be considered successful if so an assertion result containing a failure message will be returned otherwise the returned assertion result will reflect the success of the sample public assertion result get result sample result response no error as default assertion result result new assertion result get name byte response data response get response data if response data length 0 return result set result for null result set failure false the result data string result data new string get result body response data sax builder builder sax builder my builder get try builder build new string reader result data catch jdom exception e log debug cannot parse result content e may well happen result set failure true result set failure message e get message catch io exception e log error cannot read result content e should never happen result set error true result set failure message e get message return result assertionresult failuremessage assertionresult assertionresult getresult sampleresult assertionresult assertionresult getname responsedata getresponsedata responsedata setresultfornull setfailure resultdata getresultbody responsedata saxbuilder saxbuilder mybuilder stringreader resultdata jdomexception setfailure setfailuremessage getmessage ioexception seterror setfailuremessage getmessage return the body of the http return private byte get result body byte result data for int i 0 i result data length 1 i if result data i new line result data i 1 new line return get byte array slice result data i 2 result data length 1 return result data getresultbody resultdata resultdata resultdata new_line resultdata new_line getbytearrayslice resultdata resultdata resultdata return a slice of a byte array private byte get byte array slice byte array int begin int end byte slice new byte end begin 1 int count 0 for int i begin i end i slice count array i count return slice getbytearrayslice returns the converter version used to check for possible incompatibilities public static string get version return revision 674365 non nls 1 getversion see com thoughtworks xstream converters converter can convert java lang class public boolean can convert class arg0 return string property class equals arg0 canconvert canconvert stringproperty public void marshal object obj hierarchical stream writer writer marshalling context arg2 string property prop string property obj writer add attribute att name conversion help encode prop get name writer set value conversion help encode prop get string value hierarchicalstreamwriter marshallingcontext stringproperty stringproperty addattribute att_name conversionhelp getname setvalue conversionhelp getstringvalue public object unmarshal hierarchical stream reader reader unmarshalling context arg1 string property prop new string property conversion help decode reader get attribute att name conversion help decode reader get value return prop hierarchicalstreamreader unmarshallingcontext stringproperty stringproperty conversionhelp getattribute att_name conversionhelp getvalue private static final string init file beanshell postprocessor init non nls 1 protected string get init file property return init file init_file getinitfileproperty init_file public void process j meter context jmctx j meter context service get context sample result prev jmctx get previous result final bean shell interpreter bsh interpreter get bean shell interpreter if prev null bsh interpreter null log error bean shell not found return j meter variables vars jmctx get variables try add variables for access to context and variables bsh interpreter set ctx jmctx non nls 1 bsh interpreter set vars vars non nls 1 bsh interpreter set prev prev non nls 1 bsh interpreter set data prev get response data non nls 1 process file or script bsh interpreter catch j meter exception e log warn problem in bean shell script e jmetercontext jmetercontextservice getcontext sampleresult getpreviousresult beanshellinterpreter bshinterpreter getbeanshellinterpreter bshinterpreter beanshell jmetervariables getvariables bshinterpreter bshinterpreter bshinterpreter bshinterpreter getresponsedata processfileorscript bshinterpreter jmeterexception beanshell create a new standalone simple config gui public simple config gui this true simpleconfiggui simpleconfiggui create a new simple config gui as either a standalone or an embedded component param display name indicates whether or not this component should display its name if true this is a standalone component if false this component is intended to be used as a subpanel for another component public simple config gui boolean display name this display name display name init simpleconfiggui displayname simpleconfiggui displayname displayname displayname public string get label resource return simple config element non nls 1 getlabelresource simple_config_element a newly created component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui p this implementation retrieves all key value pairs from the test element object and sets these values in the gui param el the test element to configure public void configure test element el super configure el table model clear data property iterator iter el property iterator while iter has next j meter property prop iter next table model add row new object prop get name prop get string value check delete status testelement testelement testelement tablemodel cleardata propertyiterator propertyiterator hasnext jmeterproperty tablemodel addrow getname getstringvalue checkdeletestatus implements j metergui component create test element public test element create test element test element el new config test element modify test element el return el jmeterguicomponent createtestelement testelement createtestelement testelement configtestelement modifytestelement get all of the values from the gui component and set them in the test element param el the test element to modify public void modify test element test element el if table is editing table get cell editor stop cell editing data model table model get data model reset while model next el set property new string property string model get column value column names 0 string model get column value column names 1 super configure test element el testelement testelement modifytestelement testelement isediting getcelleditor stopcellediting tablemodel getdata setproperty stringproperty getcolumnvalue column_names_0 getcolumnvalue column_names_1 configuretestelement initialize the components and layout of this component private void init set layout new border layout 0 10 if display name set border make border add make title panel border layout north add create table panel border layout center force the table to be at least 70 pixels high add box create vertical strut 70 border layout west add create button panel border layout south setlayout borderlayout displayname setborder makeborder maketitlepanel borderlayout createtablepanel borderlayout createverticalstrut borderlayout createbuttonpanel borderlayout invoked when an action occurs this implementation supports the add and delete buttons param e the event that has occurred public void action performed action event e string action e get action command if action equals delete delete argument else if action equals add add argument actionperformed actionevent getactioncommand deleteargument addargument create a gui panel containing the table of configuration parameters return a gui panel containing the parameter table private component create table panel table model new power table model new string column names 0 column names 1 new class string class string class table new j table table model table get table header set default renderer new header as property renderer table set selection mode list selection model single selection return make scroll pane table createtablepanel tablemodel powertablemodel column_names_0 column_names_1 jtable tablemodel gettableheader setdefaultrenderer headeraspropertyrenderer setselectionmode listselectionmodel single_selection makescrollpane create a panel containing the add and delete buttons return a gui panel containing the buttons private j panel create button panel add new j button j meter utils get res string add non nls 1 add set action command add add add action listener this add set enabled true delete new j button j meter utils get res string delete non nls 1 delete set action command delete delete add action listener this check delete status j panel button panel new j panel button panel add add button panel add delete return button panel jpanel createbuttonpanel jbutton jmeterutils getresstring setactioncommand addactionlistener setenabled jbutton jmeterutils getresstring setactioncommand addactionlistener checkdeletestatus jpanel buttonpanel jpanel buttonpanel buttonpanel buttonpanel enable or disable the delete button depending on whether or not there is a row to be deleted protected void check delete status disable delete if there are no rows in the table to delete if table model get row count 0 delete set enabled false else delete set enabled true checkdeletestatus tablemodel getrowcount setenabled setenabled add a new argument row to the table protected void add argument if a table cell is being edited we should accept the current value and stop the editing before adding a new row stop table editing table model add new row table model fire table data changed enable delete which may already be enabled but it won t hurt delete set enabled true highlight select the appropriate row int row to select table model get row count 1 table set row selection interval row to select row to select addargument stoptableediting tablemodel addnewrow tablemodel firetabledatachanged setenabled rowtoselect tablemodel getrowcount setrowselectioninterval rowtoselect rowtoselect stop any editing that is currently being done on the table this will save any changes that have already been made protected void stop table editing if table is editing table cell editor cell editor table get cell editor table get editing row table get editing column cell editor stop cell editing stoptableediting isediting tablecelleditor celleditor getcelleditor geteditingrow geteditingcolumn celleditor stopcellediting remove the currently selected argument from the table protected void delete argument if a table cell is being edited we must cancel the editing before deleting the row if table is editing table cell editor cell editor table get cell editor table get editing row table get editing column cell editor cancel cell editing int row selected table get selected row if row selected 0 remove property table model get value at table get selected row 0 to string table model remove row row selected table model fire table data changed disable delete if there are no rows in the table to delete if table model get row count 0 delete set enabled false else table still contains one or more rows so highlight select the appropriate one int row to select row selected if row selected table model get row count row to select row selected 1 table set row selection interval row to select row to select deleteargument isediting tablecelleditor celleditor getcelleditor geteditingrow geteditingcolumn celleditor cancelcellediting rowselected getselectedrow rowselected removeproperty tablemodel getvalueat getselectedrow tostring tablemodel removerow rowselected tablemodel firetabledatachanged tablemodel getrowcount setenabled rowtoselect rowselected rowselected tablemodel getrowcount rowtoselect rowselected setrowselectioninterval rowtoselect rowtoselect public void add node object node hash tree sub tree iterator iter sub tree list iterator while iter has next object item iter next if item instanceof thread group log info num threads thread group item get num threads if item instanceof remoteable if item instanceof thread listener log error cannot handle thread listener remotable item item get class get name continue try remote sample listener rtl new remote sample listener impl item if item instanceof test listener item instanceof sample listener remote listener wrapper wrap new remote listener wrapper rtl sub tree replace item wrap else if item instanceof test listener remote test listener wrapper wrap new remote test listener wrapper rtl sub tree replace item wrap else if item instanceof sample listener remote sample listener wrapper wrap new remote sample listener wrapper rtl sub tree replace item wrap else log warn could not replace remotable item item get class get name catch remote exception e log error e non nls 1 addnode hashtree subtree subtree hasnext threadgroup threadgroup getnumthreads threadlistener threadlistener getclass getname remotesamplelistener remotesamplelistenerimpl testlistener samplelistener remotelistenerwrapper remotelistenerwrapper subtree testlistener remotetestlistenerwrapper remotetestlistenerwrapper subtree samplelistener remotesamplelistenerwrapper remotesamplelistenerwrapper subtree getclass getname remoteexception see hash tree traverser subtract node public void subtract node hashtreetraverser subtractnode subtractnode see hash tree traverser process path public void process path hashtreetraverser processpath processpath private constructor to prevent instantiation private string utilities stringutilities replace all patterns in a string see string replace all string string jdk1 4 only param input string to be transformed param pattern pattern to replace param sub replacement return the updated string public static string substitute final string input final string pattern final string sub string buffer ret new string buffer input length int start 0 int index 1 final int length pattern length while index input index of pattern start start ret append input substring start index ret append sub start index length ret append input substring start return ret to string replaceall stringbuffer stringbuffer indexof tostring when a user right clicks on the component in the test tree or selects the edit menu when the component is selected the component will be asked to return a j popup menu that provides all the options available to the user from this component p this implementation returns menu items appropriate for most assertion components return a j popup menu appropriate for the component public j popup menu create popup menu return menu factory get default assertion menu jpopupmenu jpopupmenu jpopupmenu createpopupmenu menufactory getdefaultassertionmenu this is the list of menu categories this gui component will be available under this implementation returns link org apache jmeter gui util menu factory assertions which is appropriate for most assertion components return a collection of strings where each element is one of the constants defined in menu factory public collection get menu categories return arrays as list new string menu factory assertions menufactory menufactory getmenucategories aslist menufactory create the scope settings panel return the scope settings panel protected j panel create scope panel assertion scope panel new assertion scope panel return assertion scope panel jpanel createscopepanel assertionscopepanel assertionscopepanel assertionscopepanel public void clear gui super clear gui if assertion scope panel null assertion scope panel clear gui cleargui cleargui assertionscopepanel assertionscopepanel cleargui save the scope settings in the test element param assertion protected void save scope settings abstract scoped assertion assertion if assertion scope panel is scope parent assertion set scope parent else if assertion scope panel is scope children assertion set scope children else assertion set scope all savescopesettings abstractscopedassertion assertionscopepanel isscopeparent setscopeparent assertionscopepanel isscopechildren setscopechildren setscopeall show the scope settings from the test element param assertion protected void show scope settings abstract scoped assertion assertion string scope assertion fetch scope if assertion is scope parent scope assertion scope panel set scope parent else if assertion is scope children scope assertion scope panel set scope children else assertion scope panel set scope all showscopesettings abstractscopedassertion fetchscope isscopeparent assertionscopepanel setscopeparent isscopechildren assertionscopepanel setscopechildren assertionscopepanel setscopeall private static final string default separator non nls 1 public foreach controller default_separator _ foreachcontroller public void set input val string input value set property new string property inputval input value setinputval inputvalue setproperty stringproperty inputvalue private string get input val get property inputval recover running version null return get input val string getinputval getproperty recoverrunningversion getinputvalstring public string get input val string return get property as string inputval getinputvalstring getpropertyasstring public void set return val string input value set property new string property returnval input value setreturnval inputvalue setproperty stringproperty inputvalue private string get return val get property returnval recover running version null return get return val string getreturnval getproperty recoverrunningversion getreturnvalstring public string get return val string return get property as string returnval getreturnvalstring getpropertyasstring private string get separator return get use separator default separator non nls 1 getseparator getuseseparator default_separator public void set use separator boolean b set property new boolean property use separator b setuseseparator setproperty booleanproperty use_separator public boolean get use separator return get property as boolean use separator true getuseseparator getpropertyasboolean use_separator public boolean is done j meter context context get thread context string input variable get input val get separator loop count 1 final j meter variables variables context get variables final object current variable variables get object input variable if current variable null variables put object get return val current variable if log is debug enabled log debug for each resultstring is done variables get get return val return false return super is done isdone jmetercontext getthreadcontext inputvariable getinputval getseparator loopcount jmetervariables getvariables currentvariable getobject inputvariable currentvariable putobject getreturnval currentvariable isdebugenabled foreach isdone getreturnval isdone private boolean end of arguments j meter context context get thread context string input variable get input val get separator loop count 1 if context get variables get object input variable null log debug for each resultstring eof args false return false log debug for each resultstring eof args true return true endofarguments jmetercontext getthreadcontext inputvariable getinputval getseparator loopcount getvariables getobject inputvariable foreach eofargs foreach eofargs prevent entry if nothing to do public sampler next if empty list re initialize reset loop count return null return super next emptylist reinitialize resetloopcount check if there are any matching entries return whether any entries in the list private boolean empty list j meter context context get thread context string input variable get input val get separator 1 non nls 1 if context get variables get object input variable null return false if log is debug enabled log debug no entries found null first entry input variable return true emptylist jmetercontext getthreadcontext inputvariable getinputval getseparator getvariables getobject inputvariable isdebugenabled inputvariable protected sampler next is null throws next is null exception re initialize if end of arguments set done true reset loop count return null return next nextisnull nextisnullexception reinitialize endofarguments setdone resetloopcount protected void increment loop count loop count incrementloopcount loopcount protected void reset loop count loop count 0 resetloopcount loopcount see org apache jmeter control generic controller get iter count protected int get iter count return loop count 1 genericcontroller getitercount getitercount loopcount protected void re initialize set first true reset current increment loop count recover running version reinitialize setfirst resetcurrent incrementloopcount recoverrunningversion public on message subscriber super onmessagesubscriber constructor takes the necessary jndi related parameters to create a connection and begin receiving messages param use props param jndi param url param connfactory param topic param use auth param user param pwd public on message subscriber boolean use props string jndi string url string connfactory string topic boolean use auth string user string pwd context ctx initjndi use props jndi url use auth user pwd if ctx null init connection ctx connfactory topic else log error could not initialize jndi initial context factory useprops useauth onmessagesubscriber useprops useauth useprops useauth initconnection initialize the jndi intial context param use props param jndi param url param use auth param user param pwd return the context or null public context initjndi boolean use props string jndi string url boolean use auth string user string pwd if use props try return new initial context catch naming exception e log error e get message return null else return initial context factory lookup context jndi url use auth user pwd useprops useauth useprops useauth useprops initialcontext namingexception getmessage initialcontextfactory lookupcontext useauth initialize the connection session and subscriber param ctx param connfactory param topic public void init connection context ctx string connfactory string topic try this conn connection factory get topic connection this topic initial context factory lookup topic ctx topic this session this conn create topic session false topic session auto acknowledge this subscriber this session create subscriber this topic log info created the topic connection successfully catch jms exception e log error connection error e get message initconnection connectionfactory gettopicconnection initialcontextfactory lookuptopic createtopicsession topicsession auto_acknowledge createsubscriber jmsexception getmessage resume will call connection start to begin receiving inbound messages public void resume try this conn start catch jms exception e log error failed to start recieving jmsexception close will close all the objects and set them to null public void close try log info subscriber closed this subscriber close this session close this conn close this subscriber null this session null this conn null catch jms exception e log error e get message catch throwable e log error e get message jmsexception getmessage getmessage the sample uses this method to set itself as the listener that means the sampler need to implement message listener interface param listener public void set message listener message listener listener try this subscriber set message listener listener catch jms exception e log error e get message messagelistener setmessagelistener messagelistener setmessagelistener jmsexception getmessage public class invalid variable exception extends exception public invalid variable exception invalidvariableexception invalidvariableexception public invalid variable exception string msg super msg invalidvariableexception final static string switch value switch controller value non nls 1 public switch controller super switch_value switchcontroller switchcontroller public sampler next if is first set the selection once per iteration current get selection as int return super next isfirst getselectionasint see org apache jmeter control generic controller increment current protected void increment current current integer max value genericcontroller incrementcurrent incrementcurrent max_value public void set selection string input value set property new string property switch value input value setselection inputvalue setproperty stringproperty switch_value inputvalue private int get selection as int int ret get property switch value recover running version null string sel get selection try ret integer parse int sel if ret 0 ret get sub controllers size ret 0 catch number format exception e if sel length 0 ret 0 else ret scan controller names sel return ret getselectionasint getproperty switch_value recoverrunningversion getselection parseint getsubcontrollers numberformatexception scancontrollernames private int scan controller names string sel iterator iter get sub controllers iterator int i 0 int default pos integer max value while iter has next string name test element el test element iter next name el get name if name equals sel return i if name equals ignore case default non nls 1 default pos i i return default pos scancontrollernames getsubcontrollers default_pos max_value hasnext testelement testelement getname equalsignorecase default_pos default_pos public string get selection return get property as string switch value getselection getpropertyasstring switch_value private void init synchronized this global counter 0 per thread int new thread local protected synchronized object initial value return new integer 0 globalcounter perthreadint threadlocal initialvalue per thread int new thread local protected synchronized object initial value return new integer 0 perthreadint threadlocal initialvalue public iteration counter init iterationcounter public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception new integer 1 global counter j meter variables vars get variables boolean per thread boolean value of compound variable variables 0 execute boolean value string var name non nls 1 if variables length 2 ensure variable has been provided var name compound variable variables 1 execute trim string counter string non nls 1 if per thread int thread counter thread counter integer per thread int get int value 1 per thread int set new integer thread counter counter string string value of thread counter else counter string string value of global counter vars will be null on test plan if vars null var name length 0 vars put var name counter string return counter string sampleresult previousresult currentsampler invalidvariableexception globalcounter jmetervariables getvariables perthread valueof compoundvariable booleanvalue varname varname compoundvariable counterstring perthread threadcounter threadcounter perthreadint intvalue perthreadint threadcounter counterstring valueof threadcounter counterstring valueof globalcounter varname varname counterstring counterstring see org apache jmeter functions function set parameters collection public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters 1 2 variables parameters to array setparameters setparameters invalidvariableexception checkparametercount toarray see org apache jmeter functions function get reference key public string get reference key return key getreferencekey getreferencekey see org apache jmeter functions function get argument desc public list get argument desc return desc getargumentdesc getargumentdesc set this true to suppress some items for use in http request defaults public url config gui not config only true init urlconfiggui notconfigonly public url config gui boolean value not config only value init urlconfiggui notconfigonly public void clear domain set text non nls 1 if not config only follow redirects set selected false auto redirects set selected true method set text http sampler base default method use keep alive set selected true use multipart for post set selected false path set text non nls 1 port set text non nls 1 connect time out set text non nls 1 response time out set text non nls 1 protocol set text non nls 1 content encoding set text non nls 1 args panel clear settext notconfigonly followredirects setselected autoredirects setselected settext httpsamplerbase default_method usekeepalive setselected usemultipartforpost setselected settext settext connecttimeout settext responsetimeout settext settext contentencoding settext argspanel public test element create test element config test element element new config test element element set name this get name element set property test element gui class this get class get name element set property test element test class element get class get name modify test element element return element testelement createtestelement configtestelement configtestelement setname getname setproperty testelement gui_class getclass getname setproperty testelement test_class getclass getname modifytestelement save the gui values in the sampler param element public void modify test element test element element arguments args arguments args panel create test element http argument convert arguments tohttp args element set property new test element property http sampler base arguments args element set property http sampler base domain domain get text element set property http sampler base port port get text element set property http sampler base connect timeout connect time out get text element set property http sampler base response timeout response time out get text element set property http sampler base protocol protocol get text element set property http sampler base content encoding content encoding get text element set property http sampler base path path get text if not config only element set property http sampler base method method get text element set property new boolean property http sampler base follow redirects follow redirects is selected element set property new boolean property http sampler base auto redirects auto redirects is selected element set property new boolean property http sampler base use keepalive use keep alive is selected element set property new boolean property http sampler base do multipart post use multipart for post is selected modifytestelement testelement argspanel createtestelement httpargument convertargumentstohttp setproperty testelementproperty httpsamplerbase setproperty httpsamplerbase gettext setproperty httpsamplerbase gettext setproperty httpsamplerbase connect_timeout connecttimeout gettext setproperty httpsamplerbase response_timeout responsetimeout gettext setproperty httpsamplerbase gettext setproperty httpsamplerbase content_encoding contentencoding gettext setproperty httpsamplerbase gettext notconfigonly setproperty httpsamplerbase gettext setproperty booleanproperty httpsamplerbase follow_redirects followredirects isselected setproperty booleanproperty httpsamplerbase auto_redirects autoredirects isselected setproperty booleanproperty httpsamplerbase use_keepalive usekeepalive isselected setproperty booleanproperty httpsamplerbase do_multipart_post usemultipartforpost isselected set the text etc in the ui param el contains the data to be displayed public void configure test element el set name el get name args panel configure test element el get property http sampler base arguments get object value domain set text el get property as string http sampler base domain string port string el get property as string http sampler base port only display the port number if it is meaningfully specified if port string equals http sampler base unspecified port as string port set text non nls 1 else port set text port string connect time out set text el get property as string http sampler base connect timeout response time out set text el get property as string http sampler base response timeout protocol set text el get property as string http sampler base protocol content encoding set text el get property as string http sampler base content encoding path set text el get property as string http sampler base path if not config only method set text el get property as string http sampler base method follow redirects set selected abstract test element el get property as boolean http sampler base follow redirects auto redirects set selected abstract test element el get property as boolean http sampler base auto redirects use keep alive set selected abstract test element el get property as boolean http sampler base use keepalive use multipart for post set selected abstract test element el get property as boolean http sampler base do multipart post testelement setname getname argspanel testelement getproperty httpsamplerbase getobjectvalue settext getpropertyasstring httpsamplerbase portstring getpropertyasstring httpsamplerbase portstring httpsamplerbase unspecified_port_as_string settext settext portstring connecttimeout settext getpropertyasstring httpsamplerbase connect_timeout responsetimeout settext getpropertyasstring httpsamplerbase response_timeout settext getpropertyasstring httpsamplerbase contentencoding settext getpropertyasstring httpsamplerbase content_encoding settext getpropertyasstring httpsamplerbase notconfigonly settext getpropertyasstring httpsamplerbase followredirects setselected abstracttestelement getpropertyasboolean httpsamplerbase follow_redirects autoredirects setselected abstracttestelement getpropertyasboolean httpsamplerbase auto_redirects usekeepalive setselected abstracttestelement getpropertyasboolean httpsamplerbase use_keepalive usemultipartforpost setselected abstracttestelement getpropertyasboolean httpsamplerbase do_multipart_post private void init called from ctor so must not be overridable this set layout new border layout web request panel j panel web request panel new j panel web request panel set layout new border layout web request panel set border border factory create titled border border factory create etched border j meter utils get res string web request non nls 1 j panel north panel new j panel north panel set layout new box layout north panel box layout y axis north panel add get protocol and method panel north panel add get path panel web request panel add north panel border layout north web request panel add get parameter panel border layout center this add get web server timeout panel border layout north this add web request panel border layout center setlayout borderlayout jpanel webrequestpanel jpanel webrequestpanel setlayout borderlayout webrequestpanel setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring web_request jpanel northpanel jpanel northpanel setlayout boxlayout northpanel boxlayout y_axis northpanel getprotocolandmethodpanel northpanel getpathpanel webrequestpanel northpanel borderlayout webrequestpanel getparameterpanel borderlayout getwebservertimeoutpanel borderlayout webrequestpanel borderlayout create a panel containing the webserver domain port and timeouts connect request return the panel protected final j panel get web server timeout panel web server panel j panel web server panel new horizontal panel web server panel set border border factory create titled border border factory create etched border j meter utils get res string web server non nls 1 final j panel domain panel get domain panel final j panel port panel get port panel web server panel add domain panel border layout center web server panel add port panel border layout east j panel time out new horizontal panel time out set border border factory create titled border border factory create etched border j meter utils get res string web server timeout title non nls 1 final j panel conn panel get connect time out panel final j panel req panel get response time out panel time out add conn panel time out add req panel j panel web server timeout panel new vertical panel web server timeout panel add web server panel border layout center web server timeout panel add time out border layout east return web server timeout panel jpanel getwebservertimeoutpanel jpanel webserverpanel horizontalpanel webserverpanel setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring web_server jpanel domainpanel getdomainpanel jpanel portpanel getportpanel webserverpanel domainpanel borderlayout webserverpanel portpanel borderlayout jpanel timeout horizontalpanel timeout setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring web_server_timeout_title jpanel connpanel getconnecttimeoutpanel jpanel reqpanel getresponsetimeoutpanel timeout connpanel timeout reqpanel jpanel webservertimeoutpanel verticalpanel webservertimeoutpanel webserverpanel borderlayout webservertimeoutpanel timeout borderlayout webservertimeoutpanel private j panel get port panel port new j text field 4 j label label new j label j meter utils get res string web server port non nls 1 label set label for port j panel panel new j panel new border layout 5 0 panel add label border layout west panel add port border layout center return panel jpanel getportpanel jtextfield jlabel jlabel jmeterutils getresstring web_server_port setlabelfor jpanel jpanel borderlayout borderlayout borderlayout private j panel get connect time out panel connect time out new j text field 4 j label label new j label j meter utils get res string web server timeout connect non nls 1 label set label for connect time out j panel panel new j panel new border layout 5 0 panel add label border layout west panel add connect time out border layout center return panel jpanel getconnecttimeoutpanel connecttimeout jtextfield jlabel jlabel jmeterutils getresstring web_server_timeout_connect setlabelfor connecttimeout jpanel jpanel borderlayout borderlayout connecttimeout borderlayout private j panel get response time out panel response time out new j text field 4 j label label new j label j meter utils get res string web server timeout response non nls 1 label set label for response time out j panel panel new j panel new border layout 5 0 panel add label border layout west panel add response time out border layout center return panel jpanel getresponsetimeoutpanel responsetimeout jtextfield jlabel jlabel jmeterutils getresstring web_server_timeout_response setlabelfor responsetimeout jpanel jpanel borderlayout borderlayout responsetimeout borderlayout private j panel get domain panel domain new j text field 20 j label label new j label j meter utils get res string web server domain non nls 1 label set label for domain j panel panel new j panel new border layout 5 0 panel add label border layout west panel add domain border layout center return panel jpanel getdomainpanel jtextfield jlabel jlabel jmeterutils getresstring web_server_domain setlabelfor jpanel jpanel borderlayout borderlayout borderlayout this method defines the panel for the http path follow redirects use keep alive and use multipart for http post elements return j panel the panel for the path follow redirects and use keep alive elements protected component get path panel path new j text field 15 j label label new j label j meter utils get res string path non nls 1 label set label for path if not config only follow redirects new j check box j meter utils get res string follow redirects non nls 1 follow redirects set selected false auto redirects new j check box j meter utils get res string follow redirects auto non nls 1 auto redirects add change listener this auto redirects set selected true default changed in 2 3 use keep alive new j check box j meter utils get res string use keepalive non nls 1 use keep alive set selected true use multipart for post new j check box j meter utils get res string use multipart for http post non nls 1 use multipart for post set selected false j panel path panel new j panel new border layout 5 0 path panel add label border layout west path panel add path border layout center path panel set minimum size path panel get preferred size j panel panel new j panel panel set layout new box layout panel box layout y axis panel add path panel if not config only j panel option panel new j panel new flow layout flow layout left option panel add auto redirects option panel add follow redirects option panel add use keep alive option panel add use multipart for post option panel set minimum size option panel get preferred size panel add option panel return panel keepalive jpanel keepalive getpathpanel jtextfield jlabel jlabel jmeterutils getresstring setlabelfor notconfigonly followredirects jcheckbox jmeterutils getresstring follow_redirects followredirects setselected autoredirects jcheckbox jmeterutils getresstring follow_redirects_auto autoredirects addchangelistener autoredirects setselected usekeepalive jcheckbox jmeterutils getresstring use_keepalive usekeepalive setselected usemultipartforpost jcheckbox jmeterutils getresstring use_multipart_for_http_post usemultipartforpost setselected jpanel pathpanel jpanel borderlayout pathpanel borderlayout pathpanel borderlayout pathpanel setminimumsize pathpanel getpreferredsize jpanel jpanel setlayout boxlayout boxlayout y_axis pathpanel notconfigonly jpanel optionpanel jpanel flowlayout flowlayout optionpanel autoredirects optionpanel followredirects optionpanel usekeepalive optionpanel usemultipartforpost optionpanel setminimumsize optionpanel getpreferredsize optionpanel protected j panel get protocol and method panel protocol protocol new j text field 10 content encoding content encoding new j text field 10 j label protocol label new j label j meter utils get res string protocol non nls 1 protocol label set label for protocol j label content encoding label new j label j meter utils get res string content encoding non nls 1 protocol label set label for content encoding if not config only method new j labeled choice j meter utils get res string method non nls 1 http sampler base get valid methods as array j panel panel new j panel new flow layout flow layout left panel add protocol label panel add protocol panel add box create horizontal strut 5 if not config only panel add method panel set minimum size panel get preferred size panel add box create horizontal strut 5 panel add content encoding label panel add content encoding return panel jpanel getprotocolandmethodpanel jtextfield content_encoding contentencoding jtextfield jlabel protocollabel jlabel jmeterutils getresstring protocollabel setlabelfor jlabel contentencodinglabel jlabel jmeterutils getresstring content_encoding protocollabel setlabelfor contentencoding notconfigonly jlabeledchoice jmeterutils getresstring httpsamplerbase getvalidmethodsasarray jpanel jpanel flowlayout flowlayout protocollabel createhorizontalstrut notconfigonly setminimumsize getpreferredsize createhorizontalstrut contentencodinglabel contentencoding protected j panel get parameter panel args panel new http arguments panel return args panel jpanel getparameterpanel argspanel httpargumentspanel argspanel disable follow redirects if autoredirect is selected public void state changed change event e if e get source auto redirects if auto redirects is selected follow redirects set enabled false else follow redirects set enabled true statechanged changeevent getsource autoredirects autoredirects isselected followredirects setenabled followredirects setenabled public remote listener wrapper remote sample listener l listener l get appropriate sender class governed by the behaviour set in the j meter property sender sample sender factory get instance listener remotelistenerwrapper remotesamplelistener jmeter samplesenderfactory getinstance public remote listener wrapper todo not used make private listener null sender null remotelistenerwrapper public void test started log info test started try listener test started catch throwable ex log warn test started ex teststarted teststarted teststarted public void test ended sender test ended testended testended public void test started string host log info test started on host should this be debug try listener test started host catch throwable ex log error test started host ex teststarted teststarted teststarted public void test ended string host sender test ended host testended testended public void sample occurred sample event e sender sample occurred e sampleoccurred sampleevent sampleoccurred public void sample started sample event e log debug sample started try listener sample started e catch remote exception err log error sample started err samplestarted sampleevent samplestarted remoteexception samplestarted public void sample stopped sample event e log debug sample stopped try listener sample stopped e catch remote exception err log error sample stopped err samplestopped sampleevent samplestopped remoteexception samplestopped see test listener test iteration start loop iteration event public void test iteration start loop iteration event event testlistener testiterationstart loopiterationevent testiterationstart loopiterationevent private final test element source public loop iteration event test element source int iter iteration iter this source source testelement loopiterationevent testelement returns the iteration return int public int get iteration return iteration getiteration returns the source return test element public test element get source return source testelement testelement getsource public abstract class abstract timer gui extends abstractj meter gui component when a user right clicks on the component in the test tree or selects the edit menu when the component is selected the component will be asked to return a j popup menu that provides all the options available to the user from this component p this implementation returns menu items appropriate for most timer components return a j popup menu appropriate for the component public j popup menu create popup menu return menu factory get default timer menu abstracttimergui abstractjmeterguicomponent jpopupmenu jpopupmenu jpopupmenu createpopupmenu menufactory getdefaulttimermenu this is the list of menu categories this gui component will be available under this implementation returns link org apache jmeter gui util menu factory timers which is appropriate for most timer components return a collection of strings where each element is one of the constants defined in menu factory public collection get menu categories return arrays as list new string menu factory timers menufactory menufactory getmenucategories aslist menufactory public parse benchmark super parsebenchmark public static void main string args if args length 3 int parser 0 string file null int loops 1000 if args 0 null if args 0 equals jaxb parser 1 if args 1 null file args 1 if args 2 null loops integer parse int args 2 java io file infile new java io file file java io file input stream fis null java io input stream reader isr null string buffer buf new string buffer try fis new java io file input stream infile isr new java io input stream reader fis java io buffered reader br new java io buffered reader isr string line null while line br read line null buf append line catch exception e e print stack trace long start 0 long end 0 string contents buf to string trim system out println start test loops iterations system out println content system out println contents if parser 0 try jaxb context jxbc new org apache jorphan tomcat manager object factory unmarshaller mar jxbc create unmarshaller start system current time millis for int idx 0 idx loops idx stream source ss new stream source new byte array input stream contents get bytes object ld mar unmarshal ss end system current time millis system out println elapsed time end start catch jaxb exception e else org apache jmeter monitor model object factory of org apache jmeter monitor model object factory get instance start system current time millis for int idx 0 idx loops idx notused org apache jmeter monitor model status st of parse bytes contents get bytes end system current time millis system out println elapsed time end start else system out println missing paramters system out println parser file iterations system out println example jaxb status xml 1000 parseint fileinputstream inputstreamreader stringbuffer stringbuffer fileinputstream inputstreamreader bufferedreader bufferedreader readline printstacktrace tostring jaxbcontext objectfactory createunmarshaller currenttimemillis streamsource streamsource bytearrayinputstream getbytes currenttimemillis jaxbexception objectfactory objectfactory getinstance currenttimemillis parsebytes getbytes currenttimemillis public class sample sender factory checks for the jmeter property mode and returns the required class param listener return the appropriate class standard jmeter functionality hold samples until end of test or batch samples static sample sender get instance remote sample listener listener support original property name boolean hold samples j meter utils get prop default hold samples false extended property name string type j meter utils get prop default mode standard if hold samples type equals ignore case hold hold sample sender h new hold sample sender listener return h else if type equals ignore case batch batch sample sender b new batch sample sender listener return b else if type equals ignore case statistical statistical sample sender s new statistical sample sender listener return s else standard sample sender s new standard sample sender listener return s samplesenderfactory hold_samples samplesender getinstance remotesamplelistener holdsamples jmeterutils getpropdefault hold_samples jmeterutils getpropdefault holdsamples equalsignorecase holdsamplesender holdsamplesender equalsignorecase batchsamplesender batchsamplesender equalsignorecase statisticalsamplesender statisticalsamplesender standardsamplesender standardsamplesender public class j labeled password field extends j labeled text field public j labeled password field super jlabeledpasswordfield jlabeledtextfield jlabeledpasswordfield constructs a new component with the label displaying the passed text param p label the text to in the label public j labeled password field string p label super p label plabel jlabeledpasswordfield plabel plabel protected j text field create text field int size return new j password field size jtextfield createtextfield jpasswordfield see org apache jmeter gui action command do action action event public void do action action event e if help window null help window new j dialog new frame independent frame to allow it to be overlaid by the main frame j meter utils get res string help non nls 1 false help window get content pane set layout new grid layout 1 1 component util center component in window help window 60 help window get content pane remove all help window get content pane add scroller help window show if e get source instanceof string string source string e get source reset page source 0 help doc scroll to reference source 1 else reset page help page help doc scroll to reference gui package get instance get tree listener get current node get doc anchor doaction actionevent doaction actionevent helpwindow helpwindow jdialog jmeterutils getresstring helpwindow getcontentpane setlayout gridlayout componentutil centercomponentinwindow helpwindow helpwindow getcontentpane removeall helpwindow getcontentpane helpwindow getsource getsource resetpage helpdoc scrolltoreference resetpage help_page helpdoc scrolltoreference guipackage getinstance gettreelistener getcurrentnode getdocanchor private void reset page string source if current page equals source try help doc set page source current page source catch io exception err log error err to string j meter utils report error to user problem loading a help page see log for details current page non nls 1 resetpage currentpage helpdoc setpage currentpage ioexception tostring jmeterutils reporterrortouser currentpage see org apache jmeter gui action command get action names public set get action names return commands getactionnames getactionnames extract the encoding charset from the content type e g text html charset utf 8 param content type return the charset encoding or null if none was found or the charset is not supported public static string get encoding from content type string content type string char set null if content type null int char set start pos content type to lower case java util locale english index of charset eq if char set start pos 0 char set content type substring char set start pos charset eq len if char set null remove quotes from charset name char set j orphan utils replace all chars char set char set char set trim if char set length 0 see bug 44784 int semi char set index of if semi 0 return null if semi 1 char set char set substring 0 semi if charset is supported char set return null return char set return null return char set contenttype getencodingfromcontenttype contenttype charset contenttype charsetstartpos contenttype tolowercase indexof charset_eq charsetstartpos charset contenttype charsetstartpos charset_eq_len charset charset jorphanutils replaceallchars charset charset charset charset charset indexof charset charset issupported charset charset charset generate a relative url allowing for extraneous leading segments the java link url url url string constructor does not remove these param baseurl param location relative location possibly with extraneous leading return url with extraneous removed throws malformedurl exception public static url make relativeurl url baseurl string location throws malformedurl exception url initial new url baseurl location skip expensive processing if it cannot apply if location starts with non nls 1 return initial string path initial get path match etc pattern p pattern compile non nls 1 matcher m p matcher path if m looking at string prefix m group 1 get or etc if location starts with prefix return new url baseurl location substring prefix length return initial malformedurlexception makerelativeurl malformedurlexception startswith getpath lookingat startswith create a java sampler public java sampler set arguments new arguments synchronized all samplers all samplers add this javasampler javasampler setarguments allsamplers allsamplers set the arguments parameters for the java sampler client to be executed with param args the new arguments these replace any existing arguments public void set arguments arguments args set property new test element property arguments args javasamplerclient setarguments setproperty testelementproperty get the arguments parameters for the java sampler client to be executed with return the arguments public arguments get arguments return arguments get property arguments get object value javasamplerclient getarguments getproperty getobjectvalue releases java client private void release java client if java client null java client teardown test context java client null context null releasejavaclient javaclient javaclient teardowntest javaclient sets the classname attribute of the java config object param classname the new classname value public void set classname string classname set property classname classname javaconfig setclassname setproperty gets the classname attribute of the java config object return the classname value public string get classname return get property as string classname javaconfig getclassname getpropertyasstring performs a test sample the code sample code method retrieves the reference to the java client and calls its code run test code method see java sampler client run test java sampler context param entry the entry for this sample return test sample result public sample result sample entry entry arguments args get arguments args add argument test element name get name allow sampler access to test element name context new java sampler context args if java client null log debug who ami creating java client create java client java client setup test context sample result result create java client run test context only set the default label if it has not been set if result null result get sample label length 0 result set sample label get name return result runtest javasamplerclient runtest javasamplercontext sampleresult sampleresult getarguments addargument testelement getname javasamplercontext javaclient whoami createjavaclient javaclient setuptest sampleresult createjavaclient runtest getsamplelabel setsamplelabel getname returns reference to code java sampler client code the code create java client code method uses reflection to create an instance of the specified java protocol client if the class can not be found the method returns a reference to code this code object return java sampler client reference private java sampler client create java client if java client null try class java class class for name get classname trim false thread current thread get context class loader java client java sampler client java class new instance context new java sampler context get arguments if log is debug enabled log debug who ami t created t get classname integer to hex string java client hash code catch exception e log error who ami t exception creating get classname e java client new error sampler client return java client javasamplerclient createjavaclient javasamplerclient javasamplerclient createjavaclient javaclient javaclass forname getclassname currentthread getcontextclassloader javaclient javasamplerclient javaclass newinstance javasamplercontext getarguments isdebugenabled whoami tcreated getclassname tohexstring javaclient hashcode whoami texception getclassname javaclient errorsamplerclient javaclient generate a string identifier of this instance for debugging purposes return a string identifier for this sampler instance private string who ami string buffer sb new string buffer sb append thread current thread get name sb append sb append integer to hex string hash code sb append sb append get name return sb to string whoami stringbuffer stringbuffer currentthread getname tohexstring hashcode getname tostring test listener implementation implements test listener test started public void test started log debug who ami ttest started testlistener testlistener teststarted teststarted whoami tteststarted implements test listener test started string public void test started string host log debug who ami ttest started host testlistener teststarted teststarted whoami tteststarted method called at the end of the test this is called only on one instance of java sampler this method will loop through all of the other java samplers which have been registered automatically in the constructor and notify them that the test has ended allowing the java sampler clients to cleanup public void test ended log debug who ami ttest ended synchronized all samplers iterator i all samplers iterator while i has next java sampler sampler java sampler i next sampler release java client i remove javasampler javasamplers javasamplerclients testended whoami ttestended allsamplers allsamplers hasnext javasampler javasampler releasejavaclient implements test listener test ended string public void test ended string host test ended testlistener testended testended testended implements test listener test iteration start loop iteration event public void test iteration start loop iteration event event testlistener testiterationstart loopiterationevent testiterationstart loopiterationevent class error sampler client extends abstract java sampler client return sample result with data on error see java sampler client run test java sampler context public sample result run test java sampler context p context log debug who ami trun test thread yield sample result results new sample result results set successful false results set response data class not found get classname get bytes results set sample label error get classname return results errorsamplerclient abstractjavasamplerclient sampleresult javasamplerclient runtest javasamplercontext sampleresult runtest javasamplercontext p_context whoami truntest sampleresult sampleresult setsuccessful setresponsedata getclassname getbytes setsamplelabel getclassname private string value public test time function string name super name testtimefunction public void set up jmctx j meter context service get context vars new j meter variables jmctx set variables vars jmctx set previous result result params new linked list result new sample result variable new time function setup jmetercontextservice getcontext jmetervariables setvariables setpreviousresult linkedlist sampleresult timefunction public void test default throws exception variable set parameters params long before system current time millis value variable execute result null long now long parse long value long after system current time millis assert true now before now after testdefault setparameters currenttimemillis parselong currenttimemillis asserttrue public void test default1 throws exception params add new compound variable variable set parameters params long before system current time millis value variable execute result null long now long parse long value long after system current time millis assert true now before now after testdefault1 compoundvariable setparameters currenttimemillis parselong currenttimemillis asserttrue public void test default2 throws exception params add new compound variable params add new compound variable variable set parameters params long before system current time millis value variable execute result null long now long parse long value long after system current time millis assert true now before now after testdefault2 compoundvariable compoundvariable setparameters currenttimemillis parselong currenttimemillis asserttrue public void test default none throws exception long before system current time millis value variable execute result null long now long parse long value long after system current time millis assert true now before now after testdefaultnone currenttimemillis parselong currenttimemillis asserttrue public void test too many throws exception params add new compound variable ymd params add new compound variable name params add new compound variable ymd try variable set parameters params fail should have raised invalid variable exception catch invalid variable exception ignored testtoomany compoundvariable compoundvariable compoundvariable setparameters invalidvariableexception invalidvariableexception public void testymd throws exception params add new compound variable ymd params add new compound variable name variable set parameters params value variable execute result null assert equals 8 value length assert equals value vars get name compoundvariable compoundvariable setparameters assertequals assertequals public void testym dnov throws exception params add new compound variable ymd variable set parameters params value variable execute result null assert equals 8 value length assert null vars get name testymdnov compoundvariable setparameters assertequals assertnull public void testhms throws exception params add new compound variable hms variable set parameters params value variable execute result null assert equals 6 value length compoundvariable setparameters assertequals public void testymdhms throws exception params add new compound variable ymdhms variable set parameters params value variable execute result null assert equals 15 value length compoundvariable setparameters assertequals public void testuser1 throws exception params add new compound variable user1 variable set parameters params value variable execute result null assert equals 0 value length compoundvariable setparameters assertequals public void testuser2 throws exception params add new compound variable user2 variable set parameters params value variable execute result null assert equals 0 value length compoundvariable setparameters assertequals public void test fixed throws exception params add new compound variable fixed text variable set parameters params value variable execute result null assert equals fixed text value testfixed compoundvariable setparameters assertequals public void test mixed throws exception params add new compound variable g variable set parameters params locale locale locale get default locale set default locale english value variable execute result null locale set default locale assert equals ad value testmixed compoundvariable setparameters getdefault setdefault setdefault assertequals private j labeled choice x items new j labeled choice public line graph gui super init jlabeledchoice xitems jlabeledchoice linegraphgui public string get label resource return report line graph getlabelresource report_line_graph public j popup menu create popup menu j popup menu pop new j popup menu report menu factory add file menu pop report menu factory add edit menu pop true return pop jpopupmenu createpopupmenu jpopupmenu jpopupmenu reportmenufactory addfilemenu reportmenufactory addeditmenu private void init called from ctor so must not be overridable set layout new border layout 10 10 set border make border set background color white j panel pane new j panel pane set layout new border layout 10 10 pane set background color white pane add this get name panel border layout north vertical panel options new vertical panel color white y axis label set background color white j label x label new j label j meter utils get res string report chart x axis horizontal panel xpanel new horizontal panel color white x label set border new empty border 5 2 5 2 x items set background color white x items set values abstract table xitems xpanel add x label xpanel add x items options add xpanel j label xa label new j label j meter utils get res string report chart x axis label horizontal panel x apanel new horizontal panel color white xa label set border new empty border 5 2 5 2 x axis label set background color white x axis label set values abstract chart x labels x apanel add xa label x apanel add x axis label options add x apanel j label y label new j label j meter utils get res string report chart y axis horizontal panel ypanel new horizontal panel color white y label set border new empty border 5 2 5 2 y items set background color white y items set values abstract table items ypanel add y label ypanel add y items options add ypanel options add y axis label options add caption options add urls add pane border layout north add options border layout center setlayout borderlayout setborder makeborder setbackground jpanel jpanel setlayout borderlayout setbackground getnamepanel borderlayout verticalpanel verticalpanel yaxislabel setbackground jlabel xlabel jlabel jmeterutils getresstring report_chart_x_axis horizontalpanel horizontalpanel xlabel setborder emptyborder xitems setbackground xitems setvalues abstracttable xlabel xitems jlabel xalabel jlabel jmeterutils getresstring report_chart_x_axis_label horizontalpanel xapanel horizontalpanel xalabel setborder emptyborder xaxislabel setbackground xaxislabel setvalues abstractchart x_labels xapanel xalabel xapanel xaxislabel xapanel jlabel ylabel jlabel jmeterutils getresstring report_chart_y_axis horizontalpanel horizontalpanel ylabel setborder emptyborder yitems setbackground yitems setvalues abstracttable ylabel yitems yaxislabel borderlayout borderlayout public test element create test element line chart element new line chart modify test element element return element testelement createtestelement linechart linechart modifytestelement public void modify test element test element element this configure test element element line chart bc line chart element bc setx axis x items get text bc sety axis y items get text bc setx label x axis label get text bc sety label y axis label get text bc set caption caption get text bc setur ls urls get text modifytestelement testelement configuretestelement linechart linechart setxaxis xitems gettext setyaxis yitems gettext setxlabel xaxislabel gettext setylabel yaxislabel gettext setcaption gettext seturls gettext public void configure test element element super configure element line chart bc line chart element x items set text bc getx axis y items set text bc gety axis x axis label set text bc getx label y axis label set text bc gety label caption set text bc get caption urls set text bc getur ls testelement linechart linechart xitems settext getxaxis yitems settext getyaxis xaxislabel settext getxlabel yaxislabel settext getylabel settext getcaption settext geturls to do constructor description public ldap ext sampler todo ldapextsampler public void set conn time out string connto set property new string property connto connto setconntimeout setproperty stringproperty public string get conn time out return get property as string connto getconntimeout getpropertyasstring public void set secure string sec set property new string property secure sec setsecure setproperty stringproperty public boolean is secure return get property as boolean secure issecure getpropertyasboolean public boolean is parse flag return get property as boolean parseflag isparseflag getpropertyasboolean public void set parse flag string parse flag set property new string property parseflag parse flag setparseflag parseflag setproperty stringproperty parseflag gets the username attribute of the ldap object return the username public string get userdn return get property as string userdn getuserdn getpropertyasstring sets the username attribute of the ldap object public void set userdn string new userdn set property new string property userdn new userdn setuserdn newuserdn setproperty stringproperty newuserdn gets the password attribute of the ldap object return the password public string get user pw return get property as string userpw getuserpw getpropertyasstring sets the password attribute of the ldap object public void set user pw string new user pw set property new string property userpw new user pw setuserpw newuserpw setproperty stringproperty newuserpw sets the servername attribute of the server config object param servername the new servername value public void set servername string servername set property new string property servername servername serverconfig setservername setproperty stringproperty sets the port attribute of the server config object param port the new port value public void set port string port set property new string property port port serverconfig setport setproperty stringproperty gets the servername attribute of the ldap sampler object return the servername value public string get servername return get property as string servername ldapsampler getservername getpropertyasstring gets the port attribute of the ldap sampler object return the port value public string get port return get property as string port ldapsampler getport getpropertyasstring sets the rootdn attribute of the ldap sampler object param new rootdn the new rootdn value public void set rootdn string new rootdn this set property rootdn new rootdn ldapsampler newrootdn setrootdn newrootdn setproperty newrootdn gets the rootdn attribute of the ldap sampler object return the rootdn value public string get rootdn return get property as string rootdn ldapsampler getrootdn getpropertyasstring gets the search scope attribute of the ldap sampler object return the scope value public string get scope return get property as string scope ldapsampler getscope getpropertyasstring public int get scope as int return get property as int scope getscopeasint getpropertyasint sets the search scope attribute of the ldap sampler object param new scope the new scope value public void set scope string new scope this set property scope new scope ldapsampler newscope setscope newscope setproperty newscope gets the size limit attribute of the ldap sampler object return the size limit public string get countlim return get property as string countlim ldapsampler getcountlim getpropertyasstring public long get countlim as long return get property as long countlim getcountlimaslong getpropertyaslong sets the size limit attribute of the ldap sampler object param new clim the new size limit value public void set countlim string new clim this set property countlim new clim ldapsampler newclim setcountlim newclim setproperty newclim gets the time limit attribute of the ldap sampler object return the time limit public string get timelim return get property as string timelim ldapsampler gettimelim getpropertyasstring public int get timelim as int return get property as int timelim gettimelimasint getpropertyasint sets the time limit attribute of the ldap sampler object param new tlim the new time limit value public void set timelim string new tlim this set property timelim new tlim ldapsampler newtlim settimelim newtlim setproperty newtlim gets the return objects attribute of the ldap sampler object return if the object s are to be returned public boolean is retobj return get property as boolean retobj ldapsampler isretobj getpropertyasboolean sets the return objects attribute of the ldap sampler object public void set retobj string new robj this set property retobj new robj ldapsampler setretobj newrobj setproperty newrobj gets the deref attribute of the ldap sampler object return if dereferencing is required public boolean is deref return get property as boolean deref ldapsampler isderef getpropertyasboolean sets the deref attribute of the ldap sampler object param new dref the new deref value public void set deref string new dref this set property deref new dref ldapsampler newdref setderef newdref setproperty newdref sets the test attribute of the ldap config object param new test the new test value add modify delete and search public void set test string new test this set property test new test ldapconfig newtest settest newtest setproperty newtest gets the test attribute of the ldap sampler object return the test value add modify delete and search public string get test return get property as string test ldapsampler gettest getpropertyasstring sets the attributes of the ldap config object param new attrs the new attributes value public void set attrs string new attrs this set property attribs new attrs ldapconfig newattrs setattrs newattrs setproperty newattrs gets the attributes of the ldap sampler object return the attributes public string get attrs return get property as string attribs ldapsampler getattrs getpropertyasstring sets the base entry dn attribute of the ldap sampler object param newbaseentry the new base entry dn value public void set base entrydn string newbaseentry set property new string property base entry dn newbaseentry ldapsampler setbaseentrydn setproperty stringproperty base_entry_dn gets the base entrydn attribute of the ldap sampler object return the base entry dn value public string get base entrydn return get property as string base entry dn baseentrydn ldapsampler getbaseentrydn getpropertyasstring base_entry_dn sets the arguments attribute of the ldap config object this will collect values from the table for user defined test case param value the arguments public void set arguments arguments value set property new test element property arguments value ldapconfig setarguments setproperty testelementproperty gets the arguments attribute of the ldap config object return the arguments user defined test case public arguments get arguments return arguments get property arguments get object value ldapconfig getarguments getproperty getobjectvalue sets the arguments attribute of the ldap config object this will collect values from the table for user defined test case param value the arguments public void setldap arguments ldap arguments value set property new test element property ldaparguments value ldapconfig setldaparguments ldaparguments setproperty testelementproperty gets the ldap arguments attribute of the ldap config object return the lda parguments user defined modify test case public ldap arguments getldap arguments return ldap arguments get property ldaparguments get object value ldaparguments ldapconfig ldaparguments ldaparguments getldaparguments ldaparguments getproperty getobjectvalue collect all the values from the table arguments using this create the attributes this will create the attributes for the user defined test case for add test return the attributes private attributes get user attributes attributes attrs new basic attributes true attribute attr property iterator iter get arguments iterator while iter has next argument item argument iter next get object value attr attrs get item get name if attr null attr get basic attribute item get name item get value else attr add item get value attrs put attr return attrs testcase getuserattributes basicattributes propertyiterator getarguments hasnext getobjectvalue getname getbasicattribute getname getvalue getvalue collect all the value from the table arguments using this create the basic attributes this will create the basic attributes for the user defined test case for modify test return the basic attributes private modification item get user mod attributes modification item mods new modification item getldap arguments get arguments size basic attribute attr property iterator iter getldap arguments iterator int count 0 while iter has next ldap argument item ldap argument iter next get object value if item get value length 0 attr new basic attribute item get name else attr get basic attribute item get name item get value final string opcode item get opcode if add equals opcode non nls 1 mods count new modification item dir context add attribute attr else if delete equals opcode non nls 1 remove equals opcode non nls 1 mods count new modification item dir context remove attribute attr else if replace equals opcode non nls 1 mods count new modification item dir context replace attribute attr else log warn invalid op code opcode return mods basicattributes testcase basicattributes modificationitem getusermodattributes modificationitem modificationitem getldaparguments getarguments basicattribute propertyiterator getldaparguments hasnext ldapargument ldapargument getobjectvalue getvalue basicattribute getname getbasicattribute getname getvalue getopcode modificationitem dircontext add_attribute modificationitem dircontext remove_attribute modificationitem dircontext replace_attribute opcode collect all the value from the table arguments using this create the attributes this will create the basic attributes for the user defined test case for search test return the basic attributes private string get request attributes string req attr int index string mods int count 0 if req attr length 0 return null if req attr ends with semi colon req attr req attr semi colon string attr req attr while attr length 0 index attr index of semi colon count 1 attr attr substring index 1 if count 0 mods new string count attr req attr count 0 while attr length 0 index attr index of semi colon mods count attr substring 0 index count 1 attr attr substring index 1 else mods null return mods testcase basicattributes getrequestattributes reqattr reqattr reqattr endswith semi_colon reqattr reqattr semi_colon reqattr indexof semi_colon reqattr indexof semi_colon this will create the basic attribute for the give name value pair return the basic attribute private basic attribute get basic attribute string name string value basic attribute attr new basic attribute name value return attr basicattribute basicattribute getbasicattribute basicattribute basicattribute returns a formatted string label describing this sampler example output return a formatted string label describing this sampler public string get label return ldap this get servername non nls 1 get port non nls 1 this get rootdn non nls 1 getlabel getservername getport getrootdn this will do the add test for the user defined test case private void add test ldap ext client ldap dir context dir context sample result res throws naming exception try res sample start ldap create test dir context get user attributes get base entrydn finally res sample end testcase addtest ldapextclient dircontext dircontext sampleresult namingexception samplestart createtest dircontext getuserattributes getbaseentrydn sampleend this will do the delete test for the user defined test case private void delete test ldap ext client ldap dir context dir context sample result res throws naming exception try res sample start ldap delete test dir context get property as string delete finally res sample end testcase deletetest ldapextclient dircontext dircontext sampleresult namingexception samplestart deletetest dircontext getpropertyasstring sampleend this will do the modify test for the user defined test case private void modify test ldap ext client ldap dir context dir context sample result res throws naming exception try res sample start ldap modify test dir context get user mod attributes get base entrydn finally res sample end testcase modifytest ldapextclient dircontext dircontext sampleresult namingexception samplestart modifytest dircontext getusermodattributes getbaseentrydn sampleend this will do the bind for the user defined thread this bind is used for the whole context private void bind op ldap ext client ldap dir context dir context sample result res throws naming exception dir context ctx dir context ldap contexts remove get thread name if ctx null log warn closing previous context for thread get thread name ctx close try res sample start ctx ldap connect get servername get port get rootdn get userdn get user pw get conn time out is secure finally res sample end ldap contexts put get thread name ctx bindop ldapextclient dircontext dircontext sampleresult namingexception dircontext dircontext ldapcontexts getthreadname getthreadname samplestart getservername getport getrootdn getuserdn getuserpw getconntimeout issecure sampleend ldapcontexts getthreadname this will do the bind and unbind for the user defined test case private void single bind op sample result res throws naming exception ldap ext client ldap temp ldap temp new ldap ext client try res sample start dir context ctx ldap temp connect get servername get port get rootdn get userdn get user pw get conn time out is secure ldap temp disconnect ctx finally res sample end testcase singlebindop sampleresult namingexception ldapextclient ldap_temp ldap_temp ldapextclient samplestart dircontext ldap_temp getservername getport getrootdn getuserdn getuserpw getconntimeout issecure ldap_temp sampleend this will do a moddn opp for the user new dn defined private void rename test ldap ext client ldap dir context dir context sample result res throws naming exception try res sample start ldap moddn op dir context get property as string modddn get property as string newdn finally res sample end renametest ldapextclient dircontext dircontext sampleresult namingexception samplestart moddnop dircontext getpropertyasstring getpropertyasstring sampleend this will do the unbind for the user defined test case as well as inbuilt test case private void unbind op ldap ext client ldap dir context dir context sample result res try res sample start ldap disconnect dir context finally res sample end ldap connections remove get thread name ldap contexts remove get thread name log info context and ldap ext clients removed testcase unbindop ldapextclient dircontext dircontext sampleresult samplestart dircontext sampleend ldapconnections getthreadname ldapcontexts getthreadname ldapextclients to do method description param e to do parameter description return to do return description public sample result sample entry e xml buffer xml buffer new xml buffer xml buffer open tag ldapanswer non nls 1 sample result res new sample result res set response data successfull get bytes res set response message success non nls 1 res set response code 0 non nls 1 res set content type text xml non nls 1 boolean is successful true res set sample label get name ldap ext client temp client ldap ext client ldap connections get get thread name dir context dir context dir context ldap contexts get get thread name if temp client null temp client new ldap ext client try dir context new initial dir context catch naming exception err log error ldap client context creation err ldap connections put get thread name temp client try xml buffer open tag operation non nls 1 final string test type get test xml buffer tag opertype test type non nls 1 log debug performing test test type if test type equals unbind res set sampler data unbind xml buffer tag baseobj get rootdn non nls 1 xml buffer tag binddn get userdn non nls 1 unbind op temp client dir context res else if test type equals bind res set sampler data bind as get userdn xml buffer tag baseobj get rootdn non nls 1 xml buffer tag binddn get userdn non nls 1 xml buffer tag connectionto get conn time out non nls 1 bind op temp client dir context res else if test type equals sbind res set sampler data single bind as get userdn xml buffer tag baseobj get rootdn non nls 1 xml buffer tag binddn get userdn non nls 1 xml buffer tag connectionto get conn time out non nls 1 single bind op res else if test type equals compare res set sampler data compare get property as string comparefilt get property as string comparedn xml buffer tag comparedn get property as string comparedn non nls 1 xml buffer tag comparefilter get property as string comparefilt non nls 1 naming enumeration cmp null try res sample start cmp temp client compare dir context get property as string comparefilt get property as string comparedn if cmp has more res set response code 5 non nls 1 res set response message compare false is successful false finally res sample end if cmp null cmp close else if test type equals add res set sampler data add object get base entrydn xml buffer tag attributes get arguments to string non nls 1 xml buffer tag dn get base entrydn non nls 1 add test temp client dir context res else if test type equals delete res set sampler data delete object get base entrydn xml buffer tag dn get base entrydn non nls 1 delete test temp client dir context res else if test type equals modify res set sampler data modify object get base entrydn xml buffer tag dn get base entrydn non nls 1 xml buffer tag attributes getldap arguments to string non nls 1 modify test temp client dir context res else if test type equals rename res set sampler data moddn object get property as string modddn to get property as string newdn xml buffer tag dn get property as string modddn non nls 1 xml buffer tag newdn get property as string newdn non nls 1 rename test temp client dir context res else if test type equals search final string scope str get scope final int scope get scope as int final string search filter get property as string searchfilter final string search base get property as string searchbase final string time limit get timelim final string count limit get countlim res set sampler data search with filter search filter xml buffer tag searchfilter search filter non nls 1 xml buffer tag baseobj get rootdn non nls 1 xml buffer tag searchbase search base non nls 1 xml buffer tag scope scope str non nls 1 xml buffer tag countlimit count limit non nls 1 xml buffer tag timelimit time limit non nls 1 naming enumeration srch null try res sample start srch temp client search test dir context search base search filter scope get countlim as long get timelim as int get request attributes get attrs is retobj is deref if is parse flag try xml buffer open tag searchresults non nls 1 write search results xml buffer srch finally xml buffer close tag searchresults non nls 1 else xml buffer tag searchresults non nls 1 has elements srch has more elements non nls 1 finally if srch null srch close res sample end catch naming exception ex log warn debug ex e g javax naming size limit exceeded exception ldap error code 4 sizelimit exceeded remaining name 123456789012345678901 todo tidy this up string return data ex to string final int index ofldap err code return data index of ldap error code if index ofldap err code 0 res set response message return data substring index ofldap err code 21 return data index of non nls 1 res set response code return data substring index ofldap err code 17 index ofldap err code 19 else res set response message return data res set response code 800 non nls 1 is successful false finally xml buffer close tag operation non nls 1 xml buffer tag responsecode res get response code non nls 1 xml buffer tag responsemessage res get response message non nls 1 res set response data xml buffer to string get bytes res set data type sample result text res set successful is successful return res todo todo todo sampleresult xmlbuffer xmlbuffer xmlbuffer xmlbuffer opentag sampleresult sampleresult setresponsedata getbytes setresponsemessage setresponsecode setcontenttype issuccessful setsamplelabel getname ldapextclient temp_client ldapextclient ldapconnections getthreadname dircontext dircontext dircontext ldapcontexts getthreadname temp_client temp_client ldapextclient dircontext initialdircontext namingexception ldapconnections getthreadname temp_client xmlbuffer opentag testtype gettest xmlbuffer testtype testtype testtype setsamplerdata xmlbuffer getrootdn xmlbuffer getuserdn unbindop temp_client dircontext testtype setsamplerdata getuserdn xmlbuffer getrootdn xmlbuffer getuserdn xmlbuffer getconntimeout bindop temp_client dircontext testtype setsamplerdata singlebind getuserdn xmlbuffer getrootdn xmlbuffer getuserdn xmlbuffer getconntimeout singlebindop testtype setsamplerdata getpropertyasstring getpropertyasstring xmlbuffer getpropertyasstring xmlbuffer getpropertyasstring namingenumeration samplestart temp_client dircontext getpropertyasstring getpropertyasstring hasmore setresponsecode setresponsemessage comparefalse issuccessful sampleend testtype setsamplerdata getbaseentrydn xmlbuffer getarguments tostring xmlbuffer getbaseentrydn addtest temp_client dircontext testtype setsamplerdata getbaseentrydn xmlbuffer getbaseentrydn deletetest temp_client dircontext testtype setsamplerdata getbaseentrydn xmlbuffer getbaseentrydn xmlbuffer getldaparguments tostring modifytest temp_client dircontext testtype setsamplerdata getpropertyasstring getpropertyasstring xmlbuffer getpropertyasstring xmlbuffer getpropertyasstring renametest temp_client dircontext testtype scopestr getscope getscopeasint searchfilter getpropertyasstring searchbase getpropertyasstring timelimit gettimelim countlimit getcountlim setsamplerdata searchfilter xmlbuffer searchfilter xmlbuffer getrootdn xmlbuffer searchbase xmlbuffer scopestr xmlbuffer countlimit xmlbuffer timelimit namingenumeration samplestart temp_client searchtest dircontext searchbase searchfilter getcountlimaslong gettimelimasint getrequestattributes getattrs isretobj isderef isparseflag xmlbuffer opentag writesearchresults xmlbuffer xmlbuffer closetag xmlbuffer haselements hasmoreelements sampleend namingexception sizelimitexceededexception returndata tostring indexofldaperrcode returndata indexof indexofldaperrcode setresponsemessage returndata indexofldaperrcode returndata indexof setresponsecode returndata indexofldaperrcode indexofldaperrcode setresponsemessage returndata setresponsecode issuccessful xmlbuffer closetag xmlbuffer getresponsecode xmlbuffer getresponsemessage setresponsedata xmlbuffer tostring getbytes setdatatype sampleresult setsuccessful issuccessful private void write search results final xml buffer xmlb final naming enumeration srch throws naming exception final array list sorted results new array list max sorted results final string search base get property as string searchbase final string root dn get rootdn read all sorted results into memory so we can guarantee ordering try while srch has more sorted results size max sorted results final search result sr search result srch next must be done prior to sorting normalise searchdn sr search base root dn sorted results add sr finally show what we did manage to retrieve sort results sorted results for iterator it sorted results iterator it has next final search result sr search result it next write search result sr xmlb while srch has more if there s anything left final search result sr search result srch next normalise searchdn sr search base root dn write search result sr xmlb writesearchresults xmlbuffer namingenumeration namingexception arraylist sortedresults arraylist max_sorted_results searchbase getpropertyasstring rootdn getrootdn sortedresults hasmore sortedresults max_sorted_results searchresult searchresult normalisesearchdn searchbase rootdn sortedresults sortresults sortedresults sortedresults hasnext searchresult searchresult writesearchresult hasmore searchresult searchresult normalisesearchdn searchbase rootdn writesearchresult private void write search result final search result sr final xml buffer xmlb throws naming exception final attributes attrs sr get attributes final int size attrs size final array list sorted attrs new array list size xmlb open tag searchresult non nls 1 xmlb tag dn sr get name non nls 1 xmlb tag returnedattr integer to string size non nls 1 xmlb open tag attributes non nls 1 try for naming enumeration en attrs get all en has more final attribute attr attribute en next sorted attrs add attr sort attributes sorted attrs for iterator ait sorted attrs iterator ait has next final attribute attr attribute ait next string buffer sb new string buffer if attr size 1 sb append get write value attr get else final array list sorted vals new array list attr size boolean first true for naming enumeration ven attr get all ven has more final object value get write value ven next sorted vals add value to string collections sort sorted vals for iterator vit sorted vals iterator vit has next final string value string vit next if first first false else sb append non nls 1 sb append value xmlb tag attr getid sb finally xmlb close tag attributes non nls 1 xmlb close tag searchresult non nls 1 writesearchresult searchresult xmlbuffer namingexception getattributes arraylist sortedattrs arraylist opentag getname tostring opentag namingenumeration getall hasmore sortedattrs sortattributes sortedattrs sortedattrs hasnext stringbuffer stringbuffer getwritevalue arraylist sortedvals arraylist namingenumeration getall hasmore getwritevalue sortedvals tostring sortedvals sortedvals hasnext closetag closetag private void sort attributes final array list sorted attrs collections sort sorted attrs new comparator public int compare object o1 object o2 string nm1 attribute o1 getid string nm2 attribute o2 getid return nm1 compare to nm2 sortattributes arraylist sortedattrs sortedattrs compareto public int compare object o1 object o2 string nm1 attribute o1 getid string nm2 attribute o2 getid return nm1 compare to nm2 compareto private void sort results final array list sorted results collections sort sorted results new comparator private int compare to reverse final string s1 final string s2 int len1 s1 length int len2 s2 length int s1i len1 1 int s2i len2 1 for s1i 0 s2i 0 s1i s2i char c1 s1 char at s1i char c2 s2 char at s2i if c1 c2 return c1 c2 return len1 len2 public int compare object o1 object o2 string nm1 search result o1 get name string nm2 search result o2 get name if nm1 null nm1 if nm2 null nm2 return compare to reverse nm1 nm2 sortresults arraylist sortedresults sortedresults comparetoreverse charat charat searchresult getname searchresult getname comparetoreverse private int compare to reverse final string s1 final string s2 int len1 s1 length int len2 s2 length int s1i len1 1 int s2i len2 1 for s1i 0 s2i 0 s1i s2i char c1 s1 char at s1i char c2 s2 char at s2i if c1 c2 return c1 c2 return len1 len2 comparetoreverse charat charat public int compare object o1 object o2 string nm1 search result o1 get name string nm2 search result o2 get name if nm1 null nm1 if nm2 null nm2 return compare to reverse nm1 nm2 searchresult getname searchresult getname comparetoreverse private string normalise searchdn final search result sr final string search base final string root dn string sr name sr get name if sr name ends with search base if sr name length 0 sr name sr name sr name sr name search base if root dn length 0 sr name ends with root dn if sr name length 0 sr name sr name sr name sr name root dn sr set name sr name return sr name normalisesearchdn searchresult searchbase rootdn srname getname srname endswith searchbase srname srname srname srname srname searchbase rootdn srname endswith rootdn srname srname srname srname srname rootdn setname srname srname private string get write value final object value if value instanceof string assume it s senstive data return string escape utils escape xml string value if value instanceof byte try return string escape utils escape xml new string byte value utf 8 non nls 1 catch unsupported encoding exception e log error this can t happen utf 8 character encoding not supported e return string escape utils escape xml value to string getwritevalue stringescapeutils escapexml stringescapeutils escapexml unsupportedencodingexception stringescapeutils escapexml tostring public void test started test started non nls 1 teststarted teststarted public void test ended test ended non nls 1 testended testended public void test started string host ignored teststarted ensure any remaining contexts are closed public void test ended string host iterator it ldap contexts entry set iterator while it has next map entry entry map entry it next string key string entry get key dir context dc dir context entry get value try log warn tidying old context for thread key dc close catch naming exception ignored ignored it remove make sure the entry is not left around for the next run testended ldapcontexts entryset hasnext getkey dircontext dircontext getvalue namingexception public void test iteration start loop iteration event event ignored testiterationstart loopiterationevent private array stack tags new array stack opened tags public xml buffer arraystack arraystack xmlbuffer private void start tag string t sb append sb append t sb append starttag private void end tag string t sb append sb append t sb append sb append n endtag private void empty tag string t sb append sb append t sb append sb append n emptytag open a tag save on stack param tagname return this public xml buffer open tag string tagname tags push tagname start tag tagname return this xmlbuffer opentag starttag close top tag from stack param tagname return this throws illegal argument exception if the tag names do not match public xml buffer close tag string tagname string tag string tags pop if tag equals tagname throw new illegal argument exception trying to close tag tagname should be tag end tag tag return this illegalargumentexception xmlbuffer closetag illegalargumentexception endtag add a complete tag with content param tagname param content return this public xml buffer tag string tagname string content if content length 0 empty tag tagname else start tag tagname sb append content end tag tagname return this xmlbuffer emptytag starttag endtag add a complete tag with content param tagname param content return this public xml buffer tag string tagname string buffer content if content length 0 empty tag tagname else start tag tagname sb append content end tag tagname return this xmlbuffer stringbuffer emptytag starttag endtag convert the buffer to a string closing any open tags public string to string while tags is empty end tag string tags pop return sb to string tostring isempty endtag tostring public report check dirty previous gui items new hash map report action router get instance add pre action listener report exit command class this reportcheckdirty previousguiitems hashmap reportactionrouter getinstance addpreactionlistener reportexitcommand public void action performed action event e if e get action command equals report exit command exit do action e actionperformed actionevent getactioncommand reportexitcommand doaction see org apache jmeter gui action command do action action event public void do action action event e string action e get action command if action equals sub tree saved hash tree sub tree hash tree e get source sub tree traverse this else if action equals sub tree loaded listed hash tree add tree listed hash tree e get source add tree traverse this else if action equals add all previous gui items clear report gui package get instance get tree model get report plan traverse this else if action equals remove report gui package gui package report gui package get instance report tree node nodes gui package get tree listener get selected nodes remove mode true for int i nodes length 1 i 0 i gui package get tree model get current sub tree nodes i traverse this remove mode false check mode true dirty false hash tree whole tree report gui package get instance get tree model get report plan whole tree traverse this report gui package get instance set dirty dirty check mode false doaction actionevent doaction actionevent getactioncommand sub_tree_saved hashtree subtree hashtree getsource subtree sub_tree_loaded listedhashtree addtree listedhashtree getsource addtree add_all previousguiitems reportguipackage getinstance gettreemodel getreportplan reportguipackage guipackage reportguipackage getinstance reporttreenode guipackage gettreelistener getselectednodes removemode guipackage gettreemodel getcurrentsubtree removemode checkmode hashtree wholetree reportguipackage getinstance gettreemodel getreportplan wholetree reportguipackage getinstance setdirty checkmode the tree traverses itself depth first calling process node for each object it encounters as it goes public void add node object node hash tree sub tree log debug node is class node get class report tree node tree node report tree node node if check mode if previous gui items contains key tree node if previous gui items get tree node equals tree node get test element dirty true else dirty true else if remove mode previous gui items remove tree node else previous gui items put tree node tree node get test element clone processnode addnode hashtree subtree getclass reporttreenode treenode reporttreenode checkmode previousguiitems containskey treenode previousguiitems treenode treenode gettestelement removemode previousguiitems treenode previousguiitems treenode treenode gettestelement indicates traversal has moved up a step and the visitor should remove the top node from it s stack structure public void subtract node subtractnode process path is called when a leaf is reached if a visitor wishes to generate lists of path elements to each leaf it should keep a stack data structure of nodes passed to it with add node and removing top items for every subtract node call public void process path addnode subtractnode processpath see org apache jmeter gui action command get action names public set get action names return commands getactionnames getactionnames public remote sample listener impl object listener throws remote exception super if listener instanceof test listener test listener test listener listener else test listener null if listener instanceof sample listener sample listener sample listener listener else sample listener null remotesamplelistenerimpl remoteexception testlistener testlistener testlistener testlistener samplelistener samplelistener samplelistener samplelistener public void test started if test listener null test listener test started teststarted testlistener testlistener teststarted public void test started string host if test listener null test listener test started host teststarted testlistener testlistener teststarted public void test ended if test listener null test listener test ended testended testlistener testlistener testended public void test ended string host if test listener null test listener test ended host testended testlistener testlistener testended public void test iteration start loop iteration event event if test listener null test listener test iteration start event testiterationstart loopiterationevent testlistener testlistener testiterationstart this method is called remotely and fires a list of samples events received locally the function is to reduce network load when using remote testing param samples the list of sample events to be fired locally public void process batch list samples if samples null iterator iter samples iterator while iter has next sample event e sample event iter next sample occurred e processbatch hasnext sampleevent sampleevent sampleoccurred public void sample occurred sample event e if sample listener null sample listener sample occurred e sampleoccurred sampleevent samplelistener samplelistener sampleoccurred a sample has started public void sample started sample event e if sample listener null sample listener sample started e samplestarted sampleevent samplelistener samplelistener samplestarted a sample has stopped public void sample stopped sample event e if sample listener null sample listener sample stopped e samplestopped sampleevent samplelistener samplelistener samplestopped public save graphics service super savegraphicsservice method will save the j component as an image the formats are png and tiff param filename param type param component public void savej component string filename int type j component component dimension size component get size buffered image image new buffered image size width size height buffered image type byte indexed graphics2d grp image create graphics component paint grp if type png filename png extension this savepng with batik filename image else if type tiff filename filename tiff extension this savetiff with batik filename image jcomponent savejcomponent jcomponent getsize bufferedimage bufferedimage bufferedimage type_byte_indexed creategraphics png_extension savepngwithbatik tiff_extension savetiffwithbatik use batik to save a png of the graph param filename param image public void savepng with batik string filename buffered image image file outfile new file filename output stream fos create file outfile if fos null return png encode param param png encode param get default encode param image png image encoder encoder new png image encoder fos param try encoder encode image catch io exception e j meter utils report error to user png image encoder reported e get message problem creating image file finally j orphan utils close quietly fos savepngwithbatik bufferedimage outputstream createfile pngencodeparam pngencodeparam getdefaultencodeparam pngimageencoder pngimageencoder ioexception jmeterutils reporterrortouser pngimageencoder getmessage jorphanutils closequietly use batik to save a tiff file of the graph param filename param image public void savetiff with batik string filename buffered image image file outfile new file filename output stream fos create file outfile if fos null return tiff encode param param new tiff encode param tiff image encoder encoder new tiff image encoder fos param try encoder encode image catch io exception e j meter utils report error to user tiff image encoder reported e get message problem creating image file yuck tiff image encoder uses error to report runtime problems catch error e j meter utils report error to user tiff image encoder reported e get message problem creating image file if e get class error class rethrow other errors throw e finally j orphan utils close quietly fos savetiffwithbatik bufferedimage outputstream createfile tiffencodeparam tiffencodeparam tiffimageencoder tiffimageencoder ioexception jmeterutils reporterrortouser tiffimageencoder getmessage tiffimageencoder jmeterutils reporterrortouser tiffimageencoder getmessage getclass jorphanutils closequietly create a new file for the graphics since the method creates a new file we shouldn t get a fnfe param filename return output stream created from the filename private file output stream create file file filename try return new file output stream filename catch file not found exception e j meter utils report error to user could not create file e get message problem creating image file return null fileoutputstream createfile fileoutputstream filenotfoundexception jmeterutils reporterrortouser getmessage public abstract class abstract controller gui extends abstractj meter gui component when a user right clicks on the component in the test tree or selects the edit menu when the component is selected the component will be asked to return a j popup menu that provides all the options available to the user from this component p this implementation returns menu items appropriate for most controller components return a j popup menu appropriate for the component public j popup menu create popup menu return menu factory get default controller menu abstractcontrollergui abstractjmeterguicomponent jpopupmenu jpopupmenu jpopupmenu createpopupmenu menufactory getdefaultcontrollermenu this is the list of menu categories this gui component will be available under this implementation returns link org apache jmeter gui util menu factory controllers which is appropriate for most controller components return a collection of strings where each element is one of the constants defined in menu factory public collection get menu categories return arrays as list new string menu factory controllers menufactory menufactory getmenucategories aslist menufactory notify a list of listeners that a sample has occurred param res the sample event that has occurred must be non null param listeners a list of the listeners which should be notified this list must not be null and must contain only sample listener elements public void notify listeners sample event res list listeners iterator iter listeners iterator while iter has next try sample listener sample listener sample listener iter next test bean helper prepare test element sample listener sample listener sample occurred res catch runtime exception e log error detected problem in listener e log info continuing to process further listeners samplelistener notifylisteners sampleevent hasnext samplelistener samplelistener samplelistener testbeanhelper testelement samplelistener samplelistener sampleoccurred runtimeexception private j button generate button public function helper super j frame null j meter utils get res string function helper title false non nls 1 init jbutton generatebutton functionhelper jframe jmeterutils getresstring function_helper_title private void init parameter panel new arguments panel j meter utils get res string function params non nls 1 initialize function list this get content pane set layout new border layout 10 10 j panel combo panel new j panel new flow layout flow layout center combo panel add function list j button help button new j button j meter utils get res string help non nls 1 help button add action listener new help listener combo panel add help button this get content pane add combo panel border layout north this get content pane add parameter panel border layout center j panel results panel new j panel new flow layout flow layout center cut paste function new j labeled text field j meter utils get res string cut paste function 35 non nls 1 results panel add cut paste function generate button new j button j meter utils get res string generate non nls 1 generate button add action listener this results panel add generate button this get content pane add results panel border layout south this pack component util center component in window this parameterpanel argumentspanel jmeterutils getresstring function_params initializefunctionlist getcontentpane setlayout borderlayout jpanel combopanel jpanel flowlayout flowlayout combopanel functionlist jbutton helpbutton jbutton jmeterutils getresstring helpbutton addactionlistener helplistener combopanel helpbutton getcontentpane combopanel borderlayout getcontentpane parameterpanel borderlayout jpanel resultspanel jpanel flowlayout flowlayout cutpastefunction jlabeledtextfield jmeterutils getresstring cut_paste_function resultspanel cutpastefunction generatebutton jbutton jmeterutils getresstring generatebutton addactionlistener resultspanel generatebutton getcontentpane resultspanel borderlayout componentutil centercomponentinwindow private void initialize function list try list function classes class finder find classes that extend j meter utils get search paths new class function class true iterator iter function classes iterator string function names new string function classes size int count 0 while iter has next class cl class for name string iter next function names count function cl new instance get reference key function map put function names count cl count function list new j labeled choice j meter utils get res string choose function function names non nls 1 function list add change listener this catch io exception e catch class not found exception e catch instantiation exception e catch illegal access exception e initializefunctionlist functionclasses classfinder findclassesthatextend jmeterutils getsearchpaths functionclasses functionnames functionclasses hasnext forname functionnames newinstance getreferencekey functionmap functionnames functionlist jlabeledchoice jmeterutils getresstring choose_function functionnames functionlist addchangelistener ioexception classnotfoundexception instantiationexception illegalaccessexception public void state changed change event event try arguments args new arguments function function function class function map get function list get text new instance list argument desc function get argument desc iterator iter argument desc iterator while iter has next string help string iter next args add argument help non nls 1 parameter panel configure args parameter panel revalidate get content pane remove parameter panel this pack get content pane add parameter panel border layout center this pack this validate this repaint catch instantiation exception e catch illegal access exception e statechanged changeevent functionmap functionlist gettext newinstance argumentdesc getargumentdesc argumentdesc hasnext addargument parameterpanel parameterpanel getcontentpane parameterpanel getcontentpane parameterpanel borderlayout instantiationexception illegalaccessexception public void action performed action event e string buffer function call new string buffer function call append function list get text arguments args arguments parameter panel create test element if args get arguments size 0 function call append property iterator iter args iterator boolean first true while iter has next argument arg argument iter next get object value if first function call append function call append arg get value first false function call append function call append cut paste function set text function call to string actionperformed actionevent stringbuffer functioncall stringbuffer functioncall functionlist gettext parameterpanel createtestelement getarguments functioncall propertyiterator hasnext getobjectvalue functioncall functioncall getvalue functioncall functioncall cutpastefunction settext functioncall tostring private class help listener implements action listener public void action performed action event e string source new string help help functions function list get text action event help event new action event source e getid help non nls 1 action router get instance action performed help event helplistener actionlistener actionperformed actionevent help_functions functionlist gettext actionevent helpevent actionevent actionrouter getinstance actionperformed helpevent public abstract class abstract parser control implements parser control by default always continue parsing by returning false param last option code the code of last option parsed return return true to halt false to continue parsing see parser control is finished int public boolean is finished int last option code return false abstractparsercontrol parsercontrol lastoptioncode parsercontrol isfinished isfinished lastoptioncode public proxy control set port default port set exclude list new hash set set include list new hash set set capture http headers true maintain original behaviour proxycontrol setport default_port setexcludelist hashset setincludelist hashset setcapturehttpheaders public void set port int port this set property new integer property port port setport setproperty integerproperty public void set port string port set property port port setport setproperty public void set capture http headers boolean capture set property new boolean property capture http headers capture setcapturehttpheaders setproperty booleanproperty capture_http_headers public void set grouping mode int grouping this grouping mode grouping set property new integer property grouping mode grouping setgroupingmode groupingmode setproperty integerproperty grouping_mode public void set assertions boolean b add assertions b set property new boolean property add assertions b setassertions addassertions setproperty booleanproperty add_assertions public void set sampler type name int sampler type name set property new integer property sampler type name sampler type name setsamplertypename samplertypename setproperty integerproperty sampler_type_name samplertypename public void set sampler redirect automatically boolean b sampler redirect automatically b set property new boolean property sampler redirect automatically b setsamplerredirectautomatically samplerredirectautomatically setproperty booleanproperty sampler_redirect_automatically public void set sampler follow redirects boolean b sampler follow redirects b set property new boolean property sampler follow redirects b setsamplerfollowredirects samplerfollowredirects setproperty booleanproperty sampler_follow_redirects param b public void set use keep alive boolean b use keep alive b set property new boolean property use keepalive b setusekeepalive usekeepalive setproperty booleanproperty use_keepalive public void set sampler download images boolean b sampler download images b set property new boolean property sampler download images b setsamplerdownloadimages samplerdownloadimages setproperty booleanproperty sampler_download_images public void set include list collection list set property new collection property include list new hash set list setincludelist setproperty collectionproperty include_list hashset public void set exclude list collection list set property new collection property exclude list new hash set list setexcludelist setproperty collectionproperty exclude_list hashset param b public void set regex match boolean b regex match b set property new boolean property regex match b setregexmatch regexmatch setproperty booleanproperty regex_match public void set https spoof boolean b set property new boolean property https spoof b sethttpsspoof setproperty booleanproperty https_spoof public void set https spoof match string s set property new string property https spoof match s sethttpsspoofmatch setproperty stringproperty https_spoof_match public void set content type exclude string content type exclude set property new string property content type exclude content type exclude setcontenttypeexclude contenttypeexclude setproperty stringproperty content_type_exclude contenttypeexclude public void set content type include string content type include set property new string property content type include content type include setcontenttypeinclude contenttypeinclude setproperty stringproperty content_type_include contenttypeinclude public boolean get assertions return get property as boolean add assertions getassertions getpropertyasboolean add_assertions public int get grouping mode return get property as int grouping mode getgroupingmode getpropertyasint grouping_mode public int get port return get property as int port getport getpropertyasint public string get port string return get property as string port getportstring getpropertyasstring public int get default port return default port getdefaultport default_port public boolean get capture http headers return get property as boolean capture http headers getcapturehttpheaders getpropertyasboolean capture_http_headers public int get sampler type name return get property as int sampler type name getsamplertypename getpropertyasint sampler_type_name public boolean get sampler redirect automatically return get property as boolean sampler redirect automatically false getsamplerredirectautomatically getpropertyasboolean sampler_redirect_automatically public boolean get sampler follow redirects return get property as boolean sampler follow redirects true getsamplerfollowredirects getpropertyasboolean sampler_follow_redirects public boolean get use keepalive return get property as boolean use keepalive true getusekeepalive getpropertyasboolean use_keepalive public boolean get sampler download images return get property as boolean sampler download images false getsamplerdownloadimages getpropertyasboolean sampler_download_images public boolean get regex match return get property as boolean regex match false getregexmatch getpropertyasboolean regex_match public boolean get https spoof return get property as boolean https spoof false gethttpsspoof getpropertyasboolean https_spoof public string get https spoof match return get property as string https spoof match gethttpsspoofmatch getpropertyasstring https_spoof_match public string get content type exclude return get property as string content type exclude getcontenttypeexclude getpropertyasstring content_type_exclude public string get content type include return get property as string content type include getcontenttypeinclude getpropertyasstring content_type_include public class get gui class return org apache jmeter protocol http proxy gui proxy control gui class getguiclass proxycontrolgui public void add config element config element config addconfigelement configelement public void start proxy throws io exception notify test listeners of start try server new daemon get port this server start catch io exception e log error could not create proxy daemon e throw e startproxy ioexception notifytestlistenersofstart getport ioexception public void add excluded pattern string pattern get exclude patterns add item pattern addexcludedpattern getexcludepatterns additem public collection property get exclude patterns return collection property get property exclude list collectionproperty getexcludepatterns collectionproperty getproperty exclude_list public void add included pattern string pattern get include patterns add item pattern addincludedpattern getincludepatterns additem public collection property get include patterns return collection property get property include list collectionproperty getincludepatterns collectionproperty getproperty include_list public void clear excluded patterns get exclude patterns clear clearexcludedpatterns getexcludepatterns public void clear included patterns get include patterns clear clearincludedpatterns getincludepatterns return the target controller node public j meter tree node get target return target jmetertreenode gettarget sets the target node where the samples generated by the proxy have to be stored public void set target j meter tree node target this target target settarget jmetertreenode receives the recorded sampler from the proxy server for placing in the test tree param server response to be added to allow saving of the server s response while recording a future consideration public synchronized void deliver sampler http sampler base sampler test element sub configs sample result result if filter content type result filter url sampler j meter tree node my target find target controller node collection default configurations find applicable elements my target config test element class false collection user defined variables find applicable elements my target arguments class true remove values from sampler sampler default configurations replace values sampler sub configs user defined variables sampler set auto redirects sampler redirect automatically sampler set follow redirects sampler follow redirects sampler set use keep alive use keep alive sampler set image parser sampler download images place sampler sampler sub configs my target else if log is debug enabled log debug sample excluded based on url or content type result get url as string result get content type result set sample label result get sample label sample event is not passed j meter variables because they don t make sense for proxy recording notify sample listeners new sample event result work bench todo is this the correct threadgroup name serverresponse deliversampler httpsamplerbase testelement subconfigs sampleresult filtercontenttype filterurl jmetertreenode mytarget findtargetcontrollernode defaultconfigurations findapplicableelements mytarget configtestelement userdefinedvariables findapplicableelements mytarget removevaluesfromsampler defaultconfigurations replacevalues subconfigs userdefinedvariables setautoredirects samplerredirectautomatically setfollowredirects samplerfollowredirects setusekeepalive usekeepalive setimageparser samplerdownloadimages placesampler subconfigs mytarget isdebugenabled geturlasstring getcontenttype setsamplelabel getsamplelabel sampleevent jmetervariables notifysamplelisteners sampleevent workbench public void stop proxy if server null server stop server try server join 1000 wait for server to stop catch interrupted exception e notify test listeners of end server null stopproxy stopserver interruptedexception notifytestlistenersofend package protected to allow test case access boolean filter url http sampler base sampler string domain sampler get domain if domain null domain length 0 return false string url generate match url sampler collection property include patterns get include patterns if include patterns size 0 if matches patterns url include patterns return false collection property exclude patterns get exclude patterns if exclude patterns size 0 if matches patterns url exclude patterns return false return true filterurl httpsamplerbase getdomain generatematchurl collectionproperty includepatterns getincludepatterns includepatterns matchespatterns includepatterns collectionproperty excludepatterns getexcludepatterns excludepatterns matchespatterns excludepatterns package protected to allow test case access filter the response based on the content type if no include nor exclude filter is specified the result will be included param result the sample result to check boolean filter content type sample result result string include exp get content type include string exclude exp get content type exclude if no expressions are specified we let the sample pass if include exp null include exp length 0 exclude exp null exclude exp length 0 return true check that we have a content type string sample content type result get content type if sample content type null sample content type length 0 if log is debug enabled log debug no content type found for result get url as string return true if log is debug enabled log debug content type to filter sample content type check if the include pattern is mathed if include exp null include exp length 0 if log is debug enabled log debug include expression include exp pattern pattern null try pattern j meter utils get pattern cache get pattern include exp perl5 compiler read only mask perl5 compiler singleline mask if j meter utils get matcher contains sample content type pattern return false catch malformed cache pattern exception e log warn skipped invalid content include pattern include exp e check if the exclude pattern is mathed if exclude exp null exclude exp length 0 if log is debug enabled log debug exclude expression exclude exp pattern pattern null try pattern j meter utils get pattern cache get pattern exclude exp perl5 compiler read only mask perl5 compiler singleline mask if j meter utils get matcher contains sample content type pattern return false catch malformed cache pattern exception e log warn skipped invalid content exclude pattern include exp e return true filtercontenttype sampleresult includeexp getcontenttypeinclude excludeexp getcontenttypeexclude includeexp includeexp excludeexp excludeexp samplecontenttype getcontenttype samplecontenttype samplecontenttype isdebugenabled geturlasstring isdebugenabled samplecontenttype includeexp includeexp isdebugenabled includeexp jmeterutils getpatterncache getpattern includeexp perl5compiler read_only_mask perl5compiler singleline_mask jmeterutils getmatcher samplecontenttype malformedcachepatternexception includeexp excludeexp excludeexp isdebugenabled excludeexp jmeterutils getpatterncache getpattern excludeexp perl5compiler read_only_mask perl5compiler singleline_mask jmeterutils getmatcher samplecontenttype malformedcachepatternexception includeexp private void add assertion j meter tree model model j meter tree node node throws illegal user action exception response assertion ra new response assertion ra set property test element gui class assertion gui ra set name j meter utils get res string assertion title non nls 1 ra set test field response data model add component ra node addassertion jmetertreemodel jmetertreenode illegaluseractionexception responseassertion responseassertion setproperty testelement gui_class assertion_gui setname jmeterutils getresstring assertion_title settestfieldresponsedata addcomponent private void add divider j meter tree model model j meter tree node node throws illegal user action exception generic controller sc new generic controller sc set property test element gui class logic controller gui sc set name non nls 1 model add component sc node adddivider jmetertreemodel jmetertreenode illegaluseractionexception genericcontroller genericcontroller setproperty testelement gui_class logic_controller_gui setname addcomponent helper method to add a simple controller to contain the samplers param model test component tree model param node node in the tree where we will add the controller param name a name for the controller private void add simple controller j meter tree model model j meter tree node node string name throws illegal user action exception generic controller sc new generic controller sc set property test element gui class logic controller gui sc set name name model add component sc node addsimplecontroller jmetertreemodel jmetertreenode illegaluseractionexception genericcontroller genericcontroller setproperty testelement gui_class logic_controller_gui setname addcomponent helpler method to replicate any timers found within the proxy controller into the provided sampler while replacing any occurences of string t in the timer s configuration with the provided deltat param model test component tree model param node sampler node in where we will add the timers param deltat time interval from the previous request private void add timers j meter tree model model j meter tree node node long deltat test plan variables new test plan variables add parameter t long to string deltat non nls 1 value replacer replacer new value replacer variables j meter tree node my self model get node of this enumeration children my self children while children has more elements j meter tree node template node j meter tree node children next element if template node is enabled test element template template node get test element if template instanceof timer test element timer test element template clone try replacer undo reverse replace timer model add component timer node catch invalid variable exception e not 100 sure but i believe this can t happen so i ll log and throw an error log error program error e throw new error e catch illegal user action exception e not 100 sure but i believe this can t happen so i ll log and throw an error log error program error e throw new error e _t_ addtimers jmetertreemodel jmetertreenode testplan testplan addparameter tostring valuereplacer valuereplacer jmetertreenode myself getnodeof myself hasmoreelements jmetertreenode templatenode jmetertreenode nextelement templatenode isenabled testelement templatenode gettestelement testelement testelement undoreversereplace addcomponent invalidvariableexception illegaluseractionexception finds the first enabled node of a given type in the tree param type class of the node to be found return the first node of the given type in the test component tree or code null code if none was found private j meter tree node find first node of type class type j meter tree model tree model gui package get instance get tree model list nodes tree model get nodes of type type iterator iter nodes iterator while iter has next j meter tree node node j meter tree node iter next if node is enabled return node return null jmetertreenode findfirstnodeoftype jmetertreemodel treemodel guipackage getinstance gettreemodel treemodel getnodesoftype hasnext jmetertreenode jmetertreenode isenabled finds the controller where samplers have to be stored that is ul li the controller specified by the code target code property li if none was specified the first recording controller in the tree li if none is found the first thread group in the tree li if none is found the workspace ul return the tree node for the controller where the proxy must store the generated samplers private j meter tree node find target controller node j meter tree node my target get target if my target null return my target my target find first node of type recording controller class if my target null return my target my target find first node of type thread group class if my target null return my target my target find first node of type work bench class if my target null return my target log error program error proxy recording target not found return null recordingcontroller threadgroup jmetertreenode findtargetcontrollernode jmetertreenode mytarget gettarget mytarget mytarget mytarget findfirstnodeoftype recordingcontroller mytarget mytarget mytarget findfirstnodeoftype threadgroup mytarget mytarget mytarget findfirstnodeoftype workbench mytarget mytarget finds all configuration objects of the given class applicable to the recorded samplers that is ul li all such elements directly within the http proxy server these have the highest priority li all such elements directly within the target controller higher priority or directly within any containing controller lower priority including the test plan itself lowest priority ul param my target tree node for the recording target controller param my class class of the elements to be found param ascending true if returned elements should be ordered in ascending priority false if they should be in descending priority return a collection of applicable objects of the given class private collection find applicable elements j meter tree node my target class my class boolean ascending j meter tree model tree model gui package get instance get tree model linked list elements new linked list look for elements directly within the http proxy enumeration kids tree model get node of this children while kids has more elements j meter tree node sub node j meter tree node kids next element if sub node is enabled test element element test element sub node get user object if my class is instance element if ascending elements add first element else elements add element look for arguments elements in the target controller or higher up for j meter tree node controller my target controller null controller j meter tree node controller get parent kids controller children while kids has more elements j meter tree node sub node j meter tree node kids next element if sub node is enabled test element element test element sub node get user object if my class is instance element log debug applicable element get name if ascending elements add first element else elements add element special case for the test plan s arguments sub element if element instanceof test plan test plan tp test plan element arguments args tp get arguments if my class is instance args if ascending elements add first args else elements add args return elements mytarget myclass findapplicableelements jmetertreenode mytarget myclass jmetertreemodel treemodel guipackage getinstance gettreemodel linkedlist linkedlist treemodel getnodeof hasmoreelements jmetertreenode subnode jmetertreenode nextelement subnode isenabled testelement testelement subnode getuserobject myclass isinstance addfirst jmetertreenode mytarget jmetertreenode getparent hasmoreelements jmetertreenode subnode jmetertreenode nextelement subnode isenabled testelement testelement subnode getuserobject myclass isinstance getname addfirst testplan testplan testplan testplan getarguments myclass isinstance addfirst private void place sampler http sampler base sampler test element sub configs j meter tree node my target try j meter tree model tree model gui package get instance get tree model boolean first in batch false long now system current time millis long deltat now last time if deltat sample gap if my target is leaf grouping mode grouping add separators add divider tree model my target if grouping mode grouping in controllers add simple controller tree model my target sampler get name first in batch true remember this was first in its batch if last time 0 deltat 0 decent value for timers last time now if grouping mode grouping store first only if first in batch return huh don t store this one if we re not storing subsequent samplers we ll need the first sampler to do all the work sampler set follow redirects true sampler set image parser true if grouping mode grouping in controllers find the last controller in the target to store the sampler there for int i my target get child count 1 i 0 i j meter tree node c j meter tree node my target get child at i if c get test element instanceof generic controller my target c break j meter tree node new node tree model add component sampler my target if first in batch if add assertions add assertion tree model new node add timers tree model new node deltat first in batch false for int i 0 sub configs null i sub configs length i if sub configs i instanceof header manager sub configs i set property test element gui class header panel tree model add component sub configs i new node catch illegal user action exception e j meter utils report error to user e get message placesampler httpsamplerbase testelement subconfigs jmetertreenode mytarget jmetertreemodel treemodel guipackage getinstance gettreemodel firstinbatch currenttimemillis lasttime samplegap mytarget isleaf groupingmode grouping_add_separators adddivider treemodel mytarget groupingmode grouping_in_controllers addsimplecontroller treemodel mytarget getname firstinbatch lasttime lasttime groupingmode grouping_store_first_only firstinbatch setfollowredirects setimageparser groupingmode grouping_in_controllers mytarget getchildcount jmetertreenode jmetertreenode mytarget getchildat gettestelement genericcontroller mytarget jmetertreenode newnode treemodel addcomponent mytarget firstinbatch addassertions addassertion treemodel newnode addtimers treemodel newnode firstinbatch subconfigs subconfigs subconfigs headermanager subconfigs setproperty testelement gui_class header_panel treemodel addcomponent subconfigs newnode illegaluseractionexception jmeterutils reporterrortouser getmessage remove from the sampler all values which match the one provided by the first configuration in the given collection which provides a value for that property param sampler sampler to remove values from param configurations config test elements in descending priority private void remove values from sampler http sampler base sampler collection configurations for property iterator props sampler property iterator props has next j meter property prop props next string name prop get name string value prop get string value there s a few properties which are excluded from this processing if name equals test element enabled name equals test element gui class name equals test element name name equals test element test class continue go on with next property for iterator configs configurations iterator configs has next config test element config config test element configs next string config value config get property as string name if config value null config value length 0 if config value equals value sampler set property name non nls 1 property was found in a config element whether or not it matched the value in the sampler we re done with this property don t look at lower priority configs break configtestelements removevaluesfromsampler httpsamplerbase propertyiterator propertyiterator hasnext jmeterproperty getname getstringvalue testelement testelement gui_class testelement testelement test_class hasnext configtestelement configtestelement configvalue getpropertyasstring configvalue configvalue configvalue setproperty private string generate match url http sampler base sampler string buffer buf new string buffer sampler get domain buf append non nls 1 buf append sampler get port buf append sampler get path if sampler get query string length 0 buf append non nls 1 buf append sampler get query string return buf to string generatematchurl httpsamplerbase stringbuffer stringbuffer getdomain getport getpath getquerystring getquerystring tostring private boolean matches patterns string url collection property patterns property iterator iter patterns iterator while iter has next string item iter next get string value pattern pattern null try pattern j meter utils get pattern cache get pattern item perl5 compiler read only mask perl5 compiler singleline mask if j meter utils get matcher matches url pattern return true catch malformed cache pattern exception e log warn skipped invalid pattern item e return false matchespatterns collectionproperty propertyiterator hasnext getstringvalue jmeterutils getpatterncache getpattern perl5compiler read_only_mask perl5compiler singleline_mask jmeterutils getmatcher malformedcachepatternexception scan all test elements passed in for values matching the value of any of the variables in any of the variable holding elements in the collection param sampler a test element to replace values on param configs more test elements to replace values on param variables collection of arguments to use to do the replacement ordered by ascending priority private void replace values test element sampler test element configs collection variables build the replacer from all the variables in the collection value replacer replacer new value replacer for iterator vars variables iterator vars has next final map map arguments vars next get arguments as map for iterator vals map values iterator vals has next final object next vals next if equals next drop any empty values bug 45199 vals remove replacer add variables map try replacer reverse replace sampler regex match for int i 0 i configs length i if configs i null replacer reverse replace configs i regex match catch invalid variable exception e log warn invalid variables included for replacement into recorded sample e testelement testelements replacevalues testelement testelement valuereplacer valuereplacer hasnext getargumentsasmap hasnext addvariables reversereplace regexmatch reversereplace regexmatch invalidvariableexception this will notify sample listeners directly within the proxy of the sampling that just occured so that we have a means to record the server s responses as we go param event sampling event to be delivered private void notify sample listeners sample event event j meter tree model tree model gui package get instance get tree model j meter tree node my node tree model get node of this enumeration kids my node children while kids has more elements j meter tree node sub node j meter tree node kids next element if sub node is enabled test element test element sub node get test element if test element instanceof sample listener sample listener test element sample occurred event notifysamplelisteners sampleevent jmetertreemodel treemodel guipackage getinstance gettreemodel jmetertreenode mynode treemodel getnodeof mynode hasmoreelements jmetertreenode subnode jmetertreenode nextelement subnode isenabled testelement testelement subnode gettestelement testelement samplelistener samplelistener testelement sampleoccurred this will notify test listeners directly within the proxy that the test here meaning the proxy recording has started private void notify test listeners of start j meter tree model tree model gui package get instance get tree model j meter tree node my node tree model get node of this enumeration kids my node children while kids has more elements j meter tree node sub node j meter tree node kids next element if sub node is enabled test element test element sub node get test element if test element instanceof test listener test listener test element test started notifytestlistenersofstart jmetertreemodel treemodel guipackage getinstance gettreemodel jmetertreenode mynode treemodel getnodeof mynode hasmoreelements jmetertreenode subnode jmetertreenode nextelement subnode isenabled testelement testelement subnode gettestelement testelement testlistener testlistener testelement teststarted this will notify test listeners directly within the proxy that the test here meaning the proxy recording has ended private void notify test listeners of end j meter tree model tree model gui package get instance get tree model j meter tree node my node tree model get node of this enumeration kids my node children while kids has more elements j meter tree node sub node j meter tree node kids next element if sub node is enabled test element test element sub node get test element if test element instanceof test listener test listener test element test ended notifytestlistenersofend jmetertreemodel treemodel guipackage getinstance gettreemodel jmetertreenode mynode treemodel getnodeof mynode hasmoreelements jmetertreenode subnode jmetertreenode nextelement subnode isenabled testelement testelement subnode gettestelement testelement testlistener testlistener testelement testended public boolean can remove return null server canremove public class j meter stop test exception extends runtime exception public j meter stop test exception super jmeterstoptestexception runtimeexception jmeterstoptestexception public j meter stop test exception string s super s jmeterstoptestexception private method method to invoke functor throw new illegal argument exception must provide at least one argument methodtoinvoke illegalargumentexception create a functor with the invokee and a method name the invokee will be used in all future invoke calls param invokee object on which to invoke the method param methodname method name public functor object invokee string methodname this null invokee methodname null null _invokee _methodname _invokee _methodname _invokee _methodname create a functor from class and method name this is useful for methods defined in interfaces the actual invokee must be provided in all invoke calls and must be an instance of the class param clazz class to be used param methodname method name public functor class clazz string methodname this clazz null methodname null null _clazz _methodname _clazz _methodname _clazz _methodname create a functor with the invokee method name and argument class types the invokee will be ignored in any invoke calls param invokee object on which to invoke the method param methodname method name param types public functor object invokee string methodname class types this null invokee methodname null types _invokee _methodname _types _invokee _methodname _types _invokee _methodname _types create a functor with the class method name and argument class types subsequent invoke calls must provide the appropriate ivokee object param clazz the class in which to find the method param methodname method name param types public functor class clazz string methodname class types this clazz null methodname null types _clazz _methodname _types _clazz _methodname _types _clazz _methodname _types create a functor with just the method name the invokee and any parameters must be provided in all invoke calls param methodname method name public functor string methodname this null null methodname null null _methodname _methodname _methodname create a functor with the method name and argument class types the invokee must be provided in all invoke calls param methodname method name param types parameter types public functor string methodname class types this null null methodname null types _methodname _types _methodname _types _methodname _types create a functor with an invokee method name and argument values the invokee will be ignored in any invoke calls param invokee object on which to invoke the method param methodname method name param args arguments to be passed to the method public functor object invokee string methodname object args this null invokee methodname args null _invokee _methodname _args _invokee _methodname _args _invokee _methodname _args create a functor from method name and arguments the class will be determined from the first invoke call all invoke calls must include a target object which must be of the same type as the initial invokee param methodname method name param args public functor string methodname object args this null null methodname args null _methodname _args _methodname _args _methodname _args create a functor from various different combinations of parameters param clazz class containing the method param invokee invokee to use for the method call param methodname the method name required param args arguments to be used param types types of arguments to be used throws illegal argument exception if method name is null both class and invokee are specified both arguments and types are specified private functor class clazz object invokee string methodname object args class types if methodname null throw new illegal argument exception methodname must not be null if clazz null invokee null throw new illegal argument exception cannot provide both class and object if args null types null throw new illegal argument exception cannot provide both arguments and argument types if class not provided default to invokee class else null this clazz clazz null clazz invokee null invokee get class null this invokee invokee this method name methodname this args args if types not provided default to argument types else null this types types null types args null gettypes args null _clazz _invokee _methodname _args _types illegalargumentexception methodname _clazz _invokee _methodname _args _types _methodname illegalargumentexception _clazz _invokee illegalargumentexception _args _types illegalargumentexception _clazz _clazz _invokee _invokee getclass _invokee methodname _methodname _args _types _types _args _gettypes _args private object do invoke class class object invokee object args class arg types get types args try method method do create method class arg types if method null final string message can t find method class get name method name types to string arg types log error message new throwable throw new j meter error message return method invoke invokee args catch exception e final string message trouble functing class get name method name invokee invokee e get message log warn message e throw new j meter error message e doinvoke _class _invokee _args argtypes gettypes _args docreatemethod _class argtypes _class getname methodname typestostring argtypes jmetererror _invokee _args _class getname methodname _invokee getmessage jmetererror invoke a functor which must have been created with either a class name or object return the object if any public object invoke if invokee null throw new illegal state exception cannot call invoke invokee not known if invokee was provided then clazz has been set up return do invoke clazz invokee get args illegalstateexception doinvoke getargs invoke the method on a given object param p invokee provides the object to call ignored if the class or object were provided to the constructor return the value public object invoke object p invokee return invoke p invokee get args p_invokee p_invokee p_invokee getargs invoke the method with the provided parameters the invokee must have been provided in the constructor param p args parameters for the method return the value public object invoke object p args if invokee null throw new illegal state exception invokee was not provided in constructor if invokee was provided then clazz has been set up return do invoke clazz invokee args null args p args p_args p_args illegalstateexception doinvoke p_args invoke the method on the invokee with the provided parameters the invokee must agree with the class if any provided at construction time if the invokee was provided at construction time then this invokee will be ignored if actual arguments were provided at construction time then arguments will be ignored public object invoke object p invokee object p args return do invoke clazz null clazz p invokee get class use constructor class if present invokee null invokee p invokee use invokee if provided args null args p args use argumenrs if provided p_invokee p_args doinvoke p_invokee getclass p_invokee p_args private synchronized method do create method class p class class p types if log is debug enabled log debug do create method using this to string class p class get name types arrays as list p types if method to invoke null try method to invoke p class get method method name p types catch exception e for int i 0 i p types length i class primitive get primitive p types i if primitive null method to invoke do create method p class get new array i primitive p types if method to invoke null return method to invoke class interfaces p types i get interfaces for int j 0 j interfaces length j method to invoke do create method p class get new array i interfaces j p types if method to invoke null return method to invoke class parent p types i get superclass if parent null method to invoke do create method p class get new array i parent p types if method to invoke null return method to invoke return method to invoke docreatemethod p_class p_types isdebugenabled docreatemethod tostring p_class getname aslist p_types methodtoinvoke methodtoinvoke p_class getmethod methodname p_types p_types getprimitive p_types methodtoinvoke docreatemethod p_class getnewarray p_types methodtoinvoke methodtoinvoke p_types getinterfaces methodtoinvoke docreatemethod p_class getnewarray p_types methodtoinvoke methodtoinvoke p_types getsuperclass methodtoinvoke docreatemethod p_class getnewarray p_types methodtoinvoke methodtoinvoke methodtoinvoke check if a read functor method is valid deprecated for use by unit test code only return true if method exists public boolean check method object invokee method m null try m do create method invokee get class get types args catch exception e ignored return null m checkmethod _invokee docreatemethod _invokee getclass gettypes check if a write functor method is valid deprecated for use by unit test code only return true if method exists public boolean check method object invokee class c method m null try m do create method invokee get class new class c catch exception e ignored return null m checkmethod _invokee docreatemethod _invokee getclass public string to string string buffer sb new string buffer 100 if clazz null sb append clazz get name if invokee null sb append sb append system identity hash code invokee sb append sb append method name types to string sb types return sb to string tostring stringbuffer stringbuffer getname identityhashcode methodname typestostring tostring private void types to string string buffer sb class types sb append if types null for int i 0 i types length i if i 0 sb append sb append types i get name sb append typestostring stringbuffer _types _types _types _types getname private string types to string class arg types string buffer sb new string buffer types to string sb arg types return sb to string typestostring argtypes stringbuffer stringbuffer typestostring argtypes tostring private class get primitive class t if t null return null if t equals integer class return int class else if t equals long class return long class else if t equals double class return double class else if t equals float class return float class else if t equals byte class return byte class else if t equals boolean class return boolean class else if t equals short class return short class else if t equals character class return char class return null getprimitive private class get new array int i class replacement class orig class new array new class orig length for int j 0 j new array length j if j i new array j replacement else new array j orig j return new array getnewarray newarray newarray newarray newarray newarray private class get types object args if types null return gettypes args return types gettypes _args _gettypes _args private static class gettypes object args class types if args null types new class args length for int i 0 i args length i types i args i get class else types new class 0 return types _gettypes _args _types _args _types _args _args _types _args getclass _types _types private object get args if args null args new object 0 return args getargs private transient set per thread pool set public data source element perthreadpoolset datasourceelement public void test ended synchronized this if excalibur source null excalibur source dispose excalibur source null if per thread pool set null in case iterator it per thread pool set iterator while it has next resource limiting jdbc data source dsc resource limiting jdbc data source it next log debug disposing pool dsc get instrumentable name system identity hash code dsc dsc dispose per thread pool set null testended excalibursource excalibursource excalibursource perthreadpoolset perthreadpoolset hasnext resourcelimitingjdbcdatasource resourcelimitingjdbcdatasource getinstrumentablename identityhashcode perthreadpoolset public void test ended string host test ended testended testended public void test iteration start loop iteration event event testiterationstart loopiterationevent public void test started this set running version true test bean helper prepare this j meter variables variables get thread context get variables string pool name get data source if variables get object pool name null log error jdbc data source already defined for pool name else string max pool get pool max per thread pool set collections synchronized set new hash set if max pool equals 0 i e if we want per thread pooling variables put object pool name new data source component impl pool will be created later else resource limiting jdbc data source src init pool max pool synchronized this excalibur source src variables put object pool name new data source component impl excalibur source teststarted setrunningversion testbeanhelper jmetervariables getthreadcontext getvariables poolname getdatasource getobject poolname poolname maxpool getpoolmax perthreadpoolset synchronizedset hashset maxpool putobject poolname datasourcecomponentimpl resourcelimitingjdbcdatasource initpool maxpool excalibursource putobject poolname datasourcecomponentimpl excalibursource public void test started string host test started teststarted teststarted public object clone data source element el data source element super clone el excalibur source excalibur source el per thread pool set per thread pool set return el datasourceelement datasourceelement excalibursource excalibursource perthreadpoolset perthreadpoolset public static connection get connection string pool name throws sql exception data source component pool data source component j meter context service get context get variables get object pool name if pool null throw new sql exception no pool found named pool name return pool get connection getconnection poolname sqlexception datasourcecomponent datasourcecomponent jmetercontextservice getcontext getvariables getobject poolname sqlexception poolname getconnection private resource limiting jdbc data source init pool string max pool resource limiting jdbc data source source null source new resource limiting jdbc data source default configuration config new default configuration rl jdbc non nls 1 if log is debug enabled string buffer sb new string buffer 40 sb append max pool sb append max pool sb append timeout sb append get timeout sb append trim int sb append get trim interval sb append auto commit sb append is autocommit log debug sb to string default configuration pool controller new default configuration pool controller non nls 1 pool controller set attribute max max pool non nls 1 pool controller set attribute max strict true non nls 1 non nls 2 pool controller set attribute blocking true non nls 1 non nls 2 pool controller set attribute timeout get timeout non nls 1 pool controller set attribute trim interval get trim interval non nls 1 config add child pool controller default configuration auto commit new default configuration auto commit non nls 1 auto commit set value string value of is autocommit config add child auto commit if log is debug enabled string buffer sb new string buffer 40 sb append keep alive sb append is keep alive sb append age sb append get connection age sb append check query sb append get check query log debug sb to string default configuration cfg keep alive new default configuration keep alive non nls 1 cfg keep alive set attribute disable string value of is keep alive non nls 1 cfg keep alive set attribute age get connection age non nls 1 cfg keep alive set value get check query pool controller add child cfg keep alive string username get username if log is debug enabled string buffer sb new string buffer 40 sb append driver sb append get driver sb append db url sb append get db url sb append user sb append username log debug sb to string default configuration cfg driver new default configuration driver non nls 1 cfg driver set value get driver config add child cfg driver default configuration cfg db url new default configuration dburl non nls 1 cfg db url set value get db url config add child cfg db url if username length 0 default configuration cfg username new default configuration user non nls 1 cfg username set value username config add child cfg username default configuration cfg password new default configuration password non nls 1 cfg password set value get password config add child cfg password log is required to ensure errors are available source enable logging new log kit logger log try source configure config source set instrumentable name get data source catch configuration exception e log error could not configure datasource for pool get data source e return source resourcelimitingjdbcdatasource initpool maxpool resourcelimitingjdbcdatasource resourcelimitingjdbcdatasource defaultconfiguration defaultconfiguration isdebugenabled stringbuffer stringbuffer maxpool maxpool gettimeout trimint gettriminterval isautocommit tostring defaultconfiguration poolcontroller defaultconfiguration poolcontroller setattribute maxpool poolcontroller setattribute poolcontroller setattribute poolcontroller setattribute gettimeout poolcontroller setattribute gettriminterval addchild poolcontroller defaultconfiguration autocommit defaultconfiguration autocommit setvalue valueof isautocommit addchild autocommit isdebugenabled stringbuffer stringbuffer keepalive iskeepalive getconnectionage checkquery getcheckquery tostring defaultconfiguration cfgkeepalive defaultconfiguration cfgkeepalive setattribute valueof iskeepalive cfgkeepalive setattribute getconnectionage cfgkeepalive setvalue getcheckquery poolcontroller addchild cfgkeepalive _username getusername isdebugenabled stringbuffer stringbuffer getdriver dburl getdburl _username tostring defaultconfiguration cfgdriver defaultconfiguration cfgdriver setvalue getdriver addchild cfgdriver defaultconfiguration cfgdburl defaultconfiguration cfgdburl setvalue getdburl addchild cfgdburl _username defaultconfiguration cfgusername defaultconfiguration cfgusername setvalue _username addchild cfgusername defaultconfiguration cfgpassword defaultconfiguration cfgpassword setvalue getpassword addchild cfgpassword enablelogging logkitlogger setinstrumentablename getdatasource configurationexception getdatasource used to hold per thread singleton connection pools private static final thread local per thread pool map new thread local protected synchronized object initial value return new hash map threadlocal perthreadpoolmap threadlocal initialvalue hashmap private final resource limiting jdbc data source shareddsc data source component impl shareddsc null resourcelimitingjdbcdatasource datasourcecomponentimpl data source component impl resource limiting jdbc data source p dsc shareddsc p dsc datasourcecomponentimpl resourcelimitingjdbcdatasource p_dsc p_dsc public connection get connection throws sql exception connection conn null resource limiting jdbc data source dsc null if shareddsc null i e shared pool dsc shareddsc else map pool map map per thread pool map get dsc resource limiting jdbc data source pool map get get data source if dsc null dsc init pool 1 pool map put get data source dsc log debug storing pool dsc get instrumentable name system identity hash code dsc per thread pool set add dsc if dsc null conn dsc get connection return conn getconnection sqlexception resourcelimitingjdbcdatasource poolmap perthreadpoolmap resourcelimitingjdbcdatasource poolmap getdatasource initpool poolmap getdatasource getinstrumentablename identityhashcode perthreadpoolset getconnection public void configure configuration arg0 throws configuration exception configurationexception public void add config element config element config addconfigelement configelement public boolean expects modification return false expectsmodification return returns the check query public string get check query return check query checkquery getcheckquery checkquery param check query the check query to set public void set check query string check query this check query check query checkquery checkquery setcheckquery checkquery checkquery checkquery return returns the connection age public string get connection age return connection age connectionage getconnectionage connectionage param connection age the connection age to set public void set connection age string connection age this connection age connection age connectionage connectionage setconnectionage connectionage connectionage connectionage return returns the poolname public string get data source return data source getdatasource datasource param data source the poolname to set public void set data source string data source this data source data source datasource setdatasource datasource datasource datasource return returns the db url public string get db url return db url dburl getdburl dburl param db url the db url to set public void set db url string db url this db url db url dburl dburl setdburl dburl dburl dburl return returns the driver public string get driver return driver getdriver param driver the driver to set public void set driver string driver this driver driver setdriver return returns the password public string get password return password getpassword param password the password to set public void set password string password this password password setpassword return returns the pool max public string get pool max return pool max poolmax getpoolmax poolmax param pool max the pool max to set public void set pool max string pool max this pool max pool max poolmax poolmax setpoolmax poolmax poolmax poolmax return returns the timeout public string get timeout return timeout gettimeout param timeout the timeout to set public void set timeout string timeout this timeout timeout settimeout return returns the trim interval public string get trim interval return trim interval triminterval gettriminterval triminterval param trim interval the trim interval to set public void set trim interval string trim interval this trim interval trim interval triminterval triminterval settriminterval triminterval triminterval triminterval return returns the username public string get username return username getusername param username the username to set public void set username string username this username username setusername return returns the autocommit public boolean is autocommit return autocommit isautocommit param autocommit the autocommit to set public void set autocommit boolean autocommit this autocommit autocommit setautocommit return returns the keep alive public boolean is keep alive return keep alive keepalive iskeepalive keepalive param keep alive the keep alive to set public void set keep alive boolean keep alive this keep alive keep alive keepalive keepalive setkeepalive keepalive keepalive keepalive constructs a code table cell editor code that uses a text field public text area table cell editor editor component new j text area editor component set rows 3 this click count to start 2 delegate new editor delegate public void set value object value editor component set text value null value to string public object get cell editor value return editor component get text editor component add focus listener delegate tablecelleditor textareatablecelleditor editorcomponent jtextarea editorcomponent setrows clickcounttostart editordelegate setvalue editorcomponent settext tostring getcelleditorvalue editorcomponent gettext editorcomponent addfocuslistener this click count to start 2 delegate new editor delegate public void set value object value editor component set text value null value to string clickcounttostart editordelegate setvalue editorcomponent settext tostring public object get cell editor value return editor component get text getcelleditorvalue editorcomponent gettext returns a reference to the editor component return the editor code component code public component get component return editor component getcomponent editorcomponent specifies the number of clicks needed to start editing param count an int specifying the number of clicks needed to start editing see get click count to start public void set click count to start int count click count to start count getclickcounttostart setclickcounttostart clickcounttostart returns the number of clicks needed to start editing return the number of clicks needed to start editing public int get click count to start return click count to start getclickcounttostart clickcounttostart forwards the message from the code cell editor code to the code delegate code see editor delegate get cell editor value public object get cell editor value return delegate get cell editor value celleditor editordelegate getcelleditorvalue getcelleditorvalue getcelleditorvalue forwards the message from the code cell editor code to the code delegate code see editor delegate is cell editable event object public boolean is cell editable event object an event return delegate is cell editable an event celleditor editordelegate iscelleditable eventobject iscelleditable eventobject anevent iscelleditable anevent forwards the message from the code cell editor code to the code delegate code see editor delegate should select cell event object public boolean should select cell event object an event return delegate should select cell an event celleditor editordelegate shouldselectcell eventobject shouldselectcell eventobject anevent shouldselectcell anevent forwards the message from the code cell editor code to the code delegate code see editor delegate stop cell editing public boolean stop cell editing return delegate stop cell editing celleditor editordelegate stopcellediting stopcellediting stopcellediting forwards the message from the code cell editor code to the code delegate code see editor delegate cancel cell editing public void cancel cell editing delegate cancel cell editing celleditor editordelegate cancelcellediting cancelcellediting cancelcellediting implements the code tree cell editor code interface public component get tree cell editor component j tree tree object value boolean is selected boolean expanded boolean leaf int row string string value tree convert value to text value is selected expanded leaf row false delegate set value string value return new j scroll pane editor component treecelleditor gettreecelleditorcomponent jtree isselected stringvalue convertvaluetotext isselected setvalue stringvalue jscrollpane editorcomponent implements the code table cell editor code interface public component get table cell editor component j table table object value boolean is selected int row int column delegate set value value return new j scroll pane editor component tablecelleditor gettablecelleditorcomponent jtable isselected setvalue jscrollpane editorcomponent returns the value of this cell return the value of this cell public object get cell editor value return value getcelleditorvalue sets the value of this cell param value the new value of this cell public void set value object value this value value setvalue returns true if code an event code is b not b a code mouse event code otherwise it returns true if the necessary number of clicks have occurred and returns false otherwise param an event the event return true if cell is ready for editing false otherwise see set click count to start int see should select cell public boolean is cell editable event object an event if an event instanceof mouse event return mouse event an event get click count click count to start return true anevent mouseevent anevent setclickcounttostart shouldselectcell iscelleditable eventobject anevent anevent mouseevent mouseevent anevent getclickcount clickcounttostart returns true to indicate that the editing cell may be selected param an event the event return true see is cell editable public boolean should select cell event object an event return true anevent iscelleditable shouldselectcell eventobject anevent returns true to indicate that editing has begun param an event the event public boolean start cell editing event object an event return true anevent startcellediting eventobject anevent stops editing and returns true to indicate that editing has stopped this method calls code fire editing stopped code return true public boolean stop cell editing fire editing stopped return true fireeditingstopped stopcellediting fireeditingstopped cancels editing this method calls code fire editing canceled code public void cancel cell editing fire editing canceled fireeditingcanceled cancelcellediting fireeditingcanceled when an action is performed editing is ended param e the action event see stop cell editing public void action performed action event e text area table cell editor this stop cell editing stopcellediting actionperformed actionevent textareatablecelleditor stopcellediting when an item s state changes editing is ended param e the action event see stop cell editing public void item state changed item event e text area table cell editor this stop cell editing stopcellediting itemstatechanged itemevent textareatablecelleditor stopcellediting public void focus lost focus event ev text area table cell editor this stop cell editing focuslost focusevent textareatablecelleditor stopcellediting public void focus gained focus event ev focusgained focusevent constructs a mailer model public mailer model super set property success limit key j meter utils get prop default mailer successlimit default limit non nls 1 set property failure limit key j meter utils get prop default mailer failurelimit default limit non nls 1 mailermodel mailermodel setproperty success_limit_key jmeterutils getpropdefault default_limit setproperty failure_limit_key jmeterutils getpropdefault default_limit public void add change listener change listener list change listener list addchangelistener changelistener changelistener public object clone mailer model m mailer model super clone m change listener change listener return m mailermodel mailermodel changelistener changelistener public void notify change listeners if change listener null change listener state changed new change event this notifychangelisteners changelistener changelistener statechanged changeevent gets a vector of string objects each string is one mail address of the addresses string set by code set to address str code the addresses must be seperated by commas only string objects containing a are added to the returned vector return a vector of string objects wherein each string represents a mail address public vector get address vector string addressees get to address vector address vector new vector if addressees null string tokenizer next new string tokenizer addressees non nls 1 while next has more tokens string the token next next token trim if the token index of 0 non nls 1 address vector add element the token else log warn ignored unexpected e mail address the token return address vector settoaddress getaddressvector gettoaddress addressvector stringtokenizer stringtokenizer hasmoretokens thetoken nexttoken thetoken indexof addressvector addelement thetoken thetoken addressvector adds a sample result if sample result represents a change concerning the failure success of the sampling a message might be send to the addressies according to the settings of code success count code and code failure count code param sample the sample result encapsulating informations about the last sample public synchronized void add sample result sample 1 is the code for a failed sample if sample is successful failure count success count 0 else success count if failure count get failure limit site down failure msg sent send the mail vector address vector get address vector if address vector size 0 try send mail get from address address vector get failure subject url failed sample get sample label get smtp host catch exception e log error problem sending mail e site down true failure msg sent true success count 0 success msg sent false if site down sample get time 1 success msg sent send the mail if success count get success limit vector address vector get address vector try send mail get from address address vector get success subject url restarted sample get sample label get smtp host catch exception e log error problem sending mail e site down false success msg sent true failure count 0 failure msg sent false if success msg sent failure msg sent clear notify change listeners sampleresult sampleresult successcount failurecount sampleresult sampleresult issuccessful failurecount successcount successcount failurecount getfailurelimit sitedown failuremsgsent addressvector getaddressvector addressvector sendmail getfromaddress addressvector getfailuresubject getsamplelabel getsmtphost sitedown failuremsgsent successcount successmsgsent sitedown gettime successmsgsent successcount getsuccesslimit addressvector getaddressvector sendmail getfromaddress addressvector getsuccesssubject getsamplelabel getsmtphost sitedown successmsgsent failurecount failuremsgsent successmsgsent failuremsgsent notifychangelisteners resets the state of this object to its default but this method does not reset any mail specific attributes like sender mail subject since they are independent of the sampling public synchronized void clear todo should this be clear data failure count 0 success count 0 site down false success msg sent false failure msg sent false notify change listeners cleardata failurecount successcount sitedown successmsgsent failuremsgsent notifychangelisteners returns a string representation of this object returns always e mail notification might be enhanced in future versions to return some kind of string representation of the mail parameters like sender addressies smtp host return a string representation of this object public string to string return e mail notification smtphost tostring sends a mail with the given parameters using smtp param from the sender of the mail as shown in the mail client param v emails all receivers of the mail the receivers are seperated by commas param subject the subject of the mail param att text the message body param smtp host the smtp server used to send the mail public synchronized void send mail string from vector v emails string subject string att text string smtp host throws address exception messaging exception string host smtp host boolean debug boolean value of host boolean value inet address remote inet address get by name host internet address address new internet address v emails size for int k 0 k v emails size k address k new internet address v emails element at k to string create some properties and get the default session properties props new properties props put mail smtp host host session session session get default instance props null n b properties are only used when the default session is first created so check if the mail host needs to be reset props session get properties if host equals ignore case props get property mail smtp host props set property mail smtp host host session set debug debug create a message message msg new mime message session msg set from new internet address from msg set recipients message recipient type to address msg set subject subject msg set text att text transport send msg vemails atttext smtphost sendmail vemails atttext smtphost addressexception messagingexception smtphost valueof booleanvalue inetaddress inetaddress getbyname internetaddress internetaddress vemails vemails internetaddress vemails elementat tostring mail_smtp_host getdefaultinstance getproperties equalsignorecase getproperty mail_smtp_host setproperty mail_smtp_host setdebug mimemessage setfrom internetaddress setrecipients recipienttype setsubject settext atttext public synchronized void send test mail throws address exception messaging exception string to get to address string from get from address string subject testing mail addresses string smtp host get smtp host string att text j meter testmail n to to n from from n via smtp host n fail subject get failure subject n success subject get success subject log info att text send mail from get address vector subject att text smtp host log info test mail sent successfully sendtestmail addressexception messagingexception gettoaddress getfromaddress smtphost getsmtphost atttext jmeter smtphost getfailuresubject getsuccesssubject atttext sendmail getaddressvector atttext smtphost public void set to address string str set property to key str settoaddress setproperty to_key public void set from address string str set property from key str setfromaddress setproperty from_key public void set smtp host string str set property host key str setsmtphost setproperty host_key public void set failure subject string str set property failure subject str setfailuresubject setproperty failure_subject public void set success subject string str set property success subject str setsuccesssubject setproperty success_subject public void set success limit string limit set property success limit key limit setsuccesslimit setproperty success_limit_key public void set failure limit string limit set property failure limit key limit setfailurelimit setproperty failure_limit_key public string get to address return get property as string to key gettoaddress getpropertyasstring to_key public string get from address return get property as string from key getfromaddress getpropertyasstring from_key public string get smtp host return get property as string host key getsmtphost getpropertyasstring host_key public string get failure subject return get property as string failure subject getfailuresubject getpropertyasstring failure_subject public string get success subject return get property as string success subject getsuccesssubject getpropertyasstring success_subject public long get success limit return get property as long success limit key getsuccesslimit getpropertyaslong success_limit_key public long get success count return success count getsuccesscount successcount public long get failure limit return get property as long failure limit key getfailurelimit getpropertyaslong failure_limit_key public long get failure count return this failure count getfailurecount failurecount the constructor public xml schema assertiongui init xmlschemaassertiongui returns the label to be shown within the j tree component public string get label resource return xmlschema assertion title non nls 1 jtree getlabelresource xmlschema_assertion_title create test element public test element create test element log debug xml schema assertion gui create test element called xml schema assertion el new xml schema assertion modify test element el return el testelement createtestelement xmlschemaassertiongui createtestelement xmlschemaassertion xmlschemaassertion modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element in element log debug xml schema assertion gui modify test element called configure test element in element xml schema assertion in element set xsd file name xml schema get text testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement inelement xmlschemaassertiongui modifytestelement configuretestelement inelement xmlschemaassertion inelement setxsdfilename xmlschema gettext implements j metergui component clear gui public void clear gui super clear gui xml schema set text non nls 1 jmeterguicomponent cleargui cleargui cleargui xmlschema settext configures the gui from the associated test element param el the test element should be xml schema assertion public void configure test element el super configure el xml schema assertion assertion xml schema assertion el xml schema set text assertion get xsd file name xmlschemaassertion testelement xmlschemaassertion xmlschemaassertion xmlschema settext getxsdfilename inits the gui private void init set layout new border layout 0 10 set border make border add make title panel border layout north j panel main panel new j panel new border layout user input vertical panel assertion panel new vertical panel assertion panel set border border factory create titled border border factory create etched border xml schema doctype horizontal panel xml schema panel new horizontal panel xml schema panel add new j label j meter utils get res string xmlschema assertion label non nls 1 xml schema new j text field 26 xml schema panel add xml schema assertion panel add xml schema panel main panel add assertion panel border layout north add main panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout jpanel mainpanel jpanel borderlayout user_input verticalpanel assertionpanel verticalpanel assertionpanel setborder borderfactory createtitledborder borderfactory createetchedborder horizontalpanel xmlschemapanel horizontalpanel xmlschemapanel jlabel jmeterutils getresstring xmlschema_assertion_label xmlschema jtextfield xmlschemapanel xmlschema assertionpanel xmlschemapanel mainpanel assertionpanel borderlayout mainpanel borderlayout private static logging manager log manager null private logging manager loggingmanager logmanager loggingmanager public static synchronized logging manager get log manager return log manager loggingmanager getlogmanager logmanager initialise the logging system from the jmeter properties logkit loggers inherit from their parents normally the jmeter properties file defines a single log file so set this as the default from log file default jmeter log the default priority is set from log level with a default of info public static void initialize logging properties properties synchronized logging manager class if log manager null log manager new logging manager set format properties set the top level defaults set target make writer properties get property log file jmeter log log file non nls 1 set priority properties get property log priority info set logging levels properties now set the individual categories if any set config properties further configuration log_file log_level initializelogging loggingmanager logmanager logmanager loggingmanager setformat settarget makewriter getproperty log_file log_file non_nls setpriority getproperty log_priority setlogginglevels setconfig private static void set format properties properties string pattern default pattern string type properties get property log format type non nls 1 if type length 0 pattern properties get property log format default pattern non nls 1 else if type equals ignore case thread suffix non nls 1 pattern pattern thread suffix else if type equals ignore case thread prefix non nls 1 pattern pattern thread prefix else pattern default pattern format new pattern formatter pattern n non nls 1 setformat default_pattern getproperty log_format_type non_nls getproperty log_format default_pattern non_nls equalsignorecase thread_suffix non_nls pattern_thread_suffix equalsignorecase thread_prefix non_nls pattern_thread_prefix default_pattern patternformatter non_nls private static void set config properties p string cfg p get property log config non nls 1 if cfg null return make sure same hierarchy is used hierarchy hier hierarchy get default hierarchy log kit logger manager manager new log kit logger manager null hier null null default configuration builder builder new default configuration builder try configuration c builder build from file cfg context ctx new default context manager contextualize ctx manager configure c catch illegal argument exception e this happens if the default log target id ref specifies a non existent target system out println error processing logging config cfg system out println e to string catch null pointer exception e this can happen if a log target id ref specifies a non existent target system out println error processing logging config cfg system out println perhaps a log target is missing catch configuration exception e system out println error processing logging config cfg system out println e to string catch sax exception e system out println error processing logging config cfg system out println e to string catch io exception e system out println error processing logging config cfg system out println e to string catch context exception e system out println error processing logging config cfg system out println e to string setconfig getproperty log_config non_nls getdefaulthierarchy logkitloggermanager logkitloggermanager defaultconfigurationbuilder defaultconfigurationbuilder buildfromfile defaultcontext illegalargumentexception tostring nullpointerexception configurationexception tostring saxexception tostring ioexception tostring contextexception tostring private static pattern formatter get format if format null format new pattern formatter default pattern n non nls 1 return format patternformatter getformat patternformatter default_pattern non_nls private static writer make writer string log file string prop name if the name contains at least one set of paired single quotes reformat using date format final int length log file split 1 length if length 1 length 2 1 try simple date format df new simple date format log file log file df format new date catch exception ignored writer wt is writer system out false try wt new file writer log file catch exception e system out println prop name log file e to string system out println prop name system out is writer system out true wt new print writer system out return wt makewriter logfile propname dateformat logfile simpledateformat simpledateformat logfile logfile iswritersystemout filewriter logfile propname logfile tostring propname iswritersystemout printwriter handle log priority category priority and log file category file name properties if the prefix is detected then remove it to get the category public static void set logging levels properties app properties iterator props app properties key set iterator while props has next string prop string props next if prop starts with log priority non nls 1 don t match the empty category string category prop substring log priority length 1 set priority app properties get property prop category if prop starts with log file non nls 1 string category prop substring log file length 1 string file app properties get property prop set target new writer target make writer file prop get format category log_priority log_file file_name setlogginglevels appproperties appproperties keyset hasnext startswith log_priority non_nls log_priority setpriority appproperties getproperty startswith log_file non_nls log_file appproperties getproperty settarget writertarget makewriter getformat private static string get caller class name string name class context get caller class name at 3 return name getcallerclassname classcontext getcallerclassnameat removes the standard prefix i e org apache param name from which to remove the prefix return the name with the prefix removed public static string remove prefix string name if name starts with package prefix remove the package prefix name name substring package prefix length return name removeprefix startswith package_prefix package_prefix get the logger for a class no argument needed because the calling class name is derived automatically from the call stack return logger public static logger get logger for class string class name get caller class name return hierarchy get default hierarchy get logger for remove prefix class name getloggerforclass classname getcallerclassname getdefaulthierarchy getloggerfor removeprefix classname get the logger for a class param category the full name of the logger category return logger public static logger get logger for string category return hierarchy get default hierarchy get logger for category getloggerfor getdefaulthierarchy getloggerfor get the logger for a class param category the full name of the logger category this will have the prefix removed return logger public static logger get logger for short name string category return hierarchy get default hierarchy get logger for remove prefix category getloggerforshortname getdefaulthierarchy getloggerfor removeprefix set the logging priority for a category param priority string containing the priority name e g info warn debug fatal error param category string containing the category public static void set priority string priority string category set priority priority get priority for name priority category fatal_error setpriority setpriority getpriorityforname set the logging priority for a category param priority priority e g debug info param full name e g org apache jmeter etc will have the prefix removed public static void set priority full name string priority string full name set priority priority get priority for name priority remove prefix full name fullname setpriorityfullname fullname setpriority getpriorityforname removeprefix fullname set the logging priority for a category param priority e g priority debug param category string containing the category public static void set priority priority priority string category hierarchy get default hierarchy get logger for category set priority priority setpriority getdefaulthierarchy getloggerfor setpriority public static void set priority string p set priority priority get priority for name p setpriority setpriority getpriorityforname set the default logging priority param priority e g priority debug public static void set priority priority priority hierarchy get default hierarchy set default priority priority setpriority getdefaulthierarchy setdefaultpriority set the logging target for a category param target the log target param category the category name public static void set target log target target string category logger logger hierarchy get default hierarchy get logger for category logger set log targets new log target target logtarget settarget logtarget getdefaulthierarchy getloggerfor setlogtargets logtarget sets the default log target from the parameter the existing target is first closed if necessary param target file writer public static synchronized void set target writer target file if target null target get target target file get format is target system out is writer system out else if is target system out target instanceof writer target writer target target close target get target target file get format is target system out is writer system out hierarchy get default hierarchy set default log target target targetfile settarget targetfile gettarget targetfile getformat istargetsystemout iswritersystemout istargetsystemout writertarget writertarget gettarget targetfile getformat istargetsystemout iswritersystemout getdefaulthierarchy setdefaultlogtarget private static log target get target writer target file pattern formatter fmt return new writer target target file fmt logtarget gettarget targetfile patternformatter writertarget targetfile public abstract class abstract post processor gui extends abstractj meter gui component public j popup menu create popup menu return menu factory get default extractor menu abstractpostprocessorgui abstractjmeterguicomponent jpopupmenu createpopupmenu menufactory getdefaultextractormenu public collection get menu categories return arrays as list new string menu factory post processors getmenucategories aslist menufactory post_processors private receiver queue connection factory factory queue receive queue string principal string credentials throws jms exception if null principal null credentials log info creating receiver with authorisation credentials conn factory create queue connection principal credentials else log info creating receiver without authorisation credentials conn factory create queue connection session conn create queue session false session auto acknowledge consumer session create receiver receive queue log debug receiver ctor starting connection now conn start log info receiver ctor connection to messaging system established queueconnectionfactory receivequeue jmsexception createqueueconnection createqueueconnection createqueuesession auto_acknowledge createreceiver receivequeue public static receiver create receiver queue connection factory factory queue receive queue string principal string credentials throws jms exception receiver receiver new receiver factory receive queue principal credentials thread thread new thread receiver thread start return receiver createreceiver queueconnectionfactory receivequeue jmsexception receivequeue public void run activate message reply while is active reply null try reply consumer receive 5000 if reply null if log is debug enabled log debug received message correlation id reply getjms correlationid if reply getjms correlationid null log warn received message with correlation id null discarding message else message admin get admin put reply reply getjms messageid reply catch jms exception e1 log error error handling receive e1 not active anymore if consumer null try consumer close catch jms exception e log error error closing connection e session and conn cannot be null or ctor would have caused npe try session close catch jms exception e log error error closing session e try conn close catch jms exception e log error error closing connection e isactive isdebugenabled getjmscorrelationid getjmscorrelationid messageadmin getadmin putreply getjmsmessageid jmsexception jmsexception jmsexception jmsexception public synchronized void activate active true public synchronized void deactivate active false private synchronized boolean is active return active isactive public class bsf pre processor bean info extends bsf bean info support public bsf pre processor bean info super bsf pre processor class bsfpreprocessorbeaninfo bsfbeaninfosupport bsfpreprocessorbeaninfo bsfpreprocessor constructor for the file panel object public file panel title non nls 1 init filepanel filepanel public file panel string title this title title init filepanel public file panel string title string filetype this title this filetype filetype filepanel constructor for the file panel object public file panel change listener l string title this title title init listeners add l filepanel filepanel changelistener public void add change listener change listener l listeners add l addchangelistener changelistener private void init set border border factory create titled border title add label add box create horizontal strut 5 add filename add box create horizontal strut 5 filename add action listener this add browse browse set action command action browse browse add action listener this setborder borderfactory createtitledborder createhorizontalstrut createhorizontalstrut addactionlistener setactioncommand action_browse addactionlistener public void clear gui filename set text non nls 1 cleargui settext if the gui needs to enable disable the file panel call the method param enable public void enable file boolean enable browse set enabled enable filename set enabled enable filepanel enablefile setenabled setenabled gets the filename attribute of the file panel object return the filename value public string get filename return filename get text filepanel getfilename gettext sets the filename attribute of the file panel object param f the new filename value public void set filename string f filename set text f filepanel setfilename settext private void fire file changed iterator iter listeners iterator while iter has next change listener iter next state changed new change event this firefilechanged hasnext changelistener statechanged changeevent public void action performed action event e if e get action command equals action browse j file chooser chooser if filetype null chooser file dialoger prompt to open file else chooser file dialoger prompt to open file new string filetype if chooser null chooser get selected file null filename set text chooser get selected file get path fire file changed else fire file changed actionperformed actionevent getactioncommand action_browse jfilechooser filedialoger prompttoopenfile filedialoger prompttoopenfile getselectedfile settext getselectedfile getpath firefilechanged firefilechanged public class illegal user action exception extends exception deprecated use illegal user action exception string public illegal user action exception super illegaluseractionexception illegaluseractionexception illegaluseractionexception public illegal user action exception string name super name illegaluseractionexception public axis graph super axisgraph param layout public axis graph layout manager layout super layout axisgraph layoutmanager param layout param is double buffered public axis graph layout manager layout boolean is double buffered super layout is double buffered isdoublebuffered axisgraph layoutmanager isdoublebuffered isdoublebuffered public void set data double data this data data setdata public void set title string title this title title settitle public void set max length int max length this max length max length setmaxlength maxlength maxlength maxlength public void setx axis title string title this x axis title title setxaxistitle xaxistitle public void sety axis title string title this y axis title title setyaxistitle yaxistitle public void setx axis labels string labels this x axis labels labels setxaxislabels xaxislabels public void sety axis labels string label this y axis label label setyaxislabels yaxislabel public void set width int w this width w setwidth public void set height int h this height h setheight public void paint component graphics g if data null this title null this x axis labels null this x axis title null this y axis label null this y axis title null draw sample this title this max length this x axis labels this x axis title this y axis title this data this width this height g paintcomponent xaxislabels xaxistitle yaxislabel yaxistitle drawsample maxlength xaxislabels xaxistitle yaxistitle private double find max double data double max 0 max data 0 0 for int i 0 i data length i for int j 0 j data i length j if data i j max max data i j return max findmax _data _data _data _data _data _data private string squeeze string input int maxlength if input length maxlength string output input substring 0 maxlength ellipsis len ellipsis return output return input _maxlength _maxlength _maxlength ellipsis_len private void draw sample string title int maxlength string xaxislabels string xaxistitle string yaxistitle double data int width int height graphics g double max find max data try these controls are already done in stat graph visualizer if width 0 width 450 if height 0 height 250 if maxlength 3 maxlength 3 if the title of graph is empty we can assume some default if title length 0 title graph if the labels are too long they ll be squeezed to make the chart viewable for int i 0 i xaxislabels length i string label xaxislabels i xaxislabels i squeeze label maxlength this set preferred size new dimension width height data series data series new data series xaxislabels xaxistitle yaxistitle title string legend labels y axis label paint paints new paint color yellow bar chart properties bar chart properties new bar chart properties value label renderer value label renderer new value label renderer false false true 0 value label renderer set value label position value label position at top value label renderer use vertical labels true bar chart properties add post render event listener value label renderer axis chart data set axis chart data set new axis chart data set data legend labels paints chart type bar bar chart properties data series addi axis plot data set axis chart data set chart properties chart properties new chart properties label axis properties xaxis new label axis properties data axis properties yaxis new data axis properties try big decimal round new big decimal max 1000d round round set scale 0 big decimal round up double top value round double value 1000 yaxis set user defined scale 0 500 yaxis set num items int top value 500 1 yaxis set show grid lines 1 catch property exception e log warn e axis properties axis properties new axis properties xaxis yaxis axis properties setx axis labels are vertical true legend properties legend properties new legend properties axis chart axis chart new axis chart data series chart properties axis properties legend properties width height axis chart set graphics2d graphics2d g axis chart render catch chart data exception e log warn e catch property exception e log warn e drawsample _title _maxlength _xaxislabels _xaxistitle _yaxistitle _data _width _height findmax _data statgraphvisualizer _width _width _height _height _maxlength _maxlength _title _title _xaxislabels _xaxislabels _xaxislabels _maxlength setpreferredsize _width _height dataseries dataseries dataseries _xaxislabels _xaxistitle _yaxistitle _title legendlabels yaxislabel barchartproperties barchartproperties barchartproperties valuelabelrenderer valuelabelrenderer valuelabelrenderer valuelabelrenderer setvaluelabelposition valuelabelposition at_top valuelabelrenderer useverticallabels barchartproperties addpostrendereventlistener valuelabelrenderer axischartdataset axischartdataset axischartdataset _data legendlabels charttype barchartproperties dataseries addiaxisplotdataset axischartdataset chartproperties chartproperties chartproperties labelaxisproperties labelaxisproperties dataaxisproperties dataaxisproperties bigdecimal bigdecimal setscale bigdecimal round_up topvalue doublevalue setuserdefinedscale setnumitems topvalue setshowgridlines propertyexception axisproperties axisproperties axisproperties axisproperties setxaxislabelsarevertical legendproperties legendproperties legendproperties axischart axischart axischart dataseries chartproperties axisproperties legendproperties _width _height axischart setgraphics2d axischart chartdataexception propertyexception constructor for the graph object public distribution graph init distributiongraph constructor for the graph object public distribution graph sampling stat calculator model this set model model distributiongraph samplingstatcalculator setmodel private void init called from ctor so must not be overridable repaint gets the scrollable tracks viewport width attribute of the graph object return the scrollable tracks viewport width value public boolean get scrollable tracks viewport width return true scrollabletracksviewportwidth scrollabletracksviewportwidth getscrollabletracksviewportwidth gets the scrollable tracks viewport height attribute of the graph object return the scrollable tracks viewport height value public boolean get scrollable tracks viewport height return true scrollabletracksviewportheight scrollabletracksviewportheight getscrollabletracksviewportheight sets the model attribute of the graph object private void set model object model this model sampling stat calculator model repaint setmodel samplingstatcalculator gets the preferred scrollable viewport size attribute of the graph object return the preferred scrollable viewport size value public dimension get preferred scrollable viewport size return this get preferred size preferredscrollableviewportsize preferredscrollableviewportsize getpreferredscrollableviewportsize getpreferredsize gets the scrollable unit increment attribute of the graph object return the scrollable unit increment value public int get scrollable unit increment rectangle visible rect int orientation int direction return 5 scrollableunitincrement scrollableunitincrement getscrollableunitincrement visiblerect gets the scrollable block increment attribute of the graph object return the scrollable block increment value public int get scrollable block increment rectangle visible rect int orientation int direction return int visible rect width 9 scrollableblockincrement scrollableblockincrement getscrollableblockincrement visiblerect visiblerect clears this graph public void clear data model clear cleardata method is responsible for calling draw sample and updating the graph public void paint component graphics g super paint component g final sampling stat calculator m this model synchronized m draw sample m g drawsample paintcomponent paintcomponent samplingstatcalculator drawsample private void draw sample sampling stat calculator p model graphics g int width get width double height get height 1 0 first lets draw the grid for int y 0 y 4 y int q1 int height height 0 25 y g set color color light gray g draw line xborder q1 width q1 g set color color black g draw string string value of 25 y 0 q1 g set color color black draw the x axis g draw line xborder int height width int height draw the y axis g draw line xborder 0 xborder int height the test plan has to have more than 200 samples for it to generate half way decent distribution graph the larger the sample the better the results if p model null p model get count 50 now draw the bar chart number ninety p model get percent point 0 90 number fifty p model get percent point 0 50 int total p model get count collection values p model get distribution values object objval new object values size objval values to array objval we sort the objects arrays sort objval new number comparator int len objval length for int count 0 count len count calculate the height number num number objval count double iper double num 1 int value double total double iheight height iper if the height is less than one we set it to one pixel if iheight 1 iheight 1 0 int ix count 4 xborder 5 int dheight int height iheight g set color color blue g draw line ix 1 int height ix 1 dheight g draw line ix int height ix dheight g set color color black draw a red line for 90 point if num 0 long value ninety long value g set color color red g draw line ix int height ix 55 g draw line ix 35 ix 0 g draw string 90 ix 30 20 g draw string string value of num 0 long value ix 8 20 draw an orange line for 50 point if num 0 long value fifty long value g set color color orange g draw line ix int height ix 30 g draw string 50 ix 30 50 g draw string string value of num 0 long value ix 8 50 drawsample samplingstatcalculator p_model getwidth getheight setcolor lightgray drawline setcolor drawstring valueof setcolor drawline drawline p_model p_model getcount p_model getpercentpoint p_model getpercentpoint p_model getcount p_model getdistribution toarray numbercomparator intvalue setcolor drawline drawline setcolor longvalue longvalue setcolor drawline drawline drawstring drawstring valueof longvalue longvalue longvalue setcolor drawline drawstring drawstring valueof longvalue java lang string boolean int protected http sample result sample url u string s boolean b int i throw new unsupported operation exception for test purposes only httpsampleresult unsupportedoperationexception private static final logger log logging manager get logger for class public testhtml parser string arg0 super arg0 loggingmanager getloggerforclass testhtmlparser private int test number 0 public testhtml parser string name int test super name test number test testnumber testhtmlparser testnumber public testhtml parser string name string parser int test super name test number test parser name parser testhtmlparser testnumber parsername private static class static test class can t instantiate private static test class statictestclass statictestclass private class test class can t instantiate private test class testclass testclass private test data string f string b string s string l file name f baseurl b expected set s expected list l testdata filename expectedset expectedlist public static junit framework test suite test suite suite new test suite testhtml parser suite add test new testhtml parser test default parser suite add test new testhtml parser test parser default suite add test new testhtml parser test parser missing suite add test new testhtml parser test not parser suite add test new testhtml parser test not creatable suite add test new testhtml parser test not creatable static for int i 0 i parsers length i test suite ps new test suite parsers i identify subtests ps add test new testhtml parser test parser property parsers i 0 for int j 0 j tests length j test suite ts new test suite tests j file name ts add test new testhtml parser test parser set parsers i j ts add test new testhtml parser test parser list parsers i j ps add test ts suite add test ps return suite testsuite testsuite testhtmlparser addtest testhtmlparser testdefaultparser addtest testhtmlparser testparserdefault addtest testhtmlparser testparsermissing addtest testhtmlparser testnotparser addtest testhtmlparser testnotcreatable addtest testhtmlparser testnotcreatablestatic testsuite testsuite addtest testhtmlparser testparserproperty testsuite testsuite filename addtest testhtmlparser testparserset addtest testhtmlparser testparserlist addtest addtest test if can instantiate parser using property name public void test parser property throws exception properties p j meter utils getj meter properties if p null p j meter utils get properties jmeter properties p set property html parser parser classname parser name html parser get parser testparserproperty jmeterutils getjmeterproperties jmeterutils getproperties setproperty htmlparser parser_classname parsername htmlparser getparser public void test default parser throws exception html parser get parser testdefaultparser htmlparser getparser public void test parser default throws exception html parser get parser html parser default parser testparserdefault htmlparser getparser htmlparser default_parser public void test parser missing throws exception try html parser get parser no such parser fail should not have been able to create the parser catch html parse error e if e get cause instanceof class not found exception this is ok else throw e testparsermissing htmlparser getparser htmlparseerror getcause classnotfoundexception public void test not parser throws exception try html parser get parser java lang string fail should not have been able to create the parser catch html parse error e if e get cause instanceof class cast exception return throw e testnotparser htmlparser getparser htmlparseerror getcause classcastexception public void test not creatable throws exception try html parser get parser test class class get name fail should not have been able to create the parser catch html parse error e if e get cause instanceof instantiation exception return throw e testnotcreatable htmlparser getparser testclass getname htmlparseerror getcause instantiationexception public void test not creatable static throws exception try html parser get parser static test class class get name fail should not have been able to create the parser catch html parse error e if e get cause instanceof class cast exception return if e get cause instanceof illegal access exception return throw e testnotcreatablestatic htmlparser getparser statictestclass getname htmlparseerror getcause classcastexception getcause illegalaccessexception public void test parser set throws exception html parser p html parser get parser parser name filetest p tests test number file name tests test number baseurl tests test number expected set null false testparserset htmlparser htmlparser getparser parsername testnumber filename testnumber testnumber expectedset public void test parser list throws exception html parser p html parser get parser parser name filetest p tests test number file name tests test number baseurl tests test number expected list new vector true testparserlist htmlparser htmlparser getparser parsername testnumber filename testnumber testnumber expectedlist private static void filetest html parser p string file string url string result file collection c boolean order matters does the order matter throws exception string parser name p get class get name substring org apache jmeter protocol http parser length string fname file substring file index of 1 log debug file file file f find test file file byte buffer new byte int f length int len new file input stream f read buffer assert equals len buffer length iterator result if c null result p get embedded resourceur ls buffer new url url else result p get embedded resourceur ls buffer new url url c todo exact ordering is only required for some tests change the comparison to do a set compare where necessary iterator expected if order matters expected get file result file iterator else convert both to sets expected new tree set get file result file iterator tree set temp new tree set new comparator public int compare object o1 object o2 return o1 to string compare to o2 to string while result has next temp add result next result temp iterator while expected has next object next expected next assert true fname parser name expecting another result next result has next try assert equals fname parser name next next url result next to string catch class cast exception e fail fname parser name expected url but got e to string assert false fname parser name should have reached the end of the results result has next htmlparser resultfile ordermatters parsername getclass getname indexof findtestfile fileinputstream assertequals getembeddedresourceurls getembeddedresourceurls ordermatters getfile resultfile treeset getfile resultfile treeset treeset tostring compareto tostring hasnext hasnext asserttrue parsername hasnext assertequals parsername tostring classcastexception parsername tostring assertfalse parsername hasnext expected new tree set get file result file iterator tree set temp new tree set new comparator public int compare object o1 object o2 return o1 to string compare to o2 to string treeset getfile resultfile treeset treeset tostring compareto tostring get expected results as a list private static list get file string file throws exception array list al new array list if file null file length 0 buffered reader br new buffered reader new file reader find test file file string line br read line while line null al add line line br read line br close return al getfile arraylist arraylist bufferedreader bufferedreader filereader findtestfile readline readline create a proxy authenticator with the specified username and password param user name the username to authenticate with param password the password to authenticate with public proxy authenticator string user name string password this user name user name this password password to char array proxyauthenticator username proxyauthenticator username username username tochararray return a password authentication instance using the user name and password specified in the constructor return a password authentication instance to use for authenticating with the proxy protected password authentication get password authentication return new password authentication user name password passwordauthentication username passwordauthentication passwordauthentication getpasswordauthentication passwordauthentication username private transient string saved value public string property string name string value super name this value value savedvalue stringproperty public string property super stringproperty see j meter property set running version boolean public void set running version boolean running version super set running version running version if running version saved value value else saved value null jmeterproperty setrunningversion setrunningversion runningversion setrunningversion runningversion runningversion savedvalue savedvalue public void set object value object v value v to string setobjectvalue tostring see j meter property get string value public string get string value return value jmeterproperty getstringvalue getstringvalue see j meter property get object value public object get object value return value jmeterproperty getobjectvalue getobjectvalue public object clone string property prop string property super clone prop value value return prop stringproperty stringproperty sets the value param value the value to set public void set value string value this value value setvalue public void recover running version test element owner if saved value null value saved value recoverrunningversion testelement savedvalue savedvalue default constructor for ldap config gui public ldap config gui this true ldapconfiggui ldapconfiggui public string get label resource return ldap sample title non nls 1 getlabelresource ldap_sample_title a newly created component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui param element the test element to configure public void configure test element element super configure element servername set text element get property as string ldap sampler servername port set text element get property as string ldap sampler port rootdn set text element get property as string ldap sampler rootdn card layout cl card layout cards get layout final string test type element get property as string ldap sampler test if test type equals ldap sampler add add test set selected true add set text element get property as string ldap sampler base entry dn table add panel configure test element element get property ldap sampler arguments get object value cl show cards add else if test type equals ldap sampler modify modify test set selected true modify set text element get property as string ldap sampler base entry dn table modify panel configure test element element get property ldap sampler arguments get object value cl show cards modify else if test type equals ldap sampler delete delete test set selected true delete set text element get property as string ldap sampler delete cl show cards delete else if test type equals ldap sampler searchbase search test set selected true searchbase set text element get property as string ldap sampler searchbase searchfilter set text element get property as string ldap sampler searchfilter cl show cards search if element get property as boolean ldap sampler user defined user defined set selected true else user defined set selected false cl show cards non nls 1 testelement testelement settext getpropertyasstring ldapsampler settext getpropertyasstring ldapsampler settext getpropertyasstring ldapsampler cardlayout cardlayout getlayout testtype getpropertyasstring ldapsampler testtype ldapsampler addtest setselected settext getpropertyasstring ldapsampler base_entry_dn tableaddpanel testelement getproperty ldapsampler getobjectvalue testtype ldapsampler modifytest setselected settext getpropertyasstring ldapsampler base_entry_dn tablemodifypanel testelement getproperty ldapsampler getobjectvalue testtype ldapsampler deletetest setselected settext getpropertyasstring ldapsampler testtype ldapsampler searchtest setselected settext getpropertyasstring ldapsampler settext getpropertyasstring ldapsampler getpropertyasboolean ldapsampler user_defined user_defined setselected user_defined setselected implements j metergui component create test element public test element create test element config test element element new config test element modify test element element return element jmeterguicomponent createtestelement testelement createtestelement configtestelement configtestelement modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element element element clear configure test element element element set property ldap sampler servername servername get text element set property ldap sampler port port get text element set property ldap sampler rootdn rootdn get text element set property new boolean property ldap sampler user defined user defined is selected if add test is selected element set property new string property ldap sampler test ldap sampler add element set property new string property ldap sampler base entry dn add get text element set property new test element property ldap sampler arguments table add panel create test element if modify test is selected element set property new string property ldap sampler test ldap sampler modify element set property new string property ldap sampler base entry dn modify get text element set property new test element property ldap sampler arguments table modify panel create test element if delete test is selected element set property new string property ldap sampler test ldap sampler delete element set property new string property ldap sampler delete delete get text if search test is selected element set property new string property ldap sampler test ldap sampler searchbase element set property new string property ldap sampler searchbase searchbase get text element set property new string property ldap sampler searchfilter searchfilter get text testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement setproperty ldapsampler gettext setproperty ldapsampler gettext setproperty ldapsampler gettext setproperty booleanproperty ldapsampler user_defined user_defined isselected addtest isselected setproperty stringproperty ldapsampler ldapsampler setproperty stringproperty ldapsampler base_entry_dn gettext setproperty testelementproperty ldapsampler tableaddpanel createtestelement modifytest isselected setproperty stringproperty ldapsampler ldapsampler setproperty stringproperty ldapsampler base_entry_dn gettext setproperty testelementproperty ldapsampler tablemodifypanel createtestelement deletetest isselected setproperty stringproperty ldapsampler ldapsampler setproperty stringproperty ldapsampler gettext searchtest isselected setproperty stringproperty ldapsampler ldapsampler setproperty stringproperty ldapsampler gettext setproperty stringproperty ldapsampler gettext implements j metergui component clear gui public void clear gui super clear gui rootdn set text non nls 1 searchbase set text non nls 1 searchfilter set text non nls 1 delete set text non nls 1 add set text non nls 1 modify set text non nls 1 servername set text non nls 1 port set text non nls 1 user defined set selected false add test set selected true modify test set selected false delete test set selected false search test set selected false jmeterguicomponent cleargui cleargui cleargui settext settext settext settext settext settext settext settext user_defined setselected addtest setselected modifytest setselected deletetest setselected searchtest setselected this item state changed listener for changing the card layout for based on the test selected in the user defined test case public void item state changed item event ie card layout cl card layout cards get layout if user defined is selected if add test is selected cl show cards add table modify panel clear modify set text non nls 1 searchbase set text non nls 1 searchfilter set text non nls 1 delete set text else if delete test is selected cl show cards delete table modify panel clear modify set text non nls 1 table add panel clear add set text non nls 1 searchbase set text non nls 1 searchfilter set text non nls 1 else if search test is selected cl show cards search delete set text non nls 1 table modify panel clear modify set text non nls 1 table add panel clear add set text non nls 1 else if modify test is selected cl show cards modify table add panel clear add set text non nls 1 searchbase set text non nls 1 searchfilter set text non nls 1 delete set text else cl show cards non nls 1 table add panel clear add set text non nls 1 table modify panel clear modify set text non nls 1 searchbase set text non nls 1 searchfilter set text non nls 1 delete set text non nls 1 else cl show cards non nls 1 table add panel clear add set text non nls 1 table modify panel clear modify set text non nls 1 searchbase set text non nls 1 searchfilter set text non nls 1 delete set text non nls 1 itemstatechanged itemstatechanged itemevent cardlayout cardlayout getlayout user_defined isselected addtest isselected tablemodifypanel settext settext settext settext deletetest isselected tablemodifypanel settext tableaddpanel settext settext settext searchtest isselected settext tablemodifypanel settext tableaddpanel settext modifytest isselected tableaddpanel settext settext settext settext tableaddpanel settext tablemodifypanel settext settext settext settext tableaddpanel settext tablemodifypanel settext settext settext settext public ldap config gui boolean display name this display name display name init ldapconfiggui displayname displayname displayname this will create the servername panel in the ldap config gui private j panel create servername panel j panel server panel new j panel new border layout 5 0 j label label new j label j meter utils get res string servername non nls 1 label set label for servername server panel add label border layout west server panel add servername border layout center return server panel ldapconfiggui jpanel createservernamepanel jpanel serverpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor serverpanel borderlayout serverpanel borderlayout serverpanel this will create the port panel in the ldap config gui private j panel create port panel j panel port panel new j panel new border layout 5 0 j label label new j label j meter utils get res string port non nls 1 label set label for port port panel add label border layout west port panel add port border layout center return port panel ldapconfiggui jpanel createportpanel jpanel portpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor portpanel borderlayout portpanel borderlayout portpanel this will create the root distinguised name panel in the ldap config gui private j panel create rootdn panel j panel rootdn panel new j panel new border layout 5 0 j label label new j label j meter utils get res string dn non nls 1 label set label for rootdn rootdn panel add label border layout west rootdn panel add rootdn border layout center return rootdn panel ldapconfiggui jpanel createrootdnpanel jpanel rootdnpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor rootdnpanel borderlayout rootdnpanel borderlayout rootdnpanel this will create the search panel in the ldap config gui private j panel create search panel vertical panel search panel new vertical panel j panel searchb panel new j panel new border layout 5 0 j label label new j label j meter utils get res string search base non nls 1 label set label for searchbase searchb panel add label border layout west searchb panel add searchbase border layout center j panel searchf panel new j panel new border layout 5 0 j label label2 new j label j meter utils get res string search filter non nls 1 label2 set label for searchfilter searchf panel add label2 border layout west searchf panel add searchfilter border layout center search panel add searchb panel search panel add searchf panel return search panel ldapconfiggui jpanel createsearchpanel verticalpanel searchpanel verticalpanel jpanel searchbpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring search_base setlabelfor searchbpanel borderlayout searchbpanel borderlayout jpanel searchfpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring search_filter setlabelfor searchfpanel borderlayout searchfpanel borderlayout searchpanel searchbpanel searchpanel searchfpanel searchpanel this will create the delete panel in the ldap config gui private j panel create delete panel vertical panel panel new vertical panel j panel delete panel new j panel new border layout 5 0 j label label new j label j meter utils get res string delete non nls 1 label set label for delete delete panel add label border layout west delete panel add delete border layout center panel add delete panel return panel ldapconfiggui jpanel createdeletepanel verticalpanel verticalpanel jpanel deletepanel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor deletepanel borderlayout deletepanel borderlayout deletepanel this will create the add test panel in the ldap config gui private j panel create add panel j panel add panel new j panel new border layout 5 0 j panel add inner panel new j panel new border layout 5 0 j label label new j label j meter utils get res string entry dn non nls 1 label set label for add add inner panel add label border layout west add inner panel add add border layout center add panel add add inner panel border layout north add panel add table add panel border layout center return add panel ldapconfiggui jpanel createaddpanel jpanel addpanel jpanel borderlayout jpanel addinnerpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring entry_dn setlabelfor addinnerpanel borderlayout addinnerpanel borderlayout addpanel addinnerpanel borderlayout addpanel tableaddpanel borderlayout addpanel this will create the modify panel in the ldap config gui private j panel create modify panel j panel modify panel new j panel new border layout 5 0 j panel modify inner panel new j panel new border layout 5 0 j label label new j label j meter utils get res string entry dn non nls 1 label set label for modify modify inner panel add label border layout west modify inner panel add modify border layout center modify panel add modify inner panel border layout north modify panel add table modify panel border layout center return modify panel ldapconfiggui jpanel createmodifypanel jpanel modifypanel jpanel borderlayout jpanel modifyinnerpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring entry_dn setlabelfor modifyinnerpanel borderlayout modifyinnerpanel borderlayout modifypanel modifyinnerpanel borderlayout modifypanel tablemodifypanel borderlayout modifypanel this will create the user defined test panel for create or modify or delete or search based on the panel selected in the itemevent in the ldap config gui private j panel test panel cards new j panel new card layout cards add new j panel cards add create add panel add cards add create modify panel modify cards add create delete panel delete cards add create search panel search return cards ldapconfiggui jpanel testpanel jpanel cardlayout jpanel createaddpanel createmodifypanel createdeletepanel createsearchpanel this will create the test panel in the ldap config gui private j panel create test panel j panel test panel new j panel new border layout test panel set border border factory create titled border j meter utils get res string test configuration non nls 1 test panel add new j label j meter utils get res string test non nls 1 j panel row panel new j panel row panel add add test b group add add test row panel add delete test b group add delete test row panel add search test b group add search test row panel add modify test b group add modify test test panel add row panel border layout north test panel add user defined border layout center return test panel ldapconfiggui jpanel createtestpanel jpanel testpanel jpanel borderlayout testpanel setborder borderfactory createtitledborder jmeterutils getresstring test_configuration testpanel jlabel jmeterutils getresstring jpanel rowpanel jpanel rowpanel addtest bgroup addtest rowpanel deletetest bgroup deletetest rowpanel searchtest bgroup searchtest rowpanel modifytest bgroup modifytest testpanel rowpanel borderlayout testpanel user_defined borderlayout testpanel this will initialise all the panel in the ldap config gui private void init set layout new border layout 0 5 if display name set border make border add make title panel border layout north vertical panel main panel new vertical panel main panel add create servername panel main panel add create port panel main panel add create rootdn panel main panel add create test panel main panel add test panel add main panel border layout center user defined add item listener this add test add item listener this modify test add item listener this delete test add item listener this search test add item listener this ldapconfiggui setlayout borderlayout displayname setborder makeborder maketitlepanel borderlayout verticalpanel mainpanel verticalpanel mainpanel createservernamepanel mainpanel createportpanel mainpanel createrootdnpanel mainpanel createtestpanel mainpanel testpanel mainpanel borderlayout user_defined additemlistener addtest additemlistener modifytest additemlistener deletetest additemlistener searchtest additemlistener public class renderer utils private renderer utils uninstantiable rendererutils rendererutils public static void apply renderers final j table table final table cell renderer renderers final table column model column model table get column model for int i 0 i renderers length i final table cell renderer rend renderers i if rend null column model get column i set cell renderer rend applyrenderers jtable tablecellrenderer tablecolumnmodel columnmodel getcolumnmodel tablecellrenderer columnmodel getcolumn setcellrenderer constructor param name the name long option param flags the flags param id the id character option param description description of option usage public cl option descriptor final string name final int flags final int id final string description check flags flags m id id m name name m flags flags m description description m incompatible flags duplicates allowed 0 new int 0 new int id cloptiondescriptor checkflags m_id m_name m_flags m_description m_incompatible duplicates_allowed constructor param name the name long option param flags the flags param id the id character option param description description of option usage param incompatible descriptors for incompatible options public cl option descriptor final string name final int flags final int id final string description final cl option descriptor incompatible check flags flags m id id m name name m flags flags m description description m incompatible new int incompatible length for int i 0 i incompatible length i m incompatible i incompatible i get id cloptiondescriptor cloptiondescriptor checkflags m_id m_name m_flags m_description m_incompatible m_incompatible getid private void check flags final int flags int mode count 0 if argument required flags argument required mode count if argument optional flags argument optional mode count if argument disallowed flags argument disallowed mode count if arguments required 2 flags arguments required 2 mode count if 0 mode count final string message no mode specified for option this throw new illegal state exception message else if 1 mode count final string message multiple modes specified for option this throw new illegal state exception message checkflags modecount argument_required argument_required modecount argument_optional argument_optional modecount argument_disallowed argument_disallowed modecount arguments_required_2 arguments_required_2 modecount modecount illegalstateexception modecount illegalstateexception get the array of incompatible option ids return the array of incompatible option ids protected final int get incompatible return m incompatible getincompatible m_incompatible retrieve textual description return the description public final string get description return m description getdescription m_description retrieve flags about option flags include details such as whether it allows parameters etc return the flags public final int get flags return m flags getflags m_flags retrieve the id for option the id is also the character if using single character options return the id public final int get id return m id getid m_id retrieve name of option which is also text for long option return name long option public final string get name return m name getname m_name convert to string return the converted value to string public final string to string final string buffer sb new string buffer sb append option descriptor sb append m name sb append sb append m id sb append sb append m flags sb append sb append m description sb append return sb to string tostring stringbuffer stringbuffer optiondescriptor m_name m_id m_flags m_description tostring returns the result of the assertion checks if the result is well formed xml and that the x path expression is matched or not as the case may be public assertion result get result sample result response no error as default assertion result result new assertion result get name byte response data response get response data if response data length 0 return result set result for null result set failure false result set failure message if log is debug enabled log debug new string buffer validation is set to append is validating to string log debug new string buffer whitespace is set to append is whitespace to string log debug new string buffer tolerant is set to append is tolerant to string document doc null boolean isxml j orphan utils isxml response data try doc x path util make document new byte array input stream response data is validating is whitespace is namespace is tolerant is quiet show warnings report errors isxml catch sax exception e log debug caught sax exception e result set error true result set failure message new string buffer sax exception append e get message to string return result catch io exception e log warn cannot parse result content e result set error true result set failure message new string buffer io exception append e get message to string return result catch parser configuration exception e log warn cannot parse result content e result set error true result set failure message new string buffer parser configuration exception append e get message to string return result catch tidy exception e result set error true result set failure message e get message return result if doc null doc get document element null result set error true result set failure message document is null probably not parsable return result node list node list null final string path string getx path string try x object x object x pathapi eval doc path string switch x object get type case x object class nodeset node list x object nodelist break case x object class boolean if x object bool result set failure is negated result set failure message no nodes matched path string return result default result set failure true result set failure message cannot understand path string return result catch transformer exception e result set error true result set failure message new string buffer transformer exception append e get message append for append path string to string return result if node list null node list get length 0 log debug new string buffer node list null no match append path string to string result set failure is negated result set failure message no nodes matched path string return result log debug node list length node list get length if log is debug enabled is negated for int i 0 i node list get length i log debug new string buffer node list append i append append node list item i to string result set failure is negated if is negated result set failure message specified x path was found turn off negate if this is not desired return result xpath assertionresult getresult sampleresult assertionresult assertionresult getname responsedata getresponsedata responsedata setresultfornull setfailure setfailuremessage isdebugenabled stringbuffer isvalidating tostring stringbuffer iswhitespace tostring stringbuffer istolerant tostring jorphanutils responsedata xpathutil makedocument bytearrayinputstream responsedata isvalidating iswhitespace isnamespace istolerant isquiet showwarnings reporterrors saxexception seterror setfailuremessage stringbuffer saxexception getmessage tostring ioexception seterror setfailuremessage stringbuffer ioexception getmessage tostring parserconfigurationexception seterror setfailuremessage stringbuffer parserconfigurationexception getmessage tostring tidyexception seterror setfailuremessage getmessage getdocumentelement seterror setfailuremessage nodelist nodelist pathstring getxpathstring xobject xobject xpathapi pathstring xobject gettype xobject class_nodeset nodelist xobject xobject class_boolean xobject setfailure isnegated setfailuremessage pathstring setfailure setfailuremessage pathstring transformerexception seterror setfailuremessage stringbuffer transformerexception getmessage pathstring tostring nodelist nodelist getlength stringbuffer nodelist pathstring tostring setfailure isnegated setfailuremessage pathstring nodelist nodelist getlength isdebugenabled isnegated nodelist getlength stringbuffer nodelist nodelist tostring setfailure isnegated isnegated setfailuremessage xpath get the x path string that will be used in matching the document return string xpath string public string getx path string return get property as string xpath key default xpath xpath getxpathstring getpropertyasstring xpath_key default_xpath set the x path string this will be used as an xpath param xpath string public void setx path string string xpath set property new string property xpath key xpath xpath setxpathstring setproperty stringproperty xpath_key set whether to ignore element whitespace param whitespace public void set whitespace boolean whitespace set property new boolean property whitespace key whitespace setwhitespace setproperty booleanproperty whitespace_key set use validation param validate public void set validating boolean validate set property new boolean property validate key validate setvalidating setproperty booleanproperty validate_key set whether this is namespace aware param namespace public void set namespace boolean namespace set property new boolean property namespace key namespace setnamespace setproperty booleanproperty namespace_key set tolerant mode if required param tolerant true false public void set tolerant boolean tolerant set property new boolean property tolerant key tolerant settolerant setproperty booleanproperty tolerant_key public void set negated boolean negate set property new boolean property negate key negate setnegated setproperty booleanproperty negate_key is this whitepsace ignored return boolean public boolean is whitespace return get property as boolean whitespace key false iswhitespace getpropertyasboolean whitespace_key is this validating return boolean public boolean is validating return get property as boolean validate key false isvalidating getpropertyasboolean validate_key is this namespace aware return boolean public boolean is namespace return get property as boolean namespace key false isnamespace getpropertyasboolean namespace_key is this using tolerant mode return boolean public boolean is tolerant return get property as boolean tolerant key false istolerant getpropertyasboolean tolerant_key negate the x path test that is return true if something is not found return boolean negated public boolean is negated return get property as boolean negate key false xpath isnegated getpropertyasboolean negate_key public void set report errors boolean val set property report errors key val false setreporterrors setproperty report_errors_key public boolean report errors return get property as boolean report errors key false reporterrors getpropertyasboolean report_errors_key public void set show warnings boolean val set property show warnings key val false setshowwarnings setproperty show_warnings_key public boolean show warnings return get property as boolean show warnings key false showwarnings getpropertyasboolean show_warnings_key public void set quiet boolean val set property quiet key val true setquiet setproperty quiet_key public boolean is quiet return get property as boolean quiet key true isquiet getpropertyasboolean quiet_key public summariser super synchronized accumulators accumulators clear instance count 0 instancecount constructor for use during startup intended for non gui use param name of summariser public summariser string name this set name name setname add the delta values to the total values and clear the delta private void move delta total add sample delta delta clear movedelta addsample accumulates the sample in two sample result objects one for running totals and the other for deltas see org apache jmeter samplers sample listener sample occurred org apache jmeter samplers sample event public void sample occurred sample event e sample result s e get result long now system current time millis 1000 in seconds running sample my delta null running sample my total null boolean report now false have we reached the reporting boundary need to allow for a margin of error otherwise can miss the slot also need to check we ve not hit the window already synchronized my totals if s null my totals delta add sample s if now my totals last interval window now interval interval window report now true copy the data to minimise the synch time my delta new running sample my totals delta my totals move delta my total new running sample my totals total my totals last now stop double reporting if report now string str str format my name my delta if tolog log info str if toout system out println str only if we have updated them if my total null my delta null my total get num samples my delta get num samples str format my name my total if tolog log info str if toout system out println str sampleresult samplelistener sampleoccurred sampleevent sampleoccurred sampleevent sampleresult getresult currenttimemillis runningsample mydelta runningsample mytotal reportnow mytotals mytotals addsample mytotals interval_window interval_window reportnow mydelta runningsample mytotals mytotals movedelta mytotal runningsample mytotals mytotals reportnow myname mydelta mytotal mydelta mytotal getnumsamples mydelta getnumsamples myname mytotal private static string buffer long to sb string buffer sb long l int len sb set length 0 sb append l return j orphan utils right align sb len stringbuffer longtosb stringbuffer setlength jorphanutils rightalign private static string buffer double to sb string buffer sb double d int len int frac sb set length 0 df double set minimum fraction digits frac df double set maximum fraction digits frac sb append df double format d return j orphan utils right align sb len stringbuffer doubletosb stringbuffer setlength dfdouble setminimumfractiondigits dfdouble setmaximumfractiondigits dfdouble jorphanutils rightalign param my total param string return private string format string name running sample s string type string buffer tmp new string buffer 20 for intermediate use string buffer sb new string buffer 100 output line buffer sb append name sb append sb append type sb append sb append long to sb tmp s get num samples 5 sb append in long elapsed s get elapsed sb append double to sb tmp elapsed 1000 0 5 1 sb append s if elapsed 0 sb append double to sb tmp s get rate 6 1 else sb append rate is effectively infinite sb append s avg sb append long to sb tmp s get average 5 sb append min sb append long to sb tmp s get min 5 sb append max sb append long to sb tmp s get max 5 sb append err sb append long to sb tmp s get error count 5 sb append sb append s get error percentage string sb append return sb to string mytotal runningsample stringbuffer stringbuffer stringbuffer stringbuffer longtosb getnumsamples getelapsed doubletosb doubletosb getrate longtosb getaverage longtosb getmin longtosb getmax longtosb geterrorcount geterrorpercentagestring tostring see org apache jmeter samplers sample listener sample started org apache jmeter samplers sample event public void sample started sample event e not used samplelistener samplestarted sampleevent samplestarted sampleevent see org apache jmeter samplers sample listener sample stopped org apache jmeter samplers sample event public void sample stopped sample event e not used samplelistener samplestopped sampleevent samplestopped sampleevent see org apache jmeter testelement test listener test started public void test started test started local testlistener teststarted teststarted teststarted see org apache jmeter testelement test listener test ended public void test ended test ended local testlistener testended testended testended public void test started string host synchronized accumulators my name get name my totals totals accumulators get my name if my totals null my totals new totals accumulators put my name my totals instance count teststarted myname getname mytotals myname mytotals mytotals myname mytotals instancecount public void test ended string host object totals null synchronized accumulators instance count if instance count 0 totals accumulators entry set to array if totals null we re not done yet return for int i 0 i totals length i map entry me map entry totals i string str string name string me get key totals total totals me get value only print final delta if there were some samples in the delta and there has been at least one sample reported previously if total delta get num samples 0 total total get num samples 0 str format name total delta if tolog log info str if toout system out println str total move delta str format name total total if tolog log info str if toout system out println str testended instancecount instancecount entryset toarray getkey getvalue getnumsamples getnumsamples movedelta see org apache jmeter testelement test listener test iteration start org apache jmeter engine event loop iteration event public void test iteration start loop iteration event event not used testlistener testiterationstart loopiterationevent testiterationstart loopiterationevent public power table model string headers class classes if headers length classes length throw new illegal argument exception header and column array sizes differ model set headers headers column classes classes powertablemodel illegalargumentexception setheaders columnclasses public power table model powertablemodel public void set row values int row object values if values length model get header count throw new illegal argument exception incorrect number of data items model set current pos row for int i 0 i values length i model add column value model get headers i values i setrowvalues getheadercount illegalargumentexception setcurrentpos addcolumnvalue getheaders public data get data return model getdata public void add new column string col name class col class model add header col name class new classes new class column classes length 1 system arraycopy column classes 0 new classes 0 column classes length new classes new classes length 1 col class column classes new classes object default value create default value column classes length 1 model set column data col name default value this fire table structure changed addnewcolumn colname colclass addheader colname newclasses columnclasses columnclasses newclasses columnclasses newclasses newclasses colclass columnclasses newclasses defaultvalue createdefaultvalue columnclasses setcolumndata colname defaultvalue firetablestructurechanged public void remove row int row log debug remove row row if model size row log debug calling remove row on data model remove row row removerow removerow public void remove column int col model remove column col this fire table structure changed removecolumn removecolumn firetablestructurechanged public void set column data int col list data model set column data col data setcolumndata setcolumndata public list get column data string col name return model get column as object array col name getcolumndata colname getcolumnasobjectarray colname public void clear data string headers model get headers model new data model set headers headers this fire table data changed cleardata getheaders setheaders firetabledatachanged public void add row object data if data length model get header count throw new illegal argument exception incorrect number of data items model set current pos model size for int i 0 i data length i model add column value model get headers i data i addrow getheadercount illegalargumentexception setcurrentpos addcolumnvalue getheaders public void add new row add row create default row addnewrow addrow createdefaultrow private object create default row object row data new object get column count for int i 0 i row data length i row data i create default value i return row data createdefaultrow rowdata getcolumncount rowdata rowdata createdefaultvalue rowdata public object get row data int row object row data new object get column count for int i 0 i row data length i row data i model get column value i row return row data getrowdata rowdata getcolumncount rowdata rowdata getcolumnvalue rowdata private object create default value int i class col class get column class i try return col class new instance catch exception e try constructor constr col class get constructor new class string class return constr new instance new object catch no such method exception err catch instantiation exception err catch illegal access exception err catch invocation target exception err try constructor constr col class get constructor new class integer type return constr new instance new object new integer 0 catch no such method exception err catch instantiation exception err catch illegal access exception err catch invocation target exception err try constructor constr col class get constructor new class long type return constr new instance new object new long 0l catch no such method exception err catch instantiation exception err catch illegal access exception err catch invocation target exception err try constructor constr col class get constructor new class boolean type return constr new instance new object boolean false catch no such method exception err catch instantiation exception err catch illegal access exception err catch invocation target exception err try constructor constr col class get constructor new class float type return constr new instance new object new float 0f catch no such method exception err catch instantiation exception err catch illegal access exception err catch invocation target exception err try constructor constr col class get constructor new class double type return constr new instance new object new double 0d catch no such method exception err catch instantiation exception err catch illegal access exception err catch invocation target exception err try constructor constr col class get constructor new class character type return constr new instance new object new character catch no such method exception err catch instantiation exception err catch illegal access exception err catch invocation target exception err try constructor constr col class get constructor new class byte type return constr new instance new object new byte byte min value catch no such method exception err catch instantiation exception err catch illegal access exception err catch invocation target exception err try constructor constr col class get constructor new class short type return constr new instance new object new short short min value catch no such method exception err catch instantiation exception err catch illegal access exception err catch invocation target exception err return createdefaultvalue colclass getcolumnclass colclass newinstance colclass getconstructor newinstance nosuchmethodexception instantiationexception illegalaccessexception invocationtargetexception colclass getconstructor newinstance nosuchmethodexception instantiationexception illegalaccessexception invocationtargetexception colclass getconstructor newinstance nosuchmethodexception instantiationexception illegalaccessexception invocationtargetexception colclass getconstructor newinstance nosuchmethodexception instantiationexception illegalaccessexception invocationtargetexception colclass getconstructor newinstance nosuchmethodexception instantiationexception illegalaccessexception invocationtargetexception colclass getconstructor newinstance nosuchmethodexception instantiationexception illegalaccessexception invocationtargetexception colclass getconstructor newinstance nosuchmethodexception instantiationexception illegalaccessexception invocationtargetexception colclass getconstructor newinstance min_value nosuchmethodexception instantiationexception illegalaccessexception invocationtargetexception colclass getconstructor newinstance min_value nosuchmethodexception instantiationexception illegalaccessexception invocationtargetexception required by table model interface return the row count value public int get row count if model null return 0 return model size rowcount getrowcount required by table model interface return the column count value public int get column count return model get headers length columncount getcolumncount getheaders required by table model interface return the column name value public string get column name int column return model get headers column columnname getcolumnname getheaders public boolean is cell editable int row int column all table cells are editable return true iscelleditable public class get column class int column return column classes column getcolumnclass columnclasses required by table model interface return the value at value public object get value at int row int column return model get column value column row valueat getvalueat getcolumnvalue sets the value at attribute of the arguments object param value the new value at value public void set value at object value int row int column if row model size model set current pos row model add column value model get headers column value valueat valueat setvalueat setcurrentpos addcolumnvalue getheaders public parser impl object factory factory super this factory factory try parserfactory sax parser factory new instance parser parserfactory newsax parser dochandler new monitor handler dochandler set object factory this factory catch sax exception e log error failed to create the parser e catch parser configuration exception e log error failed to create the parser e parserimpl objectfactory saxparserfactory newinstance newsaxparser monitorhandler setobjectfactory saxexception parserconfigurationexception parse byte array and return status object param bytes return status public status parse bytes byte bytes try input source is new input source is set byte stream new byte array input stream bytes parser parse is dochandler return dochandler get contents catch sax exception e log error failed to parse the bytes e let bad input fail silently return dochandler get contents catch io exception e should never happen log error failed to read the bytes e let bad input fail silently return dochandler get contents parsebytes inputsource inputsource setbytestream bytearrayinputstream getcontents saxexception getcontents ioexception getcontents param content return status public status parse string string content return parse bytes content get bytes parsestring parsebytes getbytes param result return status public status parse sample result sample result result return parse bytes result get response data parsesampleresult sampleresult parsebytes getresponsedata default constructor public param modifier set property new test element property mask new param mask parammodifier setproperty testelementproperty parammask public param mask get mask return param mask get property mask get object value parammask getmask parammask getproperty getobjectvalue public void test started get mask reset value teststarted getmask resetvalue public void test started string host get mask reset value teststarted getmask resetvalue public void test ended testended public void test ended string host testended modifies an entry object to replace the value of any url parameter that matches a defined mask public void process sampler sam get thread context get current sampler http sampler base sampler null if sam instanceof http sampler base return else sampler http sampler base sam boolean modified false property iterator iter sampler get arguments iterator while iter has next argument arg argument iter next get object value modified modify argument arg if modified break getthreadcontext getcurrentsampler httpsamplerbase httpsamplerbase httpsamplerbase propertyiterator getarguments hasnext getobjectvalue modifyargument helper method for link modify entry replaces a parameter s value if the parameter name matches the mask name and the value is a param arg an link argument representing a http parameter return code true code if the value was replaced private boolean modify argument argument arg if a mask for this argument exists if arg get name equals get mask get field name values to be masked must be set in the web app to if equals arg get value arg set value get mask get next value return true return false modifyentry modifyargument getname getmask getfieldname webapp getvalue setvalue getmask getnextvalue see test listener test iteration start loop iteration event public void test iteration start loop iteration event event testlistener testiterationstart loopiterationevent testiterationstart loopiterationevent return returns the sample results public collection get sample results return sample results sampleresults getsampleresults sampleresults param sample results the sample results to set public void set sample results collection sample results this sample results sample results sampleresults sampleresults setsampleresults sampleresults sampleresults sampleresults return returns the test start time public long get test start time return test start time teststarttime getteststarttime teststarttime param test start time the test start time to set public void set test start time long test start time this test start time test start time teststarttime teststarttime setteststarttime teststarttime teststarttime teststarttime return returns the version public string get version return version getversion param version the version to set public void set version string version this version version setversion protected object factory super parser new monitor parser this objectfactory monitorparser public static synchronized object factory get instance if factory null factory new object factory return factory objectfactory getinstance objectfactory public synchronized status parse bytes byte bytes return parser parse bytes bytes parsebytes parsebytes public status parse string string content return parser parse string content parsestring parsestring public status parse sample result sample result result return parser parse sample result result parsesampleresult sampleresult parsesampleresult public status create status return new status impl createstatus statusimpl public connector create connector return new connector impl createconnector connectorimpl public jvm create jvm return new jvm impl createjvm jvmimpl public memory create memory return new memory impl creatememory memoryimpl public request info create request info return new request info impl requestinfo createrequestinfo requestinfoimpl public thread info create thread info return new thread info impl threadinfo createthreadinfo threadinfoimpl public worker create worker return new worker impl createworker workerimpl public workers create workers return new workers impl createworkers workersimpl protected static class monitor parser extends parser impl public monitor parser object factory factory super factory monitorparser parserimpl monitorparser objectfactory private map post action listeners new hash map private report action router postactionlisteners hashmap reportactionrouter public void action performed final action event e swing utilities invoke later new runnable public void run perform action e actionperformed actionevent swingutilities invokelater performaction public void action performed final action event e swing utilities invoke later new runnable public void run perform action e actionperformed actionevent swingutilities invokelater performaction private void perform action final action event e try report gui package get instance update current node set command objects set commands get e get action command iterator iter command objects iterator while iter has next try command c command iter next pre action performed c get class e c do action e post action performed c get class e catch illegal user action exception err j meter utils report error to user err to string catch exception err log error err catch null pointer exception er log error perform action e get action command e to string caused er j meter utils report error to user sorry this feature e get action command not yet implemented performaction actionevent reportguipackage getinstance updatecurrentnode commandobjects getactioncommand commandobjects hasnext preactionperformed getclass doaction postactionperformed getclass illegaluseractionexception jmeterutils reporterrortouser tostring nullpointerexception performaction getactioncommand tostring jmeterutils reporterrortouser getactioncommand to execute an action immediately in the current thread param e the action to execute public void do action now action event e perform action e doactionnow actionevent performaction public set get action string action name set set new hash set set command objects set commands get action name iterator iter command objects iterator while iter has next try set add iter next catch exception err log error err return set getaction actionname hashset commandobjects actionname commandobjects hasnext public command get action string action name class action class set command objects set commands get action name iterator iter command objects iterator while iter has next try command com command iter next if com get class equals action class return com catch exception err log error err return null getaction actionname actionclass commandobjects actionname commandobjects hasnext getclass actionclass public command get action string action name string class name set command objects set commands get action name iterator iter command objects iterator while iter has next try command com command iter next if com get class get name equals class name return com catch exception err log error err return null getaction actionname classname commandobjects actionname commandobjects hasnext getclass getname classname allows an action listener to receive notification of a command being executed prior to the actual execution of the command param action the class of the command for which the listener will notifications for class must extend org apache jmeter report gui action command param listener the action listener to receive the notifications public void add pre action listener class action action listener listener if action null hash set set hash set pre action listeners get action get name if set null set new hash set set add listener pre action listeners put action get name set actionlistener actionlistener addpreactionlistener actionlistener hashset hashset preactionlisteners getname hashset preactionlisteners getname allows an action listener to be removed from receiving notifications of a command being executed prior to the actual execution of the command param action the class of the command for which the listener will notifications for class must extend org apache jmeter report gui action command param listener the action listener to receive the notifications public void remove pre action listener class action action listener listener if action null hash set set hash set pre action listeners get action get name if set null set remove listener pre action listeners put action get name set actionlistener actionlistener removepreactionlistener actionlistener hashset hashset preactionlisteners getname preactionlisteners getname allows an action listener to receive notification of a command being executed after the command has executed param action the class of the command for which the listener will notifications for class must extend org apache jmeter report gui action command param listener public void add post action listener class action action listener listener if action null hash set set hash set post action listeners get action get name if set null set new hash set set add listener post action listeners put action get name set actionlistener addpostactionlistener actionlistener hashset hashset postactionlisteners getname hashset postactionlisteners getname allows an action listener to be removed from receiving notifications of a command being executed after the command has executed param action the class of the command for which the listener will notifications for class must extend org apache jmeter report gui action command param listener public void remove post action listener class action action listener listener if action null hash set set hash set post action listeners get action get name if set null set remove listener post action listeners put action get name set actionlistener removepostactionlistener actionlistener hashset hashset postactionlisteners getname postactionlisteners getname protected void pre action performed class action action event e if action null hash set listener set hash set pre action listeners get action get name if listener set null listener set size 0 object listeners listener set to array for int i 0 i listeners length i action listener listeners i action performed e preactionperformed actionevent hashset listenerset hashset preactionlisteners getname listenerset listenerset listenerset toarray actionlistener actionperformed protected void post action performed class action action event e if action null hash set listener set hash set post action listeners get action get name if listener set null listener set size 0 object listeners listener set to array for int i 0 i listeners length i action listener listeners i action performed e postactionperformed actionevent hashset listenerset hashset postactionlisteners getname listenerset listenerset listenerset toarray actionlistener actionperformed private void populate command map log info populate command map called list list classes command command iterator iter classes class command class try list classes class finder find classes that extend j meter utils get search paths new class class for name org apache jmeter gui action command commands new hash map list classes size if list classes size 0 log warn uh oh didn t find any action handlers iter classes list classes iterator while iter classes has next string str class name string iter classes next if str class name starts with org apache jmeter report gui action log info classname str class name command class class for name str class name if modifier is abstract command class get modifiers command command command class new instance iterator iter command get action names iterator while iter has next string command name string iter next set command objects set commands get command name if command objects null command objects new hash set commands put command name command objects command objects add command catch headless exception e log warn e to string catch exception e log error exception finding action handlers e populatecommandmap populatecommandmap listclasses iterclasses commandclass listclasses classfinder findclassesthatextend jmeterutils getsearchpaths forname hashmap listclasses listclasses iterclasses listclasses iterclasses hasnext strclassname iterclasses strclassname startswith strclassname commandclass forname strclassname isabstract commandclass getmodifiers commandclass newinstance getactionnames hasnext commandname commandobjects commandname commandobjects commandobjects hashset commandname commandobjects commandobjects headlessexception tostring gets the instance attribute of the action router class return the instance value public static report action router get instance if router null router new report action router router populate command map return router actionrouter reportactionrouter getinstance reportactionrouter populatecommandmap create a new j meter frame param action handler this parameter is not used param tree model the model for the test tree param tree listener the listener for the test tree public main frame action listener action handler tree model tree model j meter tree listener tree listener todo action handler isn t used remove it from the parameter list this action handler action handler todo make the running indicator its own class instead of a j button running indicator new j button stopped icon running indicator set margin new insets 0 0 0 0 running indicator set border border factory create empty border total threads new j label 0 non nls 1 active threads new j label 0 non nls 1 tree make tree tree model tree listener gui package get instance set main frame this init set default close operation do nothing on close jmeter actionhandler treemodel treelistener mainframe actionlistener actionhandler treemodel treemodel jmetertreelistener treelistener actionhandler actionhandler actionhandler jbutton runningindicator jbutton stoppedicon runningindicator setmargin runningindicator setborder borderfactory createemptyborder totalthreads jlabel activethreads jlabel maketree treemodel treelistener guipackage getinstance setmainframe setdefaultcloseoperation do_nothing_on_close default constructor for the j meter frame this constructor will not properly initialize the tree so don t use it deprecated do not use only needed for j unit tests public main frame jmeter junit mainframe specify whether or not the file load menu item should be enabled param enabled true if the menu item should be enabled false otherwise public void set file load enabled boolean enabled menu bar set file load enabled enabled setfileloadenabled menubar setfileloadenabled specify whether or not the file save menu item should be enabled param enabled true if the menu item should be enabled false otherwise public void set file save enabled boolean enabled menu bar set file save enabled enabled setfilesaveenabled menubar setfilesaveenabled specify whether or not the file revert item should be enabled param enabled true if the menu item should be enabled false otherwise public void set file revert enabled boolean enabled menu bar set file revert enabled enabled setfilerevertenabled menubar setfilerevertenabled specify the project file that was just loaded param file the full path to the file that was loaded public void set project file loaded string file menu bar set project file loaded file setprojectfileloaded menubar setprojectfileloaded set the menu that should be used for the edit menu param menu the new edit menu public void set edit menu j popup menu menu menu bar set edit menu menu seteditmenu jpopupmenu menubar seteditmenu specify whether or not the edit menu item should be enabled param enabled true if the menu item should be enabled false otherwise public void set edit enabled boolean enabled menu bar set edit enabled enabled seteditenabled menubar seteditenabled set the menu that should be used for the edit add menu param menu the new edit add menu public void set edit add menu j menu menu menu bar set edit add menu menu seteditaddmenu jmenu menubar seteditaddmenu specify whether or not the edit add menu item should be enabled param enabled true if the menu item should be enabled false otherwise public void set edit add enabled boolean enabled menu bar set edit add enabled enabled seteditaddenabled menubar seteditaddenabled specify whether or not the edit remove menu item should be enabled param enabled true if the menu item should be enabled false otherwise public void set edit remove enabled boolean enabled menu bar set edit remove enabled enabled seteditremoveenabled menubar seteditremoveenabled close the currently selected menu public void close menu if menu bar is selected menu element menu element menu bar get sub elements if menu element null for int i 0 i menu element length i j menu menu j menu menu element i if menu is selected menu set popup menu visible false menu set selected false break closemenu menubar isselected menuelement menuelement menubar getsubelements menuelement menuelement jmenu jmenu menuelement isselected setpopupmenuvisible setselected show a dialog indicating that j meter threads are stopping on a particular host param host the host where j meter threads are stopping public void show stopping message string host if stopping message null stopping message dispose stopping message new j dialog this j meter utils get res string stopping test title true non nls 1 j label stop label new j label j meter utils get res string stopping test host non nls 1 non nls 2 stop label set border border factory create empty border 20 20 20 20 stopping message get content pane add stop label stopping message pack component util center component in component this stopping message swing utilities invoke later new runnable public void run if stopping message null todo how can this be null stopping message show jmeter jmeter showstoppingmessage stoppingmessage stoppingmessage stoppingmessage jdialog jmeterutils getresstring stopping_test_title jlabel stoplabel jlabel jmeterutils getresstring stopping_test stoplabel setborder borderfactory createemptyborder stoppingmessage getcontentpane stoplabel stoppingmessage componentutil centercomponentincomponent stoppingmessage swingutilities invokelater stoppingmessage stoppingmessage swing utilities invoke later new runnable public void run if stopping message null todo how can this be null stopping message show swingutilities invokelater stoppingmessage stoppingmessage public void update counts swing utilities invoke later new runnable public void run active threads set text integer to string j meter context service get number of threads total threads set text integer to string j meter context service get total threads updatecounts swingutilities invokelater activethreads settext tostring jmetercontextservice getnumberofthreads totalthreads settext tostring jmetercontextservice gettotalthreads public void update counts swing utilities invoke later new runnable public void run active threads set text integer to string j meter context service get number of threads total threads set text integer to string j meter context service get total threads updatecounts swingutilities invokelater activethreads settext tostring jmetercontextservice getnumberofthreads totalthreads settext tostring jmetercontextservice gettotalthreads public void set main panel j component comp main panel set viewport view comp setmainpanel jcomponent mainpanel setviewportview public j tree get tree return tree jtree gettree called when a test is started on the local system this implementation sets the running indicator and ensures that the menubar is enabled and in the running state public void test started test started local menu bar set enabled true teststarted teststarted menubar setenabled called when a test is started on a specific host this implementation sets the running indicator and ensures that the menubar is in the running state param host the host where the test is starting public void test started string host hosts add host running indicator set icon running icon active threads set text 0 non nls 1 total threads set text 0 non nls 1 menu bar set running true host teststarted runningindicator seticon runningicon activethreads settext totalthreads settext menubar setrunning called when a test is ended on the local system this implementation disables the menubar stops the running indicator and closes the stopping message dialog public void test ended test ended local menu bar set enabled false testended testended menubar setenabled called when a test is ended on the remote system this implementation stops the running indicator and closes the stopping message dialog param host the host where the test is ending public void test ended string host hosts remove host if hosts size 0 running indicator set icon stopped icon j meter context service end test menu bar set running false host if stopping message null stopping message dispose stopping message null testended runningindicator seticon stoppedicon jmetercontextservice endtest menubar setrunning stoppingmessage stoppingmessage stoppingmessage implements test listener test iteration start loop iteration event public void test iteration start loop iteration event event testlistener testiterationstart loopiterationevent testiterationstart loopiterationevent create the gui components and layout private void init menu bar new j meter menu bar setj menu bar menu bar j panel all new j panel new border layout all add create tool bar border layout north j split pane tree and main new j split pane j split pane horizontal split tree panel create tree panel tree and main set left component tree panel main panel create main panel tree and main set right component main panel tree and main set resize weight 2 tree and main set continuous layout true all add tree and main border layout center get content pane add all tree set selection row 1 add window listener new window happenings set title default title set icon image j meter utils get image jmeter jpg get image non nls 1 menubar jmetermenubar setjmenubar menubar jpanel jpanel borderlayout createtoolbar borderlayout jsplitpane treeandmain jsplitpane jsplitpane horizontal_split treepanel createtreepanel treeandmain setleftcomponent treepanel mainpanel createmainpanel treeandmain setrightcomponent mainpanel treeandmain setresizeweight treeandmain setcontinuouslayout treeandmain borderlayout getcontentpane setselectionrow addwindowlistener windowhappenings settitle default_title seticonimage jmeterutils getimage getimage public void set extended frame title string fname file new operation may set to null so just return app name if fname null set title default title return allow for windows chars in filename string temp fname replace non nls 1 non nls 2 string simple name temp substring temp last index of 1 non nls 1 set title simple name fname default title non nls 1 non nls 2 setextendedframetitle settitle default_title simplename lastindexof settitle simplename default_title create the j meter tool bar pane containing the running indicator return a panel containing the running indicator private component create tool bar box tool panel new box box layout x axis tool panel add box create rigid area new dimension 10 15 tool panel add box create glue tool panel add active threads tool panel add new j label tool panel add total threads tool panel add box create rigid area new dimension 10 15 tool panel add running indicator return tool panel jmeter createtoolbar toolpanel boxlayout x_axis toolpanel createrigidarea toolpanel createglue toolpanel activethreads toolpanel jlabel toolpanel totalthreads toolpanel createrigidarea toolpanel runningindicator toolpanel create the panel where the gui representation of the test tree is displayed the tree should already be created before calling this method return a scroll pane containing the test tree gui private j scroll pane create tree panel j scroll pane treep new j scroll pane tree treep set minimum size new dimension 100 0 return treep jscrollpane createtreepanel jscrollpane jscrollpane setminimumsize create the main panel where components can display their gu is return the main scroll pane private j scroll pane create main panel return new j scroll pane guis jscrollpane createmainpanel jscrollpane create and initialize the gui representation of the test tree param tree model the test tree model param tree listener the test tree listener return the initialized test tree gui private j tree make tree tree model tree model j meter tree listener tree listener j tree treevar new j tree tree model public string get tool tip text mouse event event tree path path this get path for location event getx event gety if path null object tree node path get last path component if tree node instanceof default mutable tree node object test element default mutable tree node tree node get user object if test element instanceof test element string comment test element test element get comment if comment null comment length 0 return comment return null treevar set tool tip text treevar set cell renderer get cell renderer treevar set root visible false treevar set shows root handles true tree listener setj tree treevar treevar add tree selection listener tree listener treevar add mouse listener tree listener treevar add mouse motion listener tree listener treevar add key listener tree listener return treevar treemodel treelistener jtree maketree treemodel treemodel jmetertreelistener treelistener jtree jtree treemodel gettooltiptext mouseevent treepath getpathforlocation treenode getlastpathcomponent treenode defaultmutabletreenode testelement defaultmutabletreenode treenode getuserobject testelement testelement testelement testelement getcomment settooltiptext setcellrenderer getcellrenderer setrootvisible setshowsroothandles treelistener setjtree addtreeselectionlistener treelistener addmouselistener treelistener addmousemotionlistener treelistener addkeylistener treelistener j tree treevar new j tree tree model public string get tool tip text mouse event event tree path path this get path for location event getx event gety if path null object tree node path get last path component if tree node instanceof default mutable tree node object test element default mutable tree node tree node get user object if test element instanceof test element string comment test element test element get comment if comment null comment length 0 return comment return null jtree jtree treemodel gettooltiptext mouseevent treepath getpathforlocation treenode getlastpathcomponent treenode defaultmutabletreenode testelement defaultmutabletreenode treenode getuserobject testelement testelement testelement testelement getcomment create the tree cell renderer used to draw the nodes in the test tree return a renderer to draw the test tree nodes private tree cell renderer get cell renderer default tree cell renderer rend new j meter cell renderer rend set font new font dialog font plain 11 return rend treecellrenderer getcellrenderer defaulttreecellrenderer jmetercellrenderer setfont repaint pieces of the gui as needed while dragging this method should only be called from the swing event thread param drag icon the component being dragged param x the current mouse x coordinate param y the current mouse y coordinate public void draw dragged component component drag icon int x int y dimension size drag icon get preferred size tree panel paint immediately previous dragx location previous dragy location size width size height this get layered pane set layer drag icon 400 swing utilities paint component tree panel get graphics drag icon tree panel x y size width size height previous dragx location x previous dragy location y dragicon drawdraggedcomponent dragicon dragicon getpreferredsize treepanel paintimmediately previousdragxlocation previousdragylocation getlayeredpane setlayer dragicon swingutilities paintcomponent treepanel getgraphics dragicon treepanel previousdragxlocation previousdragylocation private static class window happenings extends window adapter called when the main j meter frame is being closed sends a notification so that j meter can react appropriately param event the window event to handle public void window closing window event event action router get instance action performed new action event this event getid action names exit windowhappenings windowadapter jmeter jmeter windowevent windowclosing windowevent actionrouter getinstance actionperformed actionevent actionnames static final random rand new random public random controller randomcontroller see org apache jmeter control generic controller reset current protected void reset current if get sub controllers size 0 current rand next int this get sub controllers size else current 0 genericcontroller resetcurrent resetcurrent getsubcontrollers nextint getsubcontrollers see org apache jmeter control generic controller increment current protected void increment current super increment current current rand next int this get sub controllers size genericcontroller incrementcurrent incrementcurrent incrementcurrent nextint getsubcontrollers private j check box skip suffix public result saver gui super init jcheckbox skipsuffix resultsavergui see org apache jmeter gui j metergui component get static label public string get label resource return resultsaver title non nls 1 jmeterguicomponent getstaticlabel getlabelresource resultsaver_title see org apache jmeter gui j metergui component configure test element public void configure test element el super configure el filename set text el get property as string result saver filename errors only set selected el get property as boolean result saver errors only success only set selected el get property as boolean result saver success only skip auto number set selected el get property as boolean result saver skip auto number skip suffix set selected el get property as boolean result saver skip suffix variable name set text el get property as string result saver variable name jmeterguicomponent testelement testelement settext getpropertyasstring resultsaver errorsonly setselected getpropertyasboolean resultsaver errors_only successonly setselected getpropertyasboolean resultsaver success_only skipautonumber setselected getpropertyasboolean resultsaver skip_auto_number skipsuffix setselected getpropertyasboolean resultsaver skip_suffix variablename settext getpropertyasstring resultsaver variable_name see org apache jmeter gui j metergui component create test element public test element create test element result saver result saver new result saver modify test element result saver return result saver jmeterguicomponent createtestelement testelement createtestelement resultsaver resultsaver resultsaver modifytestelement resultsaver resultsaver modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element te super configure test element te te set property result saver filename filename get text te set property result saver errors only errors only is selected te set property result saver skip auto number skip auto number is selected te set property result saver skip suffix skip suffix is selected te set property result saver success only success only is selected abstract test element at abstract test element te at set property result saver variable name variable name get text non nls 1 testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement setproperty resultsaver gettext setproperty resultsaver errors_only errorsonly isselected setproperty resultsaver skip_auto_number skipautonumber isselected setproperty resultsaver skip_suffix skipsuffix isselected setproperty resultsaver success_only successonly isselected abstracttestelement abstracttestelement setproperty resultsaver variable_name variablename gettext implements j metergui component clear gui public void clear gui super clear gui skip auto number set selected false skip suffix set selected false filename set text non nls 1 errors only set selected false success only set selected false variable name set text non nls 1 jmeterguicomponent cleargui cleargui cleargui skipautonumber setselected skipsuffix setselected settext errorsonly setselected successonly setselected variablename settext private void init set layout new border layout set border make border box box box create vertical box box add make title panel box add create filename prefix panel box add create variable name panel errors only new j check box j meter utils get res string resultsaver errors non nls 1 box add errors only success only new j check box j meter utils get res string resultsaver success non nls 1 box add success only skip auto number new j check box j meter utils get res string resultsaver skipautonumber non nls 1 box add skip auto number skip suffix new j check box j meter utils get res string resultsaver skipsuffix non nls 1 box add skip suffix add box border layout north setlayout borderlayout setborder makeborder createverticalbox maketitlepanel createfilenameprefixpanel createvariablenamepanel errorsonly jcheckbox jmeterutils getresstring resultsaver_errors errorsonly successonly jcheckbox jmeterutils getresstring resultsaver_success successonly skipautonumber jcheckbox jmeterutils getresstring resultsaver_skipautonumber skipautonumber skipsuffix jcheckbox jmeterutils getresstring resultsaver_skipsuffix skipsuffix borderlayout private j panel create filename prefix panel j label label new j label j meter utils get res string resultsaver prefix non nls 1 filename new j text field 10 filename set name result saver filename label set label for filename j panel filename panel new j panel new border layout 5 0 filename panel add label border layout west filename panel add filename border layout center return filename panel jpanel createfilenameprefixpanel jlabel jlabel jmeterutils getresstring resultsaver_prefix jtextfield setname resultsaver setlabelfor jpanel filenamepanel jpanel borderlayout filenamepanel borderlayout filenamepanel borderlayout filenamepanel private j panel create variable name panel j label label new j label j meter utils get res string resultsaver variable non nls 1 variable name new j text field 10 variable name set name result saver variable name label set label for variable name j panel filename panel new j panel new border layout 5 0 filename panel add label border layout west filename panel add variable name border layout center return filename panel jpanel createvariablenamepanel jlabel jlabel jmeterutils getresstring resultsaver_variable variablename jtextfield variablename setname resultsaver variable_name setlabelfor variablename jpanel filenamepanel jpanel borderlayout filenamepanel borderlayout filenamepanel variablename borderlayout filenamepanel needed to avoid class cast error in clear java public void clear data cleardata public class j meter tree model extends default tree model public j meter tree model test element tp test element wb super new j meter tree node wb null init tree tp wb jmetertreemodel defaulttreemodel jmetertreemodel testelement testelement jmetertreenode inittree public j meter tree model this new test plan gui create test element new work bench gui create test element super new j meter tree node new work bench gui create test element null test element tp new test plan gui create test element init tree tp jmetertreemodel testplangui createtestelement workbenchgui createtestelement jmetertreenode workbenchgui createtestelement testelement testplangui createtestelement inittree hack to allow tree model to be used in non gui and headless mode deprecated only for use by j meter class param o dummy public j meter tree model object o this new test plan new work bench super new j meter tree node new work bench null test element tp new test plan init tree tp new work bench treemodel jmeter jmetertreemodel testplan workbench jmetertreenode workbench testelement testplan inittree workbench returns a list of tree nodes that hold objects of the given class type if none are found an empty list is returned public list get nodes of type class type list node list new linked list traverse and find type j meter tree node this get root node list return node list getnodesoftype nodelist linkedlist traverseandfind jmetertreenode getroot nodelist nodelist get the node for a given test element object public j meter tree node get node of test element user object return traverse and find user object j meter tree node get root testelement jmetertreenode getnodeof testelement userobject traverseandfind userobject jmetertreenode getroot adds the sub tree at the given node returns a boolean indicating whether the added sub tree was a full test plan public hash tree add sub tree hash tree sub tree j meter tree node current throws illegal user action exception iterator iter sub tree list iterator while iter has next test element item test element iter next if item instanceof test plan test plan tp test plan item current j meter tree node j meter tree node get root get child at 0 final test plan user object test plan current get user object user object add test element item user object set name item get name user object set functional mode tp is functional mode user object set serialized tp is serialized add sub tree sub tree get tree item current else if item instanceof work bench current j meter tree node j meter tree node get root get child at 1 final test element test element test element current get user object test element add test element item test element set name item get name add sub tree sub tree get tree item current else add sub tree sub tree get tree item add component item current return get current sub tree current hashtree addsubtree hashtree subtree jmetertreenode illegaluseractionexception subtree hasnext testelement testelement testplan testplan testplan jmetertreenode jmetertreenode getroot getchildat testplan userobject testplan getuserobject userobject addtestelement userobject setname getname userobject setfunctionalmode isfunctionalmode userobject setserialized isserialized addsubtree subtree gettree workbench jmetertreenode jmetertreenode getroot getchildat testelement testelement testelement getuserobject testelement addtestelement testelement setname getname addsubtree subtree gettree addsubtree subtree gettree addcomponent getcurrentsubtree public j meter tree node add component test element component j meter tree node node throws illegal user action exception if node get user object instanceof abstract config gui throw new illegal user action exception this node cannot hold sub elements component set property test element gui class name updater get current name component get property as string test element gui class gui package gui package gui package get instance if gui package null the node can be added in non gui mode at startup gui package update current node j metergui component guicomp gui package get gui component guicomp configure component guicomp modify test element component gui package get current gui put the gui object back to the way it was j meter tree node new node new j meter tree node component this this check the state of the test element and if returns false it disable the loaded node try if component get property test element enabled instanceof null property component get property as boolean test element enabled new node set enabled true else new node set enabled false catch exception e new node set enabled true this insert node into new node node node get child count return new node jmetertreenode addcomponent testelement jmetertreenode illegaluseractionexception getuserobject abstractconfiggui illegaluseractionexception setproperty testelement gui_class nameupdater getcurrentname getpropertyasstring testelement gui_class guipackage guipackage guipackage getinstance guipackage guipackage updatecurrentnode jmeterguicomponent guipackage getgui modifytestelement guipackage getcurrentgui jmetertreenode newnode jmetertreenode testelement getproperty testelement nullproperty getpropertyasboolean testelement newnode setenabled newnode setenabled newnode setenabled insertnodeinto newnode getchildcount newnode public void remove node from parent j meter tree node node if node get user object instanceof test plan node get user object instanceof work bench super remove node from parent node removenodefromparent jmetertreenode getuserobject testplan getuserobject workbench removenodefromparent private void traverse and find class type j meter tree node node list node list if type is instance node get user object node list add node enumeration enum node node children while enum node has more elements j meter tree node child j meter tree node enum node next element traverse and find type child node list traverseandfind jmetertreenode nodelist isinstance getuserobject nodelist enumnode enumnode hasmoreelements jmetertreenode jmetertreenode enumnode nextelement traverseandfind nodelist private j meter tree node traverse and find test element user object j meter tree node node if user object node get user object return node enumeration enum node node children while enum node has more elements j meter tree node child j meter tree node enum node next element j meter tree node result traverse and find user object child if result null return result return null jmetertreenode traverseandfind testelement userobject jmetertreenode userobject getuserobject enumnode enumnode hasmoreelements jmetertreenode jmetertreenode enumnode nextelement jmetertreenode traverseandfind userobject public hash tree get current sub tree j meter tree node node listed hash tree hash tree new listed hash tree node enumeration enum node node children while enum node has more elements j meter tree node child j meter tree node enum node next element hash tree add node get current sub tree child return hash tree hashtree getcurrentsubtree jmetertreenode listedhashtree hashtree listedhashtree enumnode enumnode hasmoreelements jmetertreenode jmetertreenode enumnode nextelement hashtree getcurrentsubtree hashtree public hash tree get test plan return get current sub tree j meter tree node j meter tree node this get root get child at 0 hashtree gettestplan getcurrentsubtree jmetertreenode jmetertreenode getroot getchildat clear the test plan and use default node for test plan and workbench n b should only be called by link gui package clear test plan public void clear test plan test element tp new test plan gui create test element clear test plan tp guipackage cleartestplan cleartestplan testelement testplangui createtestelement cleartestplan clear the test plan and use specified node for test plan and default node for workbench n b should only be called by link gui package clear test plan test element param test plan the node to use as the testplan top node public void clear test plan test element test plan remove the workbench and testplan nodes int children get child count get root while children 0 j meter tree node child j meter tree node get child get root 0 super remove node from parent child children get child count get root init the tree init tree test plan new work bench gui create test element assumes this is only called from gui mode guipackage cleartestplan testelement testplan cleartestplan testelement testplan getchildcount getroot jmetertreenode jmetertreenode getchild getroot removenodefromparent getchildcount getroot inittree testplan workbenchgui createtestelement initialize the model with nodes for testplan and workbench param tp the element to use as testplan param wb the element to use as workbench private void init tree test element tp test element wb insert the test plan node insert node into new j meter tree node tp this j meter tree node get root 0 insert the workbench node insert node into new j meter tree node wb this j meter tree node get root 1 let others know that the tree content has changed this should not be necessary but without it nodes are not shown when the user uses the close menu item node structure changed j meter tree node get root inittree testelement testelement insertnodeinto jmetertreenode jmetertreenode getroot insertnodeinto jmetertreenode jmetertreenode getroot nodestructurechanged jmetertreenode getroot see command do action action event public void do action action event e doaction actionevent doaction actionevent see command get action names abstract public set get action names getactionnames getactionnames param e protected void popup should save action event e log debug popup should save if gui package get instance get test plan file null if j option pane show confirm dialog gui package get instance get main frame j meter utils get res string should save non nls 1 j meter utils get res string warning non nls 1 j option pane yes no option j option pane question message j option pane yes option action router get instance do action now new action event e get source e getid action names save popupshouldsave actionevent popupshouldsave guipackage getinstance gettestplanfile joptionpane showconfirmdialog guipackage getinstance getmainframe jmeterutils getresstring should_save jmeterutils getresstring joptionpane yes_no_option joptionpane question_message joptionpane yes_option actionrouter getinstance doactionnow actionevent getsource actionnames public class test random order controller extends j meter test case public test random order controller string name super name testrandomordercontroller jmetertestcase testrandomordercontroller public void test random order test log debug testing random order controller random order controller roc new random order controller roc add test element new test sampler zero roc add test element new test sampler one roc add test element new test sampler two roc add test element new test sampler three test element sampler null list used samplers new array list roc initialize while sampler roc next null string sampler name sampler get name if used samplers contains sampler name assert true duplicate sampler returned from next false used samplers add sampler name assert true all samplers were returned used samplers size 4 testrandomorder testlog randomordercontroller randomordercontroller randomordercontroller addtestelement testsampler addtestelement testsampler addtestelement testsampler addtestelement testsampler testelement usedsamplers arraylist samplername getname usedsamplers samplername asserttrue usedsamplers samplername asserttrue usedsamplers public void test random order no elements random order controller roc new random order controller roc initialize assert true roc next null testrandomordernoelements randomordercontroller randomordercontroller asserttrue public void test random order one element random order controller roc new random order controller roc add test element new test sampler zero test element sampler null list used samplers new array list roc initialize while sampler roc next null string sampler name sampler get name if used samplers contains sampler name assert true duplicate sampler returned from next false used samplers add sampler name assert true all samplers were returned used samplers size 1 testrandomorderoneelement randomordercontroller randomordercontroller addtestelement testsampler testelement usedsamplers arraylist samplername getname usedsamplers samplername asserttrue usedsamplers samplername asserttrue usedsamplers constructor for the j meter tree listener object public report tree listener report tree model model this model model drag icon validate drag icon set visible true jmetertreelistener reporttreelistener reporttreemodel dragicon dragicon setvisible public report tree listener drag icon validate drag icon set visible true reporttreelistener dragicon dragicon setvisible public void set model report tree model m model m setmodel reporttreemodel sets the action handler attribute of the j meter tree listener object param ah the new action handler value public void set action handler action listener ah action handler ah actionhandler jmetertreelistener actionhandler setactionhandler actionlistener actionhandler sets the j tree attribute of the j meter tree listener object param tree the new j tree value public void setj tree j tree tree this tree tree jtree jmetertreelistener jtree setjtree jtree sets the end window attribute of the j meter tree listener object param window the new end window value public void set end window container window end window window endwindow jmetertreelistener endwindow setendwindow endwindow gets the j tree attribute of the j meter tree listener object return tree the current j tree value public j tree getj tree return tree jtree jmetertreelistener jtree jtree getjtree gets the current node attribute of the j meter tree listener object return the current node value public report tree node get current node if current path null if current path get last path component null return report tree node current path get last path component else return report tree node current path get parent path get last path component else return report tree node model get root currentnode jmetertreelistener currentnode reporttreenode getcurrentnode currentpath currentpath getlastpathcomponent reporttreenode currentpath getlastpathcomponent reporttreenode currentpath getparentpath getlastpathcomponent reporttreenode getroot public report tree node get selected nodes tree path paths tree get selection paths if paths null return new report tree node get current node report tree node nodes new report tree node paths length for int i 0 i paths length i nodes i report tree node paths i get last path component return nodes reporttreenode getselectednodes treepath getselectionpaths reporttreenode getcurrentnode reporttreenode reporttreenode reporttreenode getlastpathcomponent public tree path removed selected node current path current path get parent path return current path treepath removedselectednode currentpath currentpath getparentpath currentpath public void value changed tree selection event e log debug value changed updating current path current path e get new lead selection path action handler action performed new action event this 3333 edit valuechanged treeselectionevent currentpath currentpath getnewleadselectionpath actionhandler actionperformed actionevent public void mouse clicked mouse event ev mouseclicked mouseevent public void mouse released mouse event e if dragging is valid drag action dragged nodes get current node dragging false j popup menu drag ndrop new j popup menu j menu item item new j menu item j meter utils get res string insert before item add action listener action handler item set action command report dragn drop insert before drag ndrop add item item new j menu item j meter utils get res string insert after item add action listener action handler item set action command report dragn drop insert after drag ndrop add item item new j menu item j meter utils get res string add as child item add action listener action handler item set action command report dragn drop add drag ndrop add item drag ndrop add separator item new j menu item j meter utils get res string cancel drag ndrop add item display pop up e drag ndrop else report gui package get instance get main frame repaint dragging false mousereleased mouseevent isvaliddragaction draggednodes getcurrentnode jpopupmenu dragndrop jpopupmenu jmenuitem jmenuitem jmeterutils getresstring addactionlistener actionhandler setactioncommand reportdragndrop insert_before dragndrop jmenuitem jmeterutils getresstring addactionlistener actionhandler setactioncommand reportdragndrop insert_after dragndrop jmenuitem jmeterutils getresstring addactionlistener actionhandler setactioncommand reportdragndrop dragndrop dragndrop addseparator jmenuitem jmeterutils getresstring dragndrop displaypopup dragndrop reportguipackage getinstance getmainframe public report tree node get dragged nodes return dragged nodes reporttreenode getdraggednodes draggednodes tests if the node is being dragged into one of it s own sub nodes or into itself private boolean is valid drag action report tree node source report tree node dest boolean is valid true tree node path dest get path for int i 0 i path length i if contains source path i is valid false return is valid isvaliddragaction reporttreenode reporttreenode isvalid treenode getpath isvalid isvalid public void mouse entered mouse event e mouseentered mouseevent private void change selection if dragging mouse event e if dragging report gui package get instance get main frame draw dragged component drag icon e getx e gety if tree get path for location e getx e gety null current path tree get path for location e getx e gety if contains dragged nodes get current node tree set selection path current path changeselectionifdragging mouseevent reportguipackage getinstance getmainframe drawdraggedcomponent dragicon getpathforlocation currentpath getpathforlocation draggednodes getcurrentnode setselectionpath currentpath private boolean contains object container object item for int i 0 i container length i if container i item return true return false public void mouse pressed mouse event e get the main frame report main frame main frame report gui package get instance get main frame close any main menu that is open main frame close menu int sel row tree get row for location e getx e gety if tree get path for location e getx e gety null log debug mouse pressed updating current path current path tree get path for location e getx e gety if sel row 1 update main menu j metergui component get current node get user object create popup menu if is right click e if tree get selection count 2 tree set selection path current path if get current node null log debug about to display pop up display pop up e mousepressed mouseevent reportmainframe mainframe reportguipackage getinstance getmainframe mainframe closemenu selrow getrowforlocation getpathforlocation currentpath currentpath getpathforlocation selrow updatemainmenu jmeterguicomponent getcurrentnode getuserobject createpopupmenu isrightclick getselectioncount setselectionpath currentpath getcurrentnode displaypopup public void mouse dragged mouse event e if dragging dragging true dragged nodes get selected nodes if dragged nodes 0 get user object instanceof report gui dragging false change selection if dragging e mousedragged mouseevent draggednodes getselectednodes draggednodes getuserobject reportgui changeselectionifdragging public void mouse moved mouse event e mousemoved mouseevent public void mouse exited mouse event ev mouseexited mouseevent public void key pressed key event e keypressed keyevent public void key released key event e keyreleased keyevent public void key typed key event e keytyped keyevent private boolean is right click mouse event e return e is popup trigger mouse event button2 mask e get modifiers 0 mouse event button3 mask e get modifiers isrightclick mouseevent ispopuptrigger mouseevent button2_mask getmodifiers mouseevent button3_mask getmodifiers private void display pop up mouse event e j popup menu pop get current node create popup menu report gui package get instance display pop up e pop displaypopup mouseevent jpopupmenu getcurrentnode createpopupmenu reportguipackage getinstance displaypopup private void display pop up mouse event e j popup menu popup log warn shouldn t be here if popup null popup pack popup show tree e getx e gety popup set visible true popup request focus displaypopup mouseevent jpopupmenu setvisible requestfocus private map post action listeners new hash map private action router postactionlisteners hashmap actionrouter public void action performed final action event e swing utilities invoke later new runnable public void run perform action e actionperformed actionevent swingutilities invokelater performaction public void action performed final action event e swing utilities invoke later new runnable public void run perform action e actionperformed actionevent swingutilities invokelater performaction private void perform action final action event e string action command e get action command try try gui package get instance update current gui catch exception err log error perform action action command update current gui on e to string caused err j meter utils report error to user problem updating gui see log file for details set command objects set commands get action command iterator iter command objects iterator while iter has next try command c command iter next pre action performed c get class e c do action e post action performed c get class e catch illegal user action exception err j meter utils report error to user err to string catch exception err log error err catch null pointer exception er log error perform action action command e to string caused er j meter utils report error to user sorry this feature action command not yet implemented performaction actionevent actioncommand getactioncommand guipackage getinstance updatecurrentgui performaction actioncommand updatecurrentgui tostring jmeterutils reporterrortouser commandobjects actioncommand commandobjects hasnext preactionperformed getclass doaction postactionperformed getclass illegaluseractionexception jmeterutils reporterrortouser tostring nullpointerexception performaction actioncommand tostring jmeterutils reporterrortouser actioncommand to execute an action immediately in the current thread param e the action to execute public void do action now action event e perform action e doactionnow actionevent performaction public set get action string action name set set new hash set set command objects set commands get action name iterator iter command objects iterator while iter has next try set add iter next catch exception err log error err return set getaction actionname hashset commandobjects actionname commandobjects hasnext public command get action string action name class action class set command objects set commands get action name iterator iter command objects iterator while iter has next try command com command iter next if com get class equals action class return com catch exception err log error err return null getaction actionname actionclass commandobjects actionname commandobjects hasnext getclass actionclass public command get action string action name string class name set command objects set commands get action name iterator iter command objects iterator while iter has next try command com command iter next if com get class get name equals class name return com catch exception err log error err return null getaction actionname classname commandobjects actionname commandobjects hasnext getclass getname classname allows an action listener to receive notification of a command being executed prior to the actual execution of the command param action the class of the command for which the listener will notifications for class must extend org apache jmeter gui action command param listener the action listener to receive the notifications public void add pre action listener class action action listener listener if action null hash set set hash set pre action listeners get action get name if set null set new hash set set add listener pre action listeners put action get name set actionlistener actionlistener addpreactionlistener actionlistener hashset hashset preactionlisteners getname hashset preactionlisteners getname allows an action listener to be removed from receiving notifications of a command being executed prior to the actual execution of the command param action the class of the command for which the listener will notifications for class must extend org apache jmeter gui action command param listener the action listener to receive the notifications public void remove pre action listener class action action listener listener if action null hash set set hash set pre action listeners get action get name if set null set remove listener pre action listeners put action get name set actionlistener actionlistener removepreactionlistener actionlistener hashset hashset preactionlisteners getname preactionlisteners getname allows an action listener to receive notification of a command being executed after the command has executed param action the class of the command for which the listener will notifications for class must extend org apache jmeter gui action command param listener public void add post action listener class action action listener listener if action null hash set set hash set post action listeners get action get name if set null set new hash set set add listener post action listeners put action get name set actionlistener addpostactionlistener actionlistener hashset hashset postactionlisteners getname hashset postactionlisteners getname allows an action listener to be removed from receiving notifications of a command being executed after the command has executed param action the class of the command for which the listener will notifications for class must extend org apache jmeter gui action command param listener public void remove post action listener class action action listener listener if action null hash set set hash set post action listeners get action get name if set null set remove listener post action listeners put action get name set actionlistener removepostactionlistener actionlistener hashset hashset postactionlisteners getname postactionlisteners getname protected void pre action performed class action action event e if action null hash set listener set hash set pre action listeners get action get name if listener set null listener set size 0 object listeners listener set to array for int i 0 i listeners length i action listener listeners i action performed e preactionperformed actionevent hashset listenerset hashset preactionlisteners getname listenerset listenerset listenerset toarray actionlistener actionperformed protected void post action performed class action action event e if action null hash set listener set hash set post action listeners get action get name if listener set null listener set size 0 object listeners listener set to array for int i 0 i listeners length i action listener listeners i action performed e postactionperformed actionevent hashset listenerset hashset postactionlisteners getname listenerset listenerset listenerset toarray actionlistener actionperformed private void populate command map list list classes command command iterator iter classes class command class try list classes class finder find classes that extend j meter utils get search paths new class class for name org apache jmeter gui action command commands new hash map list classes size if list classes size 0 log fatal error uh oh didn t find any action handlers throw new j meter error no action handlers found check j meter home and libraries iter classes list classes iterator while iter classes has next string str class name string iter classes next if str class name starts with org apache jmeter gui command class class for name str class name if modifier is abstract command class get modifiers command command command class new instance iterator iter command get action names iterator while iter has next string command name string iter next set command objects set commands get command name if command objects null command objects new hash set commands put command name command objects command objects add command catch headless exception e log warn e to string catch j meter error e throw e catch exception e log error exception finding action handlers e populatecommandmap listclasses iterclasses commandclass listclasses classfinder findclassesthatextend jmeterutils getsearchpaths forname hashmap listclasses listclasses fatalerror jmetererror jmeterhome iterclasses listclasses iterclasses hasnext strclassname iterclasses strclassname startswith commandclass forname strclassname isabstract commandclass getmodifiers commandclass newinstance getactionnames hasnext commandname commandobjects commandname commandobjects commandobjects hashset commandname commandobjects commandobjects headlessexception tostring jmetererror gets the instance attribute of the action router class return the instance value public static action router get instance if router null router new action router router populate command map return router actionrouter actionrouter getinstance actionrouter populatecommandmap public class report cell renderer extends default tree cell renderer public report cell renderer reportcellrenderer defaulttreecellrenderer reportcellrenderer public component get tree cell renderer component j tree tree object value boolean sel boolean expanded boolean leaf int row boolean p hasfocus super get tree cell renderer component tree report tree node value get name sel expanded leaf row p hasfocus boolean enabled report tree node value is enabled image icon ic report tree node value get icon enabled if ic null if enabled set icon ic else set disabled icon ic else if enabled i e no disabled icon found must therefore set the enabled icon so there is at least some icon ic report tree node value get icon if ic null set icon ic this set enabled enabled return this gettreecellrenderercomponent jtree p_hasfocus gettreecellrenderercomponent reporttreenode getname p_hasfocus reporttreenode isenabled imageicon reporttreenode geticon seticon setdisabledicon reporttreenode geticon seticon setenabled get look and feel classname from the following properties ul li jmeter laf lt os name lowercased spaces replaced by li li jmeter laf lt os family lowercased li li jmeter laf li li ui manager get cross platform look and feel class name li ul return laf classname private static string getj meter laf string os name system get property os name non nls 1 to lower case locale english string laf spaces are not allowed in property names read from files laf j meter utils get property jmeter laf os name replace if laf null return check laf name laf string os family os name split s e g windows xp windows laf j meter utils get property jmeter laf os family 0 if laf null return check laf name laf laf j meter utils get property jmeter laf if laf null return check laf name laf return ui manager get cross platform look and feel class name lookandfeel _ uimanager getcrossplatformlookandfeelclassname getjmeterlaf osname getproperty tolowercase jmeterutils getproperty jmeter_laf osname _ checklafname osfamily osname jmeterutils getproperty jmeter_laf osfamily checklafname jmeterutils getproperty jmeter_laf checklafname uimanager getcrossplatformlookandfeelclassname check if laf is a built in one private static string check laf name string laf if system equals ignore case laf non nls 1 return ui manager get system look and feel class name if crossplatform equals ignore case laf non nls 1 return ui manager get cross platform look and feel class name return laf checklafname equalsignorecase uimanager getsystemlookandfeelclassname equalsignorecase uimanager getcrossplatformlookandfeelclassname public look and feel command lookandfeelcommand public void do action action event ev try string class name ev get action command substring 4 replace ui manager set look and feel class name swing utilities update component treeui gui package get instance get main frame catch javax swing unsupported look and feel exception e j meter utils report error to user look and feel unavailable e to string catch instantiation exception e j meter utils report error to user look and feel unavailable e to string catch class not found exception e j meter utils report error to user look and feel unavailable e to string catch illegal access exception e j meter utils report error to user look and feel unavailable e to string doaction actionevent classname getactioncommand uimanager setlookandfeel classname swingutilities updatecomponenttreeui guipackage getinstance getmainframe unsupportedlookandfeelexception jmeterutils reporterrortouser tostring instantiationexception jmeterutils reporterrortouser tostring classnotfoundexception jmeterutils reporterrortouser tostring illegalaccessexception jmeterutils reporterrortouser tostring public set get action names return commands getactionnames public monitor handler super monitorhandler set the object factory used to create new param factory public void set object factory object factory factory this factory factory objectfactory setobjectfactory objectfactory public void start document throws sax exception this start doc true startdocument saxexception startdoc public void end document throws sax exception this start doc false this end doc true enddocument saxexception startdoc enddoc receive notification of the start of an element p by default do nothing application writers may override this method in a subclass to take specific actions at the start of each element such as allocating a new tree node or writing output to a file p param uri param local name the element type name param q name param attributes the specified or defaulted attributes exception org xml sax sax exception any sax exception possibly wrapping another exception see org xml sax content handler start element public void start element string uri string local name string q name attributes attributes throws sax exception if q name equals constants status status factory create status stacktree push status else if q name equals constants jvm jvm factory create jvm if stacktree peek instanceof status status set jvm jvm stacktree push jvm else if q name equals constants memory memory factory create memory if stacktree peek instanceof jvm stacktree push memory if attributes null for int idx 0 idx attributes get length idx string attr attributes getq name idx if attr equals constants memory free memory set free parse long attributes get value idx else if attr equals constants memory total memory set total parse long attributes get value idx else if attr equals constants memory max memory set max parse long attributes get value idx jvm set memory memory else if q name equals constants connector connector factory create connector if stacktree peek instanceof status stacktree peek instanceof connector status add connector connector stacktree push connector if attributes null for int idx 0 idx attributes get length idx string attr attributes getq name idx if attr equals constants attribute name connector set name attributes get value idx else if q name equals constants threadinfo threadinfo factory create thread info if stacktree peek instanceof connector stacktree push threadinfo connector set thread info threadinfo if attributes null for int idx 0 idx attributes get length idx string attr attributes getq name idx if attr equals constants maxthreads threadinfo set max threads parse int attributes get value idx else if attr equals constants minsparethreads threadinfo set min spare threads parse int attributes get value idx else if attr equals constants maxsparethreads threadinfo set max spare threads parse int attributes get value idx else if attr equals constants currentthreadcount threadinfo set current thread count parse int attributes get value idx else if attr equals constants currentbusythreads threadinfo set current threads busy parse int attributes get value idx else if q name equals constants requestinfo requestinfo factory create request info if stacktree peek instanceof connector stacktree push requestinfo connector set request info requestinfo if attributes null for int idx 0 idx attributes get length idx string attr attributes getq name idx if attr equals constants maxtime requestinfo set max time parse int attributes get value idx else if attr equals constants processingtime requestinfo set processing time parse int attributes get value idx else if attr equals constants requestcount requestinfo set request count parse int attributes get value idx else if attr equals constants errorcount requestinfo set error count parse int attributes get value idx else if attr equals constants bytesreceived requestinfo set bytes received parse long attributes get value idx else if attr equals constants bytessent requestinfo set bytes sent parse long attributes get value idx else if q name equals constants workers workers factory create workers if stacktree peek instanceof connector connector set workers workers stacktree push workers else if q name equals constants worker worker factory create worker if stacktree peek instanceof workers stacktree peek instanceof worker stacktree push worker workers impl workers add worker worker if attributes null for int idx 0 idx attributes get length idx string attr attributes getq name idx if attr equals constants stage worker set stage attributes get value idx else if attr equals constants requestprocessingtime worker set request processing time parse int attributes get value idx else if attr equals constants requestbytessent worker set request bytes sent parse long attributes get value idx else if attr equals constants requestbytesreceived worker set request bytes received parse long attributes get value idx else if attr equals constants remoteaddr worker set remote addr attributes get value idx else if attr equals constants virtualhost worker set virtual host attributes get value idx else if attr equals constants method worker set method attributes get value idx else if attr equals constants currenturi worker set current uri attributes get value idx else if attr equals constants currentquerystring worker set current query string attributes get value idx else if attr equals constants protocol worker set protocol attributes get value idx localname qname saxexception contenthandler startelement startelement localname qname saxexception qname createstatus qname createjvm setjvm qname creatememory getlength getqname memory_free setfree parselong getvalue memory_total settotal parselong getvalue memory_max setmax parselong getvalue setmemory qname createconnector addconnector getlength getqname attribute_name setname getvalue qname createthreadinfo setthreadinfo getlength getqname setmaxthreads parseint getvalue setminsparethreads parseint getvalue setmaxsparethreads parseint getvalue setcurrentthreadcount parseint getvalue setcurrentthreadsbusy parseint getvalue qname createrequestinfo setrequestinfo getlength getqname setmaxtime parseint getvalue setprocessingtime parseint getvalue setrequestcount parseint getvalue seterrorcount parseint getvalue setbytesreceived parselong getvalue setbytessent parselong getvalue qname createworkers setworkers qname createworker workersimpl addworker getlength getqname setstage getvalue setrequestprocessingtime parseint getvalue setrequestbytessent parselong getvalue setrequestbytesreceived parselong getvalue setremoteaddr getvalue setvirtualhost getvalue setmethod getvalue setcurrenturi getvalue setcurrentquerystring getvalue setprotocol getvalue receive notification of the end of an element p by default do nothing application writers may override this method in a subclass to take specific actions at the end of each element such as finalising a tree node or writing output to a file p param uri param local name the element type name param q name the specified or defaulted attributes exception org xml sax sax exception any sax exception possibly wrapping another exception see org xml sax content handler end element public void end element string uri string local name string q name throws sax exception if q name equals constants status if stacktree peek instanceof status stacktree pop else if q name equals constants jvm if stacktree peek instanceof jvm stacktree pop else if q name equals constants memory if stacktree peek instanceof memory stacktree pop else if q name equals constants connector if stacktree peek instanceof connector stacktree peek instanceof connector stacktree pop else if q name equals constants threadinfo if stacktree peek instanceof thread info stacktree pop else if q name equals constants requestinfo if stacktree peek instanceof request info stacktree pop else if q name equals constants workers if stacktree peek instanceof workers stacktree pop else if q name equals constants worker if stacktree peek instanceof worker stacktree peek instanceof worker stacktree pop localname qname saxexception contenthandler endelement endelement localname qname saxexception qname qname qname qname qname threadinfo qname requestinfo qname qname receive notification of character data inside an element p by default do nothing application writers may override this method to take specific actions for each chunk of character data such as adding the data to a node or buffer or printing it to a file p param ch the characters param start the start position in the character array param length the number of characters to use from the character array exception org xml sax sax exception any sax exception possibly wrapping another exception see org xml sax content handler characters public void characters char ch int start int length throws sax exception saxexception contenthandler saxexception convienance method for parsing long if the string was not a number the method returns zero param data return the value as a long public long parse long string data long val 0 if data length 0 try val long parse long data catch number format exception e val 0 return val parselong parselong numberformatexception convienance method for parsing integers param data return the value as an integer public int parse int string data int val 0 if data length 0 try val integer parse int data catch number format exception e val 0 return val parseint parseint numberformatexception method returns the status object return the status public status get contents return this status getcontents keeping track of which row is next to be read private int next row probably does not need to be synch always accessed through thread local int get next row give access to test code return next row nextrow threadlocal getnextrow nextrow public x path file container string file string xpath throws file not found exception io exception parser configuration exception sax exception transformer exception log debug x path file xpath xpath file name file this xpath xpath next row 0 node list load xpathfilecontainer filenotfoundexception ioexception parserconfigurationexception saxexception transformerexception xpath filename nextrow nodelist private node list load throws io exception file not found exception parser configuration exception sax exception transformer exception input stream fis null node list nl null try document builder builder document builder factory new instance new document builder fis new file input stream file name nl x pathapi select node list builder parse fis xpath log debug found nl get length catch file not found exception e log warn e to string throw e catch io exception e log warn e to string throw e catch parser configuration exception e log warn e to string throw e catch sax exception e log warn e to string throw e catch transformer exception e log warn e to string throw e finally j orphan utils close quietly fis return nl nodelist ioexception filenotfoundexception parserconfigurationexception saxexception transformerexception inputstream nodelist documentbuilder documentbuilderfactory newinstance newdocumentbuilder fileinputstream filename xpathapi selectnodelist getlength filenotfoundexception tostring ioexception tostring parserconfigurationexception tostring saxexception tostring transformerexception tostring jorphanutils closequietly public string getx path string int num return node list item num get node value getxpathstring nodelist getnodevalue returns the next row to the caller and updates it allowing for wrap round return the first free unread row public int next row int row next row next row if next row size 0 based next row 0 log debug new string buffer row append row to string return row nextrow nextrow nextrow nextrow nextrow stringbuffer tostring public int size return node list null 1 node list get length nodelist nodelist getlength return the file name for this class public string get file name return file name getfilename filename return returns the sample results public collection get sample results return calculated results sampleresults getsampleresults calculatedresults param results the sample results to set public void set sample results collection results this calculated results results sampleresults setsampleresults calculatedresults return returns the test start time public long get test start time return test start time teststarttime getteststarttime teststarttime param test start time the test start time to set public void set test start time long test start time this test start time test start time teststarttime teststarttime setteststarttime teststarttime teststarttime teststarttime return returns the version public string get version return version getversion param version the version to set public void set version string version this version version setversion private static final logger log logging manager get logger for class private plugin manager loggingmanager getloggerforclass pluginmanager installs a plugin param plugin the plugin to install param use gui indication of whether or not the gui will be used public static void install j meter plugin plugin boolean use gui if use gui instance install plugin plugin usegui jmeterplugin usegui usegui installplugin private void install plugin j meter plugin plugin string icons plugin get icon mappings class loader classloader plugin get class get class loader for int i 0 i icons length i url resource classloader get resource icons i 1 trim if resource null log warn can t find icon for icons i 0 icons i 1 else gui factory register icon icons i 0 new image icon resource if icons i length 2 icons i 2 null url resource2 classloader get resource icons i 2 trim if resource2 null log info can t find disabled icon for icons i 0 icons i 2 else gui factory register disabled icon icons i 0 new image icon resource2 installplugin jmeterplugin geticonmappings classloader getclass getclassloader getresource guifactory registericon imageicon getresource guifactory registerdisabledicon imageicon constructor for post writer uses the post writer boundary as the boundary string public post writer this boundary postwriter postwriter postwriter constructor for post writer param boundary the boundary string to use as marker between multipart parts public post writer string boundary this boundary boundary postwriter postwriter send post data from entry to the open connection return the post body sent actual file content is not returned it is just shown as a placeholder text actual file content public string send post data url connection connection http sampler sampler throws io exception buffer to hold the post body except file content string buffer posted body new string buffer 1000 http file arg files sampler gethttp files string content encoding sampler get content encoding if content encoding null content encoding length 0 content encoding encoding check if we should do a multipart form data or an application x www form urlencoded post request if sampler get use multipart for post output stream out connection get output stream write the form data post body which we have constructed in the set headers this contains the multipart start divider and any form data i e arguments out write form data post body retrieve the formatted data using the same encoding used to create it posted body append new string form data post body content encoding add any files for int i 0 i files length i http file arg file files i first write the start multipart file byte header file get header get bytes todo what encoding should be used here out write header retrieve the formatted data using the same encoding used to create it posted body append new string header write the actual file content write file to stream file get path out we just add placeholder text for file content posted body append actual file content not shown here non nls 1 write the end of multipart file byte file multipart end divider get file multipart end divider out write file multipart end divider retrieve the formatted data using the same encoding used to create it posted body append new string file multipart end divider encoding if i 1 files length out write crlf posted body append new string crlf write end of multipart byte multipart end divider get multipart end divider out write multipart end divider posted body append new string multipart end divider encoding out flush out close else if there are no arguments we can send a file as the body of the request if sampler get arguments null sampler has arguments sampler get send file as post body output stream out connection get output stream we re sure that there is at least one file because of get send file as post body method s return value http file arg file files 0 write file to stream file get path out out flush out close we just add placeholder text for file content posted body append actual file content not shown here non nls 1 else if form data url encoded null may be null for put in an application x www form urlencoded request we only support parameters no file upload is allowed output stream out connection get output stream out write form data url encoded out flush out close posted body append new string form data url encoded content encoding return posted body to string sendpostdata urlconnection httpsampler ioexception stringbuffer postedbody stringbuffer httpfilearg gethttpfiles contentencoding getcontentencoding contentencoding contentencoding contentencoding getusemultipartforpost outputstream getoutputstream setheaders formdatapostbody postedbody formdatapostbody contentencoding httpfilearg getheader getbytes postedbody writefiletostream getpath postedbody filemultipartenddivider getfilemultipartenddivider filemultipartenddivider postedbody filemultipartenddivider postedbody multipartenddivider getmultipartenddivider multipartenddivider postedbody multipartenddivider getarguments hasarguments getsendfileaspostbody outputstream getoutputstream getsendfileaspostbody httpfilearg writefiletostream getpath postedbody formdataurlencoded outputstream getoutputstream formdataurlencoded postedbody formdataurlencoded contentencoding postedbody tostring public void set headers url connection connection http sampler sampler throws io exception get the encoding to use for the request string content encoding sampler get content encoding if content encoding null content encoding length 0 content encoding encoding long content length 0l http file arg files sampler gethttp files check if we should do a multipart form data or an application x www form urlencoded post request if sampler get use multipart for post set the content type connection set request property http constants header content type http constants multipart form data boundary get boundary non nls 1 write the form section byte array output stream bos new byte array output stream first the multipart start divider bos write get multipart divider add any parameters property iterator args sampler get arguments iterator while args has next http argument arg http argument args next get object value string parameter name arg get name if arg is skippable parameter name continue end the previous multipart bos write crlf write multipart for parameter write form multipart bos parameter name arg get value content encoding if there are any files we need to end the previous multipart if files length 0 end the previous multipart bos write crlf bos flush keep the content will be sent later form data post body bos to byte array bos close content length form data post body length now we just construct any multipart for the files we only construct the file multipart start we do not write the actual file content for int i 0 i files length i http file arg file files i write multipart for file bos new byte array output stream write start file multipart bos file get path file get param name file get mime type bos flush string header bos to string content encoding todo is this correct if this is not the first file we can t write its header now for simplicity we always save it even if there is only one file file set header header bos close content length header length add also the length of the file content file upload file new file file get path content length upload file length and the end of the file multipart content length get file multipart end divider length if i 1 files length content length crlf length add the end of multipart content length get multipart end divider length set the content length connection set request property http constants header content length long to string content length make the connection ready for sending post data connection set do output true connection set do input true else check if the header manager had a content type header this allows the user to specify his own content type for a post request string content type header connection get request property http constants header content type boolean has content type header content type header null content type header length 0 if there are no arguments we can send a file as the body of the request if sampler get arguments null sampler get arguments get argument count 0 sampler get send file as post body we re sure that there is one file because of get send file as post body method s return value http file arg file files 0 if has content type header allow the mimetype of the file to control the content type if file get mime type null file get mime type length 0 connection set request property http constants header content type file get mime type else connection set request property http constants header content type http constants application x www form urlencoded create the content length we are going to write file input file new file file get path content length input file length else we create the post body content now so we know the size byte array output stream bos new byte array output stream if none of the arguments have a name specified we just send all the values as the post body string post body null if sampler get send parameter values as post body set the content type if has content type header connection set request property http constants header content type http constants application x www form urlencoded it is a normal post request with parameter names and values post body sampler get query string content encoding else allow the mimetype of the file to control the content type this is not obvious in gui if you are not uploading any files but just sending the content of nameless parameters todo needs a multiple file upload scenerio if has content type header http file arg file files length 0 files 0 null if file null file get mime type null file get mime type length 0 connection set request property http constants header content type file get mime type else todo is this the correct default connection set request property http constants header content type http constants application x www form urlencoded just append all the parameter values and use that as the post body string buffer post body buffer new string buffer property iterator args sampler get arguments iterator while args has next http argument arg http argument args next get object value post body buffer append arg get encoded value content encoding post body post body buffer to string bos write post body get bytes content encoding bos flush bos close keep the content will be sent later form data url encoded bos to byte array content length bos to byte array length set the content length connection set request property http constants header content length long to string content length make the connection ready for sending post data connection set do output true setheaders urlconnection httpsampler ioexception contentencoding getcontentencoding contentencoding contentencoding contentencoding contentlength httpfilearg gethttpfiles getusemultipartforpost setrequestproperty httpconstants header_content_type httpconstants multipart_form_data getboundary bytearrayoutputstream bytearrayoutputstream getmultipartdivider propertyiterator getarguments hasnext httpargument httpargument getobjectvalue parametername getname isskippable parametername writeformmultipart parametername getvalue contentencoding formdatapostbody tobytearray contentlength formdatapostbody httpfilearg bytearrayoutputstream writestartfilemultipart getpath getparamname getmimetype tostring contentencoding setheader contentlength uploadfile getpath contentlength uploadfile contentlength getfilemultipartenddivider contentlength contentlength getmultipartenddivider setrequestproperty httpconstants header_content_length tostring contentlength setdooutput setdoinput contenttypeheader getrequestproperty httpconstants header_content_type hascontenttypeheader contenttypeheader contenttypeheader getarguments getarguments getargumentcount getsendfileaspostbody getsendfileaspostbody httpfilearg hascontenttypeheader getmimetype getmimetype setrequestproperty httpconstants header_content_type getmimetype setrequestproperty httpconstants header_content_type httpconstants application_x_www_form_urlencoded inputfile getpath contentlength inputfile bytearrayoutputstream bytearrayoutputstream postbody getsendparametervaluesaspostbody hascontenttypeheader setrequestproperty httpconstants header_content_type httpconstants application_x_www_form_urlencoded postbody getquerystring contentencoding hascontenttypeheader httpfilearg getmimetype getmimetype setrequestproperty httpconstants header_content_type getmimetype setrequestproperty httpconstants header_content_type httpconstants application_x_www_form_urlencoded stringbuffer postbodybuffer stringbuffer propertyiterator getarguments hasnext httpargument httpargument getobjectvalue postbodybuffer getencodedvalue contentencoding postbody postbodybuffer tostring postbody getbytes contentencoding formdataurlencoded tobytearray contentlength tobytearray setrequestproperty httpconstants header_content_length tostring contentlength setdooutput get the boundary string used to separate multiparts return the boundary string protected string get boundary return boundary getboundary get the bytes used to separate multiparts encoded using encoding return the bytes used to separate multiparts throws io exception private byte get multipart divider throws io exception return dash dash get boundary get bytes encoding ioexception getmultipartdivider ioexception dash_dash getboundary getbytes get the bytes used to end a file multipart encoded using encoding return the bytes used to end a file multipart throws io exception private byte get file multipart end divider throws io exception byte ending get multipart divider byte complete ending new byte ending length crlf length system arraycopy crlf 0 complete ending 0 crlf length system arraycopy ending 0 complete ending crlf length ending length return complete ending ioexception getfilemultipartenddivider ioexception getmultipartdivider completeending completeending completeending completeending get the bytes used to end the multipart request return the bytes used to end the multipart request private byte get multipart end divider byte ending dash dash bytes byte complete ending new byte ending length crlf length system arraycopy ending 0 complete ending 0 ending length system arraycopy crlf 0 complete ending ending length crlf length return complete ending getmultipartenddivider dash_dash_bytes completeending completeending completeending completeending write the start of a file multipart up to the point where the actual file content should be written private void write start file multipart output stream out string filename string name field string mimetype throws io exception write out content disposition form data name non nls 1 write out name field write out filename non nls 1 write out new file filename get name writeln out non nls 1 writeln out content type mimetype non nls 1 writeln out content transfer encoding binary non nls 1 out write crlf writestartfilemultipart outputstream namefield ioexception namefield getname write the content of a file to the output stream param filename the filename of the file to write to the stream param out the stream to write to throws io exception private void write file to stream string filename output stream out throws io exception byte buf new byte 1024 1k the previous 100k made no sense there s tons of buffers elsewhere in the chain and it caused oom when many concurrent uploads were being done could be fixed by increasing the evacuation ratio in bin jmeter bat but this is better input stream in new buffered input stream new file input stream filename int read try while read in read buf 0 out write buf 0 read finally in close ioexception writefiletostream outputstream ioexception inputstream bufferedinputstream fileinputstream writes form data in multipart format private void write form multipart output stream out string name string value string char set throws io exception writeln out content disposition form data name name non nls 1 non nls 2 writeln out content type text plain charset char set non nls 1 writeln out content transfer encoding 8bit non nls 1 out write crlf out write value get bytes char set out write crlf write boundary end marker out write get multipart divider writeformmultipart outputstream charset ioexception charset getbytes charset getmultipartdivider private void write output stream out string value throws unsupported encoding exception io exception out write value get bytes encoding outputstream unsupportedencodingexception ioexception getbytes private void writeln output stream out string value throws unsupported encoding exception io exception out write value get bytes encoding out write crlf outputstream unsupportedencodingexception ioexception getbytes private on error panel error panel public result action gui super init onerrorpanel errorpanel resultactiongui see org apache jmeter gui j metergui component get static label public string get label resource return resultaction title non nls 1 jmeterguicomponent getstaticlabel getlabelresource resultaction_title see org apache jmeter gui j metergui component configure test element public void configure test element el super configure el error panel configure on error test element el get error action jmeterguicomponent testelement testelement errorpanel onerrortestelement geterroraction see org apache jmeter gui j metergui component create test element public test element create test element result action result action new result action modify test element result action return result action jmeterguicomponent createtestelement testelement createtestelement resultaction resultaction resultaction modifytestelement resultaction resultaction modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element te super configure test element te on error test element te set error action error panel get on error setting testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement onerrortestelement seterroraction errorpanel getonerrorsetting implements j metergui component clear gui public void clear gui super clear gui error panel configure on error test element on error continue jmeterguicomponent cleargui cleargui cleargui errorpanel onerrortestelement on_error_continue private void init set layout new border layout set border make border box box box create vertical box box add make title panel error panel new on error panel box add error panel add box border layout north setlayout borderlayout setborder makeborder createverticalbox maketitlepanel errorpanel onerrorpanel errorpanel borderlayout constructor takes no arguments public data header new array list data new hash map current pos 1 size current pos 1 arraylist hashmap currentpos currentpos replaces the given header name with a new header name param old header old header name param new header new header name public void replace header string old header string new header list temp list int index header index of old header header set index new header temp list list data remove old header data put new header temp list oldheader newheader replaceheader oldheader newheader templist indexof oldheader newheader templist oldheader newheader templist adds the rows of the given data object to this data object param d data object to be appended to this one public void append data d boolean valid true string headers get headers string d headers d get headers if headers length d headers length valid false else for int count 0 count d headers length count if header contains d headers count valid false if valid current pos size d reset while d next for int count 0 count headers length count add column value headers count d get column value headers count getheaders dheaders getheaders dheaders dheaders dheaders currentpos addcolumnvalue getcolumnvalue get the number of the current row return integer representing the current row public int get current pos return current pos getcurrentpos currentpos removes the current row public void remove row list temp list iterator it data key set iterator log debug removing row size size if current pos 1 current pos size log debug got to here while it has next temp list list data get it next temp list remove current pos if current pos 0 current pos size removerow templist keyset currentpos currentpos hasnext templist templist currentpos currentpos currentpos public void remove row int index log debug removing row index if index size set current pos index log debug setting currentpos to index remove row removerow setcurrentpos removerow public void add row string headers get headers list temp list new array list for int i 0 i headers length i if temp list array list data get header get i null temp list new array list data put headers i temp list temp list add size temp list size set current pos size 1 addrow getheaders templist arraylist templist arraylist templist arraylist templist templist templist setcurrentpos sets the current pos if value sent to method is not a valid number the current position is set to one higher than the maximum param r position to set to public void set current pos int r current pos r setcurrentpos currentpos sorts the data using a given row as the sorting criteria a boolean value indicates whether to sort ascending or descending param column name of column to use as sorting criteria param asc boolean value indicating whether to sort ascending or descending true for asc false for desc currently this feature is not enabled and all sorts are asc public void sort string column boolean asc sort data column 0 size sortdata private void swap rows int row1 int row2 list temp object o iterator it data key set iterator while it has next temp list data get it next o temp get row1 temp set row1 temp get row2 temp set row2 o swaprows keyset hasnext private method that implements the quicksort algorithm to sort the rows of the data object param column name of column to use as sorting criteria param start starting index for quicksort algorithm param end ending index for quicksort algorithm private void sort data string column int start int end int x start y end 1 string basis list data get column get x y 2 to string if x y return while x y while x end list data get column get x to string compare to basis 0 x while y start 1 list data get column get y to string compare to basis 0 y if x y swap rows x y x y if x y x y end x if x 0 sort data column start x if y 0 sort data column x end sortdata tostring tostring compareto tostring compareto swaprows sortdata sortdata gets the number of rows in the data object return number of rows in data object public int size return size adds a value into the data set at the current row using a column name to find the column in which to insert the new value param column the name of the column to set param value value to set into column public void add column value string column object value array list temp list if temp list array list data get column null temp list new array list data put column temp list int s temp list size if current pos 1 current pos size if current pos size size current pos 1 while current pos s s temp list add null if current pos s temp list add value else temp list set current pos value addcolumnvalue arraylist templist templist arraylist templist arraylist templist templist currentpos currentpos currentpos currentpos currentpos templist currentpos templist templist currentpos returns the row number where a certain value is param column column to be searched for value param value object in search of return row where value exists public int find value string column object value list list list data get column int ret 1 ret list index of value return ret findvalue indexof sets the value in the data set at the current row using a column name to find the column in which to insert the new value param column the name of the column to set param value value to set into column public void set column value string column object value list temp list if temp list list data get column null temp list new array list data put column temp list if current pos 1 current pos 0 if current pos size size temp list add value else if current pos temp list size temp list add value else temp list set current pos value setcolumnvalue templist templist templist arraylist templist currentpos currentpos currentpos templist currentpos templist templist templist currentpos checks to see if a column exists in the data object param column name of column header to check for return true or false depending on whether the column exists public boolean has header string column return data contains key column hasheader containskey sets the current position of the data set to the next row return true if there is another row false if there are no more rows public boolean next return current pos size currentpos gets a data object from a result set param rs result set passed in from a database query return a data object throws java sql sql exception public static data get data from result set result set rs throws sql exception result set meta data meta rs get meta data data data new data int num columns meta get column count string db cols new string num columns for int i 0 i num columns i db cols i meta get column name i 1 data add header db cols i while rs next data next for int i 0 i num columns i object o rs get object i 1 if o instanceof byte o new string byte o data add column value db cols i o return data resultset resultset sqlexception getdatafromresultset resultset sqlexception resultsetmetadata getmetadata numcolumns getcolumncount dbcols numcolumns numcolumns dbcols getcolumnname addheader dbcols numcolumns getobject addcolumnvalue dbcols sets the current position of the data set to the previous row return true if there is another row false if there are no more rows public boolean previous return current pos 0 currentpos resets the current position of the data set to just before the first element public void reset current pos 1 currentpos gets the value in the current row of the given column param column name of the column return an object which holds the value of the column public object get column value string column try if current pos size return list data get column get current pos else return null catch exception e return null getcolumnvalue currentpos currentpos gets the value in the current row of the given column param column index of the column starts at 0 return an object which holds the value of the column public object get column value int column string column name string header get column try if current pos size return list data get column name get current pos else return null catch exception e return null getcolumnvalue columnname currentpos columnname currentpos public object get column value int column int row set current pos row return get column value column getcolumnvalue setcurrentpos getcolumnvalue public void remove column int col string column name string header get col data remove column name header remove column name removecolumn columnname columnname columnname sets the headers for the data set each header represents a column of data each row s data can be gotten with the column header name which will always be a string param h array of strings representing the column headers these must be distinct duplicates will cause incorrect behaviour public void set headers string h int x 0 header new array list h length for x 0 x h length x header add h x data put h x new array list setheaders arraylist arraylist returns a string array of the column headers return array of strings of the column headers public string get headers string r new string header size if r length 0 r string header to array r return r getheaders toarray public int get header count return header size getheadercount this method will retrieve every entry in a certain column it returns an array of objects from the column param column name name of the column return array of objects representing the data public list get column as object array string column name return list data get column name columnname getcolumnasobjectarray columnname columnname this method will retrieve every entry in a certain column it returns an array of strings from the column even if the data are not strings they will be returned as strings in this method param column name name of the column return array of strings representing the data public string get column string column name string return value object o list temp list data get column name if temp null return value new string temp size iterator it temp iterator int index 0 while it has next o it next if o null if o instanceof string return value index string o else return value index o to string else return value new string 0 return return value columnname getcolumn columnname returnvalue columnname returnvalue hasnext returnvalue returnvalue tostring returnvalue returnvalue use this method to set the entire data set it takes an array of strings it uses the first row as the headers and the next rows as the data elements delimiter represents the delimiting character s that separate each item in a data row param contents array of strings the first element is a list of the column headers the next elements each represent a single row of data param delimiter the delimiter character that separates columns within the string array public void set data string contents string delimiter set headers j orphan utils split contents 0 delimiter int x 1 while x contents length set line j orphan utils split contents x delimiter setdata setheaders jorphanutils setline jorphanutils sets the data for every row in the column public void set column data string col name object value list list this get column as object array col name while list size size list add value setcolumndata colname getcolumnasobjectarray colname public void set column data int col list data reset iterator iter data iterator string column name string header get col while iter has next next set column value column name iter next setcolumndata columnname hasnext setcolumnvalue columnname adds a header name to the data object param s name of header public void add header string s header add s data put s new array list math max size 100 addheader arraylist sets a row of data using an array of strings as input each value in the array represents a column s value in that row assumes the order will be the same order in which the headers were added to the data set param line array of strings representing column values public void set line string line list temp list string h get headers for int count 0 count h length count temp list list data get h count if count line length line count length 0 temp list add line count else temp list add n a size setline templist getheaders templist templist templist sets a row of data using an array of strings as input each value in the array represents a column s value in that row assumes the order will be the same order in which the headers were added to the data set param line array of strings representing column values param deflt default value to be placed in data if line is not as long as headers public void set line string line string deflt list temp list string h get headers for int count 0 count h length count temp list list data get h count if count line length line count length 0 temp list add line count else temp list add deflt size setline templist getheaders templist templist templist returns all the data in the data set as an array of strings each array gives a row of data each column separated by tabs return array of strings public string get data as text string buffer temp new string buffer string line new string size 1 string elements get headers for int count 0 count elements length count temp append elements count if count 1 elements length temp append t line 0 temp to string reset int index 1 while next temp new string buffer for int count 0 count elements length count temp append get column value count if count 1 elements length temp append t line index temp to string return line getdataastext stringbuffer stringbuffer getheaders tostring stringbuffer getcolumnvalue tostring public string to string string contents get data as text string buffer sb new string buffer boolean first true for int x 0 x contents length x if first sb append n else first false sb append contents x return sb to string tostring getdataastext stringbuffer stringbuffer tostring public class test http request hdr extends j meter test case public test http request hdr string name super name testhttprequesthdr jmetertestcase testhttprequesthdr public void test repeated arguments throws exception string url http localhost matrix html a http get request string content encoding utf 8 string test get request get url update yes d 1 d 2 d d d d d d 1 d 2 d 1 d d http 1 0 r n r n http sampler base s get sampler for request url test get request content encoding assert equals http sampler base get s get method assert equals content encoding s get content encoding check arguments arguments arguments s get arguments assert equals 13 arguments get argument count check argument http argument arguments get argument 0 update yes yes content encoding false check argument http argument arguments get argument 1 d 1 1 content encoding false check argument http argument arguments get argument 2 d 2 2 content encoding false check argument http argument arguments get argument 3 d content encoding false check argument http argument arguments get argument 4 d content encoding false check argument http argument arguments get argument 5 d content encoding false check argument http argument arguments get argument 6 d content encoding false check argument http argument arguments get argument 7 d content encoding false check argument http argument arguments get argument 8 d 1 1 content encoding false check argument http argument arguments get argument 9 d 2 2 content encoding false check argument http argument arguments get argument 10 d 1 1 content encoding false check argument http argument arguments get argument 11 d content encoding false check argument http argument arguments get argument 12 d content encoding false a http post request content encoding utf 8 string post body update yes d 1 d 2 d d d d d d 1 d 2 d 1 d d string test post request post url http 1 0 n content type http sampler base application x www form urlencoded r n content length get body length post body content encoding r n r n post body s get sampler for request url test post request content encoding assert equals http sampler base post s get method assert false s get do multipart post assert equals content encoding s get content encoding check arguments arguments s get arguments assert equals 13 arguments get argument count check argument http argument arguments get argument 0 update yes yes content encoding false check argument http argument arguments get argument 1 d 1 1 content encoding false check argument http argument arguments get argument 2 d 2 2 content encoding false check argument http argument arguments get argument 3 d content encoding false check argument http argument arguments get argument 4 d content encoding false check argument http argument arguments get argument 5 d content encoding false check argument http argument arguments get argument 6 d content encoding false check argument http argument arguments get argument 7 d content encoding false check argument http argument arguments get argument 8 d 1 1 content encoding false check argument http argument arguments get argument 9 d 2 2 content encoding false check argument http argument arguments get argument 10 d 1 1 content encoding false check argument http argument arguments get argument 11 d content encoding false check argument http argument arguments get argument 12 d content encoding false a http post request with content type text plain content encoding utf 8 post body update yes d 1 d 2 d d d d d d 1 d 2 d 1 d uc385 d test post request post url http 1 1 r n content type text plain r n content length get body length post body content encoding r n r n post body s get sampler for request url test post request content encoding assert equals http sampler base post s get method assert false s get do multipart post assert equals content encoding s get content encoding check arguments we should have one argument with the value equal to the post body arguments s get arguments assert equals 1 arguments get argument count check argument http argument arguments get argument 0 post body post body content encoding false a http post request with content type text plain charset utf 8 the encoding should be picked up from the header we send with the request content encoding utf 8 post body update yes d 1 d 2 d d d d d d 1 d 2 d 1 d uc385 d test post request post url http 1 1 r n content type text plain charset content encoding r n content length get body length post body content encoding r n r n post body use null for url to simulate that http request hdr do not know the encoding for the page specify content encoding so the request is sent using that encoding s get sampler for request null test post request content encoding assert equals http sampler base post s get method assert false s get do multipart post assert equals content encoding s get content encoding check arguments we should have one argument with the value equal to the post body arguments s get arguments assert equals 1 arguments get argument count check argument http argument arguments get argument 0 post body post body content encoding false testrepeatedarguments contentencoding testgetrequest httpsamplerbase getsamplerforrequest testgetrequest contentencoding assertequals httpsamplerbase getmethod assertequals contentencoding getcontentencoding getarguments assertequals getargumentcount checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding contentencoding postbody testpostrequest httpsamplerbase application_x_www_form_urlencoded getbodylength postbody contentencoding postbody getsamplerforrequest testpostrequest contentencoding assertequals httpsamplerbase getmethod assertfalse getdomultipartpost assertequals contentencoding getcontentencoding getarguments assertequals getargumentcount checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding contentencoding postbody testpostrequest getbodylength postbody contentencoding postbody getsamplerforrequest testpostrequest contentencoding assertequals httpsamplerbase getmethod assertfalse getdomultipartpost assertequals contentencoding getcontentencoding getarguments assertequals getargumentcount checkargument httpargument getargument postbody postbody contentencoding contentencoding postbody testpostrequest contentencoding getbodylength postbody contentencoding postbody httprequesthdr contentencoding getsamplerforrequest testpostrequest contentencoding assertequals httpsamplerbase getmethod assertfalse getdomultipartpost assertequals contentencoding getcontentencoding getarguments assertequals getargumentcount checkargument httpargument getargument postbody postbody contentencoding public void test encoded arguments throws exception string url http localhost matrix html a http get request with encoding not known string content encoding string query string abc 3fspace a b space a 20b query what 3f string test get request get url query string http 1 1 r n r n use null for url and content encoding to simulate that http request hdr do not know the encoding for the page http sampler base s get sampler for request null test get request null assert equals http sampler base get s get method assert equals query string s get query string assert equals content encoding s get content encoding check arguments arguments arguments s get arguments assert equals 3 arguments get argument count when the encoding is not known the argument will get the encoded value and the encode set to false check argument http argument arguments get argument 0 abc 3fspace a b a b content encoding false check argument http argument arguments get argument 1 space a 20b a 20b content encoding false check argument http argument arguments get argument 2 query what 3f what 3f content encoding false a http get request with utf 8 encoding content encoding utf 8 query string abc 3fspace a b space a 20b query what 3f test get request get url query string http 1 1 r n r n s get sampler for request url test get request content encoding assert equals http sampler base get s get method string expected query string abc 3fspace a b space a b query what 3f assert equals expected query string s get query string assert equals content encoding s get content encoding check arguments arguments s get arguments assert equals 3 arguments get argument count check argument http argument arguments get argument 0 abc space a b a b content encoding true check argument http argument arguments get argument 1 space a b a b content encoding true check argument http argument arguments get argument 2 query what what 3f content encoding true a http post request with unknown encoding content encoding string post body abc 3fspace a b space a 20b query what 3f string test post request post url http 1 1 r n content type http sampler base application x www form urlencoded r n content length get body length post body content encoding r n r n post body use null for url and content encoding to simulate that http request hdr do not know the encoding for the page s get sampler for request null test post request null assert equals http sampler base post s get method assert equals query string s get query string assert equals content encoding s get content encoding assert false s get do multipart post check arguments arguments s get arguments assert equals 3 arguments get argument count when the encoding is not known the argument will get the encoded value and the encode set to false check argument http argument arguments get argument 0 abc 3fspace a b a b content encoding false check argument http argument arguments get argument 1 space a 20b a 20b content encoding false check argument http argument arguments get argument 2 query what 3f what 3f content encoding false a http post request with utf 8 encoding content encoding utf 8 post body abc space a b space a 20b query what test post request post url http 1 1 n content type http sampler base application x www form urlencoded r n content length get body length post body content encoding r n r n post body s get sampler for request url test post request content encoding assert equals http sampler base post s get method expected query string abc 3fspace a b space a b query what 3f assert equals expected query string s get query string assert equals content encoding s get content encoding assert false s get do multipart post check arguments arguments s get arguments assert equals 3 arguments get argument count check argument http argument arguments get argument 0 abc space a b a b content encoding true check argument http argument arguments get argument 1 space a b a b content encoding true check argument http argument arguments get argument 2 query what what 3f content encoding true testencodedarguments contentencoding querystring testgetrequest querystring contentencoding httprequesthdr httpsamplerbase getsamplerforrequest testgetrequest assertequals httpsamplerbase getmethod assertequals querystring getquerystring assertequals contentencoding getcontentencoding getarguments assertequals getargumentcount checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding contentencoding querystring testgetrequest querystring getsamplerforrequest testgetrequest contentencoding assertequals httpsamplerbase getmethod expectedquerystring assertequals expectedquerystring getquerystring assertequals contentencoding getcontentencoding getarguments assertequals getargumentcount checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding contentencoding postbody testpostrequest httpsamplerbase application_x_www_form_urlencoded getbodylength postbody contentencoding postbody contentencoding httprequesthdr getsamplerforrequest testpostrequest assertequals httpsamplerbase getmethod assertequals querystring getquerystring assertequals contentencoding getcontentencoding assertfalse getdomultipartpost getarguments assertequals getargumentcount checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding contentencoding postbody testpostrequest httpsamplerbase application_x_www_form_urlencoded getbodylength postbody contentencoding postbody getsamplerforrequest testpostrequest contentencoding assertequals httpsamplerbase getmethod expectedquerystring assertequals expectedquerystring getquerystring assertequals contentencoding getcontentencoding assertfalse getdomultipartpost getarguments assertequals getargumentcount checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding checkargument httpargument getargument contentencoding public void test get request encodings throws exception string url http localhost matrix html a http get request with encoding not known string content encoding string param1 value yes string param2 value 0 5 u00c5 uc385 c3 85 string param2 value encoded url encoder encode param2 value utf 8 string test get request get url param1 param1 value param2 param2 value encoded http 1 1 r n r n use null for url and content encoding to simulate that http request hdr do not know the encoding for the page http sampler base s get sampler for request null test get request null assert equals http sampler base get s get method assert equals content encoding s get content encoding check arguments arguments arguments s get arguments assert equals 2 arguments get argument count check argument http argument arguments get argument 0 param1 param1 value param1 value content encoding false when the encoding is not known the argument will get the encoded value and the encode set to false check argument http argument arguments get argument 1 param2 param2 value encoded param2 value encoded content encoding false a http get request with utf 8 encoding content encoding utf 8 param1 value yes param2 value 0 5 u007c u2aa1 u266a u0153 u20a1 u0115 u0364 u00c5 u2052 uc385 c3 85 param2 value encoded url encoder encode param2 value content encoding test get request get url param1 param1 value param2 param2 value encoded http 1 1 r n r n s get sampler for request url test get request content encoding assert equals http sampler base get s get method assert equals content encoding s get content encoding check arguments arguments s get arguments assert equals 2 arguments get argument count check argument http argument arguments get argument 0 param1 param1 value param1 value content encoding false check argument http argument arguments get argument 1 param2 param2 value param2 value encoded content encoding true a http get request with iso 8859 1 encoding content encoding iso 8859 1 param1 value yes param2 value 0 5 u00c5 c3 85 param2 value encoded url encoder encode param2 value content encoding test get request get url param1 param1 value param2 param2 value encoded http 1 1 r n r n s get sampler for request url test get request content encoding assert equals http sampler base get s get method assert equals content encoding s get content encoding check arguments arguments s get arguments assert equals 2 arguments get argument count check argument http argument arguments get argument 0 param1 param1 value param1 value content encoding false check argument http argument arguments get argument 1 param2 param2 value param2 value encoded content encoding true testgetrequestencodings contentencoding param1value param2value param2valueencoded urlencoder param2value testgetrequest param1value param2valueencoded contentencoding httprequesthdr httpsamplerbase getsamplerforrequest testgetrequest assertequals httpsamplerbase getmethod assertequals contentencoding getcontentencoding getarguments assertequals getargumentcount checkargument httpargument getargument param1value param1value contentencoding checkargument httpargument getargument param2valueencoded param2valueencoded contentencoding contentencoding param1value param2value param2valueencoded urlencoder param2value contentencoding testgetrequest param1value param2valueencoded getsamplerforrequest testgetrequest contentencoding assertequals httpsamplerbase getmethod assertequals contentencoding getcontentencoding getarguments assertequals getargumentcount checkargument httpargument getargument param1value param1value contentencoding checkargument httpargument getargument param2value param2valueencoded contentencoding contentencoding param1value param2value param2valueencoded urlencoder param2value contentencoding testgetrequest param1value param2valueencoded getsamplerforrequest testgetrequest contentencoding assertequals httpsamplerbase getmethod assertequals contentencoding getcontentencoding getarguments assertequals getargumentcount checkargument httpargument getargument param1value param1value contentencoding checkargument httpargument getargument param2value param2valueencoded contentencoding public void test post request encodings throws exception string url http localhost matrix html a http post request with encoding not known string content encoding string param1 value yes string param2 value 0 5 u00c5 c3 85 string param2 value encoded url encoder encode param2 value utf 8 string post body param1 param1 value param2 param2 value encoded r n string test post request post url http 1 1 r n content type http sampler base application x www form urlencoded r n content length get body length post body content encoding r n r n post body use null for url and content encoding to simulate that http request hdr do not know the encoding for the page http sampler base s get sampler for request null test post request null assert equals http sampler base post s get method assert equals content encoding s get content encoding check arguments arguments arguments s get arguments assert equals 2 arguments get argument count check argument http argument arguments get argument 0 param1 param1 value param1 value content encoding false when the encoding is not known the argument will get the encoded value and the encode set to false check argument http argument arguments get argument 1 param2 param2 value encoded param2 value encoded content encoding false a http post request with utf 8 encoding content encoding utf 8 param1 value yes param2 value 0 5 u007c u2aa1 u266a u0153 u20a1 u0115 u0364 u00c5 u2052 uc385 c3 85 param2 value encoded url encoder encode param2 value content encoding post body param1 param1 value param2 param2 value encoded r n test post request post url http 1 1 r n content type http sampler base application x www form urlencoded r n content length get body length post body content encoding r n r n post body s get sampler for request url test post request content encoding assert equals http sampler base post s get method assert equals content encoding s get content encoding check arguments arguments s get arguments assert equals 2 arguments get argument count check argument http argument arguments get argument 0 param1 param1 value param1 value content encoding false check argument http argument arguments get argument 1 param2 param2 value param2 value encoded content encoding true a http post request with iso 8859 1 encoding content encoding iso 8859 1 param1 value yes param2 value 0 5 u00c5 c3 85 param2 value encoded url encoder encode param2 value content encoding post body param1 param1 value param2 param2 value encoded r n test post request post url http 1 1 r n content type http sampler base application x www form urlencoded r n content length get body length post body content encoding r n r n post body s get sampler for request url test post request content encoding assert equals http sampler base post s get method assert equals content encoding s get content encoding check arguments arguments s get arguments assert equals 2 arguments get argument count check argument http argument arguments get argument 0 param1 param1 value param1 value content encoding false check argument http argument arguments get argument 1 param2 param2 value param2 value encoded content encoding true testpostrequestencodings contentencoding param1value param2value param2valueencoded urlencoder param2value postbody param1value param2valueencoded testpostrequest httpsamplerbase application_x_www_form_urlencoded getbodylength postbody contentencoding postbody contentencoding httprequesthdr httpsamplerbase getsamplerforrequest testpostrequest assertequals httpsamplerbase getmethod assertequals contentencoding getcontentencoding getarguments assertequals getargumentcount checkargument httpargument getargument param1value param1value contentencoding checkargument httpargument getargument param2valueencoded param2valueencoded contentencoding contentencoding param1value param2value param2valueencoded urlencoder param2value contentencoding postbody param1value param2valueencoded testpostrequest httpsamplerbase application_x_www_form_urlencoded getbodylength postbody contentencoding postbody getsamplerforrequest testpostrequest contentencoding assertequals httpsamplerbase getmethod assertequals contentencoding getcontentencoding getarguments assertequals getargumentcount checkargument httpargument getargument param1value param1value contentencoding checkargument httpargument getargument param2value param2valueencoded contentencoding contentencoding param1value param2value param2valueencoded urlencoder param2value contentencoding postbody param1value param2valueencoded testpostrequest httpsamplerbase application_x_www_form_urlencoded getbodylength postbody contentencoding postbody getsamplerforrequest testpostrequest contentencoding assertequals httpsamplerbase getmethod assertequals contentencoding getcontentencoding getarguments assertequals getargumentcount checkargument httpargument getargument param1value param1value contentencoding checkargument httpargument getargument param2value param2valueencoded contentencoding public void test post multipart form data throws exception string url http localhost matrix html a http post request multipart form data simple values string content encoding utf 8 string boundary xf8sqldnvmn6mfywriojaeur2 z4clrxosmb string end of line r n string title value mytitle string description value mydescription string post body create multipart form body title value description value content encoding true boundary end of line string test post request create multipart form request url post body content encoding boundary end of line http sampler base s get sampler for request url test post request content encoding assert equals http sampler base post s get method assert equals content encoding s get content encoding assert true s get do multipart post check arguments arguments arguments s get arguments assert equals 2 arguments get argument count check argument http argument arguments get argument 0 title title value title value content encoding false check argument http argument arguments get argument 1 description description value description value content encoding false a http post request multipart form data simple values with r n as end of line which is according to spec and with more headers in each multipart end of line r n title value mytitle description value mydescription post body create multipart form body title value description value content encoding true boundary end of line test post request create multipart form request url post body content encoding boundary end of line s get sampler for request url test post request content encoding assert equals http sampler base post s get method assert equals content encoding s get content encoding assert true s get do multipart post check arguments arguments s get arguments assert equals 2 arguments get argument count check argument http argument arguments get argument 0 title title value title value content encoding false check argument http argument arguments get argument 1 description description value description value content encoding false a http post request multipart form data simple values with n as end of line which should also be handled and with more headers in each multipart end of line n title value mytitle description value mydescription post body create multipart form body title value description value content encoding true boundary end of line test post request create multipart form request url post body content encoding boundary end of line s get sampler for request url test post request content encoding assert equals http sampler base post s get method assert equals content encoding s get content encoding assert true s get do multipart post check arguments arguments s get arguments assert equals 2 arguments get argument count check argument http argument arguments get argument 0 title title value title value content encoding false check argument http argument arguments get argument 1 description description value description value content encoding false a http post request multipart form data with value that will change if they are url encoded values are similar to viewstate parameter that net uses end of line r n title value wep dwullte2 mzm2ota0ntypzbyc agmpz ra 8dz2dnz2dnz2d gn dar6 osh pwd jc description value mydescription post body create multipart form body title value description value content encoding true boundary end of line test post request create multipart form request url post body content encoding boundary end of line s get sampler for request url test post request content encoding assert equals http sampler base post s get method assert equals content encoding s get content encoding assert true s get do multipart post check arguments arguments s get arguments assert equals 2 arguments get argument count check argument http argument arguments get argument 0 title title value title value content encoding false check argument http argument arguments get argument 1 description description value description value content encoding false testpostmultipartformdata contentencoding xf8sqldnvmn6mfywriojaeur2_z4clrxosmb endofline titlevalue descriptionvalue postbody createmultipartformbody titlevalue descriptionvalue contentencoding endofline testpostrequest createmultipartformrequest postbody contentencoding endofline httpsamplerbase getsamplerforrequest testpostrequest contentencoding assertequals httpsamplerbase getmethod assertequals contentencoding getcontentencoding asserttrue getdomultipartpost getarguments assertequals getargumentcount checkargument httpargument getargument titlevalue titlevalue contentencoding checkargument httpargument getargument descriptionvalue descriptionvalue contentencoding endofline titlevalue descriptionvalue postbody createmultipartformbody titlevalue descriptionvalue contentencoding endofline testpostrequest createmultipartformrequest postbody contentencoding endofline getsamplerforrequest testpostrequest contentencoding assertequals httpsamplerbase getmethod assertequals contentencoding getcontentencoding asserttrue getdomultipartpost getarguments assertequals getargumentcount checkargument httpargument getargument titlevalue titlevalue contentencoding checkargument httpargument getargument descriptionvalue descriptionvalue contentencoding endofline titlevalue descriptionvalue postbody createmultipartformbody titlevalue descriptionvalue contentencoding endofline testpostrequest createmultipartformrequest postbody contentencoding endofline getsamplerforrequest testpostrequest contentencoding assertequals httpsamplerbase getmethod assertequals contentencoding getcontentencoding asserttrue getdomultipartpost getarguments assertequals getargumentcount checkargument httpargument getargument titlevalue titlevalue contentencoding checkargument httpargument getargument descriptionvalue descriptionvalue contentencoding __viewstate endofline titlevalue wepdwullte2mzm2ota0ntypzbycagmpz gndar6oshpwdjc descriptionvalue postbody createmultipartformbody titlevalue descriptionvalue contentencoding endofline testpostrequest createmultipartformrequest postbody contentencoding endofline getsamplerforrequest testpostrequest contentencoding assertequals httpsamplerbase getmethod assertequals contentencoding getcontentencoding asserttrue getdomultipartpost getarguments assertequals getargumentcount checkargument httpargument getargument titlevalue titlevalue contentencoding checkargument httpargument getargument descriptionvalue descriptionvalue contentencoding public void test parse1 throws exception no space after http request hdr req new http request hdr byte array input stream bis null bis new byte array input stream get xxx http 1 0 r nname value r n get bytes iso 8859 1 req parse bis bis close header manager mgr req get header manager header header mgr get headers header mgr get header 0 assert equals name header get name assert equals value header get value testparse1 httprequesthdr httprequesthdr bytearrayinputstream bytearrayinputstream getbytes headermanager getheadermanager getheaders getheader assertequals getname assertequals getvalue public void test parse2 throws exception spaces after http request hdr req new http request hdr byte array input stream bis null bis new byte array input stream get xxx http 1 0 r nname value r n get bytes iso 8859 1 req parse bis bis close header manager mgr req get header manager header header mgr get headers header mgr get header 0 assert equals name header get name assert equals value header get value testparse2 httprequesthdr httprequesthdr bytearrayinputstream bytearrayinputstream getbytes headermanager getheadermanager getheaders getheader assertequals getname assertequals getvalue public void test post multipart file upload throws exception string url http localhost matrix html a http post request multipart form data simple values string content encoding utf 8 string boundary xf8sqldnvmn6mfywriojaeur2 z4clrxosmb string end of line r n string file field value test file string file name somefilename txt string mime type text plain string file content somedummycontent n ndfgdfg r nfgdgdg n content type dfsfsfds string post body create multipart file upload body file field value file name mime type file content boundary end of line string test post request create multipart form request url post body content encoding boundary end of line http sampler base s get sampler for request url test post request content encoding assert equals http sampler base post s get method assert equals content encoding s get content encoding assert equals s get query string assert true s get do multipart post check arguments arguments arguments s get arguments assert equals 0 arguments get argument count assert equals file field value s get file field assert equals file name s get filename assert equals mime type s get mimetype testpostmultipartfileupload contentencoding xf8sqldnvmn6mfywriojaeur2_z4clrxosmb endofline filefieldvalue test_file filename mimetype filecontent ncontent postbody createmultipartfileuploadbody filefieldvalue filename mimetype filecontent endofline testpostrequest createmultipartformrequest postbody contentencoding endofline httpsamplerbase getsamplerforrequest testpostrequest contentencoding assertequals httpsamplerbase getmethod assertequals contentencoding getcontentencoding assertequals getquerystring asserttrue getdomultipartpost getarguments assertequals getargumentcount assertequals filefieldvalue getfilefield assertequals filename getfilename assertequals mimetype getmimetype private string create multipart form body string title value string description value string content encoding boolean include extra headers string boundary string end of line title multipart string post body boundary end of line content disposition form data name title end of line if include extra headers post body content type text plain charset content encoding end of line content transfer encoding 8bit end of line post body end of line title value end of line boundary end of line description multipart post body content disposition form data name description end of line if include extra headers post body content type text plain charset content encoding end of line content transfer encoding 8bit end of line post body end of line description value end of line boundary end of line return post body createmultipartformbody titlevalue descriptionvalue contentencoding includeextraheaders endofline postbody endofline endofline includeextraheaders postbody contentencoding endofline endofline postbody endofline titlevalue endofline endofline postbody endofline includeextraheaders postbody contentencoding endofline endofline postbody endofline descriptionvalue endofline endofline postbody private string create multipart file upload body string file field string file name string file mime type string file content string boundary string end of line file upload multipart string post body boundary end of line content disposition form data name file field filename file name end of line content type file mime type end of line content transfer encoding binary end of line end of line file content end of line boundary end of line return post body createmultipartfileuploadbody filefield filename filemimetype filecontent endofline postbody endofline filefield filename endofline filemimetype endofline endofline endofline filecontent endofline endofline postbody private string create multipart form request string url string post body string content encoding string boundary string end of line throws io exception string post request post url http 1 1 end of line content type http sampler base multipart form data boundary boundary end of line content length get body length post body content encoding end of line end of line post body return post request createmultipartformrequest postbody contentencoding endofline ioexception postrequest endofline httpsamplerbase multipart_form_data endofline getbodylength postbody contentencoding endofline endofline postbody postrequest private http sampler base get sampler for request string url string request string content encoding throws io exception http request hdr req new http request hdr byte array input stream bis null if content encoding null bis new byte array input stream request get bytes content encoding else most browsers use iso 8859 1 as default encoding even if spec says utf 8 bis new byte array input stream request get bytes iso 8859 1 req parse bis bis close map page encodings collections synchronized map new hash map map form encodings collections synchronized map new hash map if url null content encoding null page encodings put url content encoding return req get sampler page encodings form encodings httpsamplerbase getsamplerforrequest contentencoding ioexception httprequesthdr httprequesthdr bytearrayinputstream contentencoding bytearrayinputstream getbytes contentencoding bytearrayinputstream getbytes pageencodings synchronizedmap hashmap formencodings synchronizedmap hashmap contentencoding pageencodings contentencoding getsampler pageencodings formencodings private void check argument http argument arg string expected name string expected value string expected encoded value string content encoding boolean expected encoded throws io exception assert equals expected name arg get name system out println expect url encoder encode expected value utf 8 system out println actual url encoder encode arg get value utf 8 assert equals expected value arg get value if content encoding null content encoding length 0 assert equals expected encoded value arg get encoded value content encoding else most browsers use iso 8859 1 as default encoding even if spec says utf 8 assert equals expected encoded value arg get encoded value iso 8859 1 assert equals expected encoded arg is always encoded checkargument httpargument expectedname expectedvalue expectedencodedvalue contentencoding expectedencoded ioexception assertequals expectedname getname urlencoder expectedvalue urlencoder getvalue assertequals expectedvalue getvalue contentencoding contentencoding assertequals expectedencodedvalue getencodedvalue contentencoding assertequals expectedencodedvalue getencodedvalue assertequals expectedencoded isalwaysencoded private int get body length string post body string content encoding throws io exception if content encoding null content encoding length 0 return post body get bytes content encoding length else most browsers use iso 8859 1 as default encoding even if spec says utf 8 return post body get bytes length getbodylength postbody contentencoding ioexception contentencoding contentencoding postbody getbytes contentencoding postbody getbytes constructor for the close object public report close reportclose gets the action names attribute of the close object return the action names value public set get action names return commands actionnames actionnames getactionnames this method performs the actual command processing param e the generic ui action event public void do action action event e report action router get instance do action now new action event e get source e getid report check dirty check dirty report gui package gui package report gui package get instance if gui package is dirty if j option pane show confirm dialog report gui package get instance get main frame j meter utils get res string cancel new to save j meter utils get res string save j option pane yes no option j option pane question message j option pane yes option report action router get instance do action now new action event e get source e getid action names save gui package get tree model clear test plan gui package get tree listener getj tree set selection row 1 clear the name of the test plan file report gui package get instance set report plan file null report action router get instance action performed new action event e get source e getid action names add all doaction actionevent reportactionrouter getinstance doactionnow actionevent getsource reportcheckdirty check_dirty reportguipackage guipackage reportguipackage getinstance guipackage isdirty joptionpane showconfirmdialog reportguipackage getinstance getmainframe jmeterutils getresstring cancel_new_to_save jmeterutils getresstring joptionpane yes_no_option joptionpane question_message joptionpane yes_option reportactionrouter getinstance doactionnow actionevent getsource actionnames guipackage gettreemodel cleartestplan guipackage gettreelistener getjtree setselectionrow reportguipackage getinstance setreportplanfile reportactionrouter getinstance actionperformed actionevent getsource actionnames add_all public result collector helper result collector result collector visualizer visualizer this visualizer visualizer this errors only result collector is error logging this success only result collector is success only logging resultcollectorhelper resultcollector resultcollector errorsonly resultcollector iserrorlogging successonly resultcollector issuccessonlylogging public void add sample result sample if result collector is sample wanted sample is successful errors only success only visualizer add sample sampleresult resultcollector issamplewanted issuccessful errorsonly successonly private j check box style public interleave control gui init jcheckbox interleavecontrolgui public void configure test element el super configure el if interleave control el get style interleave control ignore sub controllers style set selected true else style set selected false testelement interleavecontrol getstyle interleavecontrol ignore_sub_controllers setselected setselected public test element create test element interleave control ic new interleave control modify test element ic return ic testelement createtestelement interleavecontrol interleavecontrol modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element ic configure test element ic if style is selected interleave control ic set style interleave control ignore sub controllers else interleave control ic set style interleave control use sub controllers testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement isselected interleavecontrol setstyle interleavecontrol ignore_sub_controllers interleavecontrol setstyle interleavecontrol use_sub_controllers implements j metergui component clear gui public void clear gui super clear gui style set selected false jmeterguicomponent cleargui cleargui cleargui setselected public string get label resource return interleave control title non nls 1 getlabelresource interleave_control_title private void init set layout new vertical layout 5 vertical layout both vertical layout top set border make border add make title panel style new j check box j meter utils get res string ignore subcontrollers non nls 1 add style setlayout verticallayout verticallayout verticallayout setborder makeborder maketitlepanel jcheckbox jmeterutils getresstring ignore_subcontrollers public class test loop controller extends j meter test case public test loop controller string name super name testloopcontroller jmetertestcase testloopcontroller public void test processing throws exception generic controller controller new generic controller generic controller sub 1 new generic controller sub 1 add test element new test sampler one sub 1 add test element new test sampler two controller add test element sub 1 controller add test element new test sampler three loop controller sub 2 new loop controller sub 2 set loops 3 generic controller sub 3 new generic controller sub 2 add test element new test sampler four sub 3 add test element new test sampler five sub 3 add test element new test sampler six sub 2 add test element sub 3 sub 2 add test element new test sampler seven controller add test element sub 2 string order new string one two three four five six seven four five six seven four five six seven int counter 15 controller set running version true sub 1 set running version true sub 2 set running version true sub 3 set running version true controller initialize for int i 0 i 2 i assert equals 15 counter counter 0 test element sampler null while sampler controller next null assert equals order counter sampler get name testprocessing genericcontroller genericcontroller genericcontroller sub_1 genericcontroller sub_1 addtestelement testsampler sub_1 addtestelement testsampler addtestelement sub_1 addtestelement testsampler loopcontroller sub_2 loopcontroller sub_2 setloops genericcontroller sub_3 genericcontroller sub_2 addtestelement testsampler sub_3 addtestelement testsampler sub_3 addtestelement testsampler sub_2 addtestelement sub_3 sub_2 addtestelement testsampler addtestelement sub_2 setrunningversion sub_1 setrunningversion sub_2 setrunningversion sub_3 setrunningversion assertequals testelement assertequals getname public void test loop zero times throws exception loop controller loop new loop controller loop set loops 0 loop add test element new test sampler never run loop initialize assert null loop next testloopzerotimes loopcontroller loopcontroller setloops addtestelement testsampler assertnull public void test infinite loop throws exception loop controller loop new loop controller loop set loops 1 loop add test element new test sampler never run loop set running version true loop initialize for int i 0 i 42 i assert not null loop next testinfiniteloop loopcontroller loopcontroller setloops addtestelement testsampler setrunningversion assertnotnull public class table extends abstract table public table super abstracttable for now the method isn t implemented i still need to decide how it should be implemented public string get table data list data return new string 0 0 gettabledata public request info impl super requestinfoimpl public long get bytes received return this bytes received getbytesreceived bytesreceived public void set bytes received long value this bytes received value setbytesreceived bytesreceived public long get bytes sent return this bytes sent getbytessent bytessent public void set bytes sent long value this bytes sent value setbytessent bytessent public long get request count return request count getrequestcount requestcount public void set request count long value this request count value setrequestcount requestcount public long get error count return this error count geterrorcount errorcount public void set error count long value this error count value seterrorcount errorcount public int get max time return this max time getmaxtime maxtime public void set max time int value this max time value setmaxtime maxtime public int get processing time return this processing time getprocessingtime processingtime public void set processing time int value this processing time value setprocessingtime processingtime public class logic controller gui extends abstract controller gui create a new logic controller gui instance public logic controller gui init logiccontrollergui abstractcontrollergui logiccontrollergui logiccontrollergui implements j metergui component create test element public test element create test element generic controller lc new generic controller configure test element lc return lc jmeterguicomponent createtestelement testelement createtestelement genericcontroller genericcontroller configuretestelement implements j metergui component modify test element test element public void modify test element test element el configure test element el jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement public string get label resource return logic controller title non nls 1 getlabelresource logic_controller_title initialize the gui components and layout for this component private void init set layout new border layout set border make border add make title panel border layout north setlayout borderlayout setborder makeborder maketitlepanel borderlayout public xml conf panel super init xmlconfpanel param is double buffered public xml conf panel boolean is double buffered super is double buffered init isdoublebuffered xmlconfpanel isdoublebuffered isdoublebuffered private void init box tidy options box create horizontal box tidy options set border border factory create etched border tidy options add get tolerant quiet new j check box j meter utils get res string xpath tidy quiet true non nls 1 report errors new j check box j meter utils get res string xpath tidy report errors true non nls 1 show warnings new j check box j meter utils get res string xpath tidy show warnings true non nls 1 tidy options add quiet tidy options add report errors tidy options add show warnings add tidy options add get namespace add get validate add get whitespace set default values tidyoptions createhorizontalbox tidyoptions setborder borderfactory createetchedborder tidyoptions gettolerant jcheckbox jmeterutils getresstring xpath_tidy_quiet reporterrors jcheckbox jmeterutils getresstring xpath_tidy_report_errors showwarnings jcheckbox jmeterutils getresstring xpath_tidy_show_warnings tidyoptions tidyoptions reporterrors tidyoptions showwarnings tidyoptions getnamespace getvalidate getwhitespace setdefaultvalues public void set default values set whitespace false set validate false set tolerant false set namespace false quiet set selected true report errors set selected false show warnings set selected false tolerant setdefaultvalues setwhitespace setvalidate settolerant setnamespace setselected reporterrors setselected showwarnings setselected return returns the namespace private j check box get namespace if namespace null namespace new j check box j meter utils get res string xml namespace button non nls 1 return namespace jcheckbox getnamespace jcheckbox jmeterutils getresstring xml_namespace_button return returns the tolerant private j check box get tolerant if tolerant null tolerant new j check box j meter utils get res string xml tolerant button non nls 1 tolerant add action listener new action listener public void action performed action event e tolerant return tolerant jcheckbox gettolerant jcheckbox jmeterutils getresstring xml_tolerant_button addactionlistener actionlistener actionperformed actionevent tolerant add action listener new action listener public void action performed action event e tolerant addactionlistener actionlistener actionperformed actionevent return returns the validate private j check box get validate if validate null validate new j check box j meter utils get res string xml validate button non nls 1 return validate jcheckbox getvalidate jcheckbox jmeterutils getresstring xml_validate_button return returns the whitespace private j check box get whitespace if whitespace null whitespace new j check box j meter utils get res string xml whitespace button non nls 1 return whitespace jcheckbox getwhitespace jcheckbox jmeterutils getresstring xml_whitespace_button private boolean is namespace return get namespace is selected isnamespace getnamespace isselected private void set namespace boolean namespace get namespace set selected namespace setnamespace getnamespace setselected private boolean is tolerant return get tolerant is selected istolerant gettolerant isselected private void set tolerant boolean tolerant get tolerant set selected tolerant settolerant gettolerant setselected private boolean is whitespace return get whitespace is selected iswhitespace getwhitespace isselected private void set whitespace boolean whitespace get whitespace set selected whitespace setwhitespace getwhitespace setselected private boolean is validate return get validate is selected isvalidate getvalidate isselected private void set validate boolean validating get validate set selected validating setvalidate getvalidate setselected private void tolerant final boolean is tolerant is tolerant get validate set enabled is tolerant get whitespace set enabled is tolerant get namespace set enabled is tolerant quiet set enabled is tolerant report errors set enabled is tolerant show warnings set enabled is tolerant istolerant istolerant getvalidate setenabled istolerant getwhitespace setenabled istolerant getnamespace setenabled istolerant setenabled istolerant reporterrors setenabled istolerant showwarnings setenabled istolerant called by x path assertion gui public void modify test element x path assertion assertion assertion set validating is validate assertion set whitespace is whitespace assertion set tolerant is tolerant assertion set namespace is namespace assertion set show warnings show warnings is selected assertion set report errors report errors is selected assertion set quiet quiet is selected xpathassertiongui modifytestelement xpathassertion setvalidating isvalidate setwhitespace iswhitespace settolerant istolerant setnamespace isnamespace setshowwarnings showwarnings isselected setreporterrors reporterrors isselected setquiet isselected called by x path assertion gui public void configure x path assertion assertion set whitespace assertion is whitespace set validate assertion is validating set tolerant assertion is tolerant set namespace assertion is namespace quiet set selected assertion is quiet show warnings set selected assertion show warnings report errors set selected assertion report errors tolerant xpathassertiongui xpathassertion setwhitespace iswhitespace setvalidate isvalidating settolerant istolerant setnamespace isnamespace setselected isquiet showwarnings setselected showwarnings reporterrors setselected reporterrors constructor for the save object public report save graphics reportsavegraphics gets the action names attribute of the save object return the action names value public set get action names return commands actionnames actionnames getactionnames public void do action action event e throws illegal user action exception j metergui component component null j component comp null if commands contains e get action command throw new illegal user action exception invalid user command e get action command if e get action command equals save graphics component report gui package get instance get current gui get the j component from the visualizer if component instanceof printable comp printable component get printable component string filename j file chooser chooser report file dialoger prompt to save file report gui package get instance get tree listener get current node get name extensions if chooser null return get the string given from the choose and check the file extension filename chooser get selected file get absolute path if filename null save graphics service save new save graphics service string ext filename substring filename length 4 string name filename substring 0 filename length 4 if ext equals save graphics service png extension save savej component name save graphics service png comp else if ext equals save graphics service tiff extension save savej component name save graphics service tiff comp else save savej component filename save graphics service png comp doaction actionevent illegaluseractionexception jmeterguicomponent jcomponent getactioncommand illegaluseractionexception getactioncommand getactioncommand save_graphics reportguipackage getinstance getcurrentgui jcomponent getprintablecomponent jfilechooser reportfiledialoger prompttosavefile reportguipackage getinstance gettreelistener getcurrentnode getname getselectedfile getabsolutepath savegraphicsservice savegraphicsservice savegraphicsservice png_extension savejcomponent savegraphicsservice savegraphicsservice tiff_extension savejcomponent savegraphicsservice savejcomponent savegraphicsservice public void add node object node hash tree sub tree if node instanceof test element node instanceof test plan test element node set running version true addnode hashtree subtree testelement testplan testelement setrunningversion see org apache jorphan collections hash tree traverser subtract node public void subtract node hashtreetraverser subtractnode subtractnode see org apache jorphan collections hash tree traverser process path public void process path hashtreetraverser processpath processpath public component get table cell renderer component j table table object value boolean is selected boolean has focus int row int column rend new j text area value to string use two rows so that we have room for horisontal scrollbar if the text is one long line fix for 40371 this is not an optimal solution but makes it possible to see the line if it is long rend set rows 2 rend revalidate if has focus is selected rend set background j meter color lavender if table get row height row get preferred height table set row height row get preferred height return rend gettablecellrenderercomponent jtable isselected hasfocus jtextarea tostring setrows hasfocus isselected setbackground jmetercolor getrowheight getpreferredheight setrowheight getpreferredheight public int get preferred height return rend get preferred size height 5 getpreferredheight getpreferredsize create a new http file args object with no files public http file args set property new collection property http file args new array list httpfileargs httpfileargs setproperty collectionproperty http_file_args arraylist get the files return the files public collection property gethttp file args collection return collection property get property http file args collectionproperty gethttpfileargscollection collectionproperty getproperty http_file_args clear the files public void clear super clear set property new collection property http file args new array list setproperty collectionproperty http_file_args arraylist set the list of files any existing files will be lost param files the new files public void sethttp file args list files set property new collection property http file args files sethttpfileargs setproperty collectionproperty http_file_args add a new file with the given path param path the path of the file public void addhttp file arg string path addhttp file arg new http file arg path addhttpfilearg addhttpfilearg httpfilearg add a new file param file the new file public void addhttp file arg http file arg file test element property newhttp file arg new test element property file get path file if is running version this set temporary newhttp file arg gethttp file args collection add item newhttp file arg addhttpfilearg httpfilearg testelementproperty newhttpfilearg testelementproperty getpath isrunningversion settemporary newhttpfilearg gethttpfileargscollection additem newhttpfilearg adds a new file to the http file args list to be uploaded with http request param path file full path param param http parameter name param mime mime type of file public void addhttp file arg string path string param string mime addhttp file arg new http file arg path param mime httpfileargs addhttpfilearg addhttpfilearg httpfilearg get a property iterator of the files return an iteration of the files public property iterator iterator return gethttp file args collection iterator propertyiterator propertyiterator gethttpfileargscollection get the current arguments as an array return an array of file arguments public http file arg as array collection property props gethttp file args collection final int size props size http file arg args new http file arg size for int i 0 i size i args i http file arg props get i get object value return args httpfilearg asarray collectionproperty gethttpfileargscollection httpfilearg httpfilearg httpfilearg getobjectvalue create a string representation of the files return the string representation of the files public string to string string buffer str new string buffer property iterator iter gethttp file args collection iterator while iter has next http file arg file http file arg iter next get object value str append file get path if iter has next str append non nls 1 return str to string tostring stringbuffer stringbuffer propertyiterator gethttpfileargscollection hasnext httpfilearg httpfilearg getobjectvalue getpath hasnext tostring remove the specified file from the list param row the index of the file to remove public void removehttp file arg int row if row gethttp file arg count gethttp file args collection remove row removehttpfilearg gethttpfileargcount gethttpfileargscollection remove the specified file from the list param file the file to remove public void removehttp file arg http file arg file property iterator iter gethttp file args collection iterator while iter has next http file arg item http file arg iter next get object value if file equals item iter remove removehttpfilearg httpfilearg propertyiterator gethttpfileargscollection hasnext httpfilearg httpfilearg getobjectvalue remove the file with the specified path param file path the path of the file to remove public void removehttp file arg string file path property iterator iter gethttp file args collection iterator while iter has next http file arg file http file arg iter next get object value if file get path equals file path iter remove filepath removehttpfilearg filepath propertyiterator gethttpfileargscollection hasnext httpfilearg httpfilearg getobjectvalue getpath filepath remove all files from the list public void remove allhttp file args gethttp file args collection clear removeallhttpfileargs gethttpfileargscollection add a new empty file to the list the new file will have the empty string as its path public void add emptyhttp file arg addhttp file arg new http file arg addemptyhttpfilearg addhttpfilearg httpfilearg get the number of files in the list return the number of files public int gethttp file arg count return gethttp file args collection size gethttpfileargcount gethttpfileargscollection get a single file param row the index of the file to return return the file at the specified index or null if no file exists at that index public http file arg gethttp file arg int row http file arg file null if row gethttp file arg count file http file arg gethttp file args collection get row get object value return file httpfilearg gethttpfilearg httpfilearg gethttpfileargcount httpfilearg gethttpfileargscollection getobjectvalue private bean shell interpreter bsh interpreter null public bean shell beanshellinterpreter bshinterpreter beanshell public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception if bsh interpreter null did we find bean shell throw new invalid variable exception bean shell not found j meter context jmctx j meter context service get context j meter variables vars jmctx get variables string script compound variable values 0 execute string var name non nls 1 if values length 1 var name compound variable values 1 execute trim string result str non nls 1 log debug script script try pass in some variables if current sampler null bsh interpreter set sampler current sampler non nls 1 if previous result null bsh interpreter set sample result previous result non nls 1 allow access to context and variables directly bsh interpreter set ctx jmctx non nls 1 bsh interpreter set vars vars non nls 1 bsh interpreter set props j meter utils getj meter properties non nls 1 bsh interpreter set thread name thread current thread get name non nls 1 execute the script object bsh out bsh interpreter eval script if bsh out null result str bsh out to string if vars null var name length 0 vars will be null on test plan vars put var name result str catch exception ex mainly for bsh eval error log warn error running bsh script ex log debug output result str return result str sampleresult previousresult currentsampler invalidvariableexception bshinterpreter beanshell invalidvariableexception beanshell jmetercontext jmetercontextservice getcontext jmetervariables getvariables compoundvariable varname varname compoundvariable resultstr currentsampler bshinterpreter currentsampler previousresult bshinterpreter sampleresult previousresult bshinterpreter bshinterpreter bshinterpreter jmeterutils getjmeterproperties bshinterpreter threadname currentthread getname bshout bshinterpreter bshout resultstr bshout tostring varname testplan varname resultstr evalerror resultstr resultstr public void log info string s log info s log_info public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters 1 2 values parameters to array try bsh interpreter new bean shell interpreter j meter utils get property init file log catch class not found exception e throw new invalid variable exception bean shell not found setparameters invalidvariableexception checkparametercount toarray bshinterpreter beanshellinterpreter jmeterutils getproperty init_file classnotfoundexception invalidvariableexception beanshell see org apache jmeter functions function get reference key public string get reference key return key getreferencekey getreferencekey see org apache jmeter functions function get argument desc public list get argument desc return desc getargumentdesc getargumentdesc create a new login config gui as a standalone component public cache manager gui init loginconfiggui cachemanagergui public string get label resource return cache manager title non nls 1 getlabelresource cache_manager_title a newly created component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui param element the test element to configure public void configure test element element super configure element clear each iteration set selected cache manager element get clear each iteration testelement testelement cleareachiteration setselected cachemanager getcleareachiteration implements j metergui component create test element public test element create test element cache manager element new cache manager modify test element element return element jmeterguicomponent createtestelement testelement createtestelement cachemanager cachemanager modifytestelement implements j metergui component modify test element test element public void modify test element test element element configure test element element cache manager element set clear each iteration clear each iteration is selected jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement cachemanager setcleareachiteration cleareachiteration isselected implements j metergui component clear gui public void clear gui super clear gui clear each iteration set selected false jmeterguicomponent cleargui cleargui cleargui cleareachiteration setselected initialize the components and layout of this component private void init set layout new border layout 0 5 set border make border clear each iteration new j check box j meter utils get res string clear cache per iter false j panel north panel new j panel north panel set layout new vertical layout 5 vertical layout both north panel add make title panel north panel add clear each iteration add north panel border layout north setlayout borderlayout setborder makeborder cleareachiteration jcheckbox jmeterutils getresstring clear_cache_per_iter jpanel northpanel jpanel northpanel setlayout verticallayout verticallayout northpanel maketitlepanel northpanel cleareachiteration northpanel borderlayout public abstract class abstract config gui extends abstractj meter gui component when a user right clicks on the component in the test tree or selects the edit menu when the component is selected the component will be asked to return a j popup menu that provides all the options available to the user from this component p this implementation returns menu items appropriate for most configuration components return a j popup menu appropriate for the component public j popup menu create popup menu return menu factory get default config element menu abstractconfiggui abstractjmeterguicomponent jpopupmenu jpopupmenu jpopupmenu createpopupmenu menufactory getdefaultconfigelementmenu this is the list of menu categories this gui component will be available under this implementation returns link org apache jmeter gui util menu factory config elements which is appropriate for most configuration components return a collection of strings where each element is one of the constants defined in menu factory public collection get menu categories return arrays as list new string menu factory config elements menufactory config_elements menufactory getmenucategories aslist menufactory config_elements prevent instantiation of utility class private file dialoger filedialoger prompts the user to choose a file from their filesystems for our own devious uses this method maintains the last directory the user visited before dismissing the dialog this does not imply they actually chose a file from that directory only that they closed the dialog there it is the caller s responsibility to check to see if the selected file is non null return the j file chooser that interacted with the user after they are finished using it null if no file was chosen public static j file chooser prompt to open file string exts j file chooser jfc null if lastjfc directory null string start j meter utils get prop default user dir non nls 1 non nls 2 if start length 0 jfc set current directory new file start clear file filters if exts null exts length 0 j meter file filter current filter new j meter file filter exts jfc add choosable file filter current filter jfc set accept all file filter used true jfc set file filter current filter int ret val jfc show open dialog gui package get instance get main frame lastjfc directory jfc get current directory get absolute path if ret val j file chooser approve option return jfc return null jfilechooser jfilechooser prompttoopenfile jfilechooser lastjfcdirectory jmeterutils getpropdefault setcurrentdirectory clearfilefilters jmeterfilefilter currentfilter jmeterfilefilter addchoosablefilefilter currentfilter setacceptallfilefilterused setfilefilter currentfilter retval showopendialog guipackage getinstance getmainframe lastjfcdirectory getcurrentdirectory getabsolutepath retval jfilechooser approve_option private static void clear file filters file filter filters jfc get choosable file filters for int x 0 x filters length x jfc remove choosable file filter filters x clearfilefilters filefilter getchoosablefilefilters removechoosablefilefilter public static j file chooser prompt to open file return prompt to open file new string 0 jfilechooser prompttoopenfile prompttoopenfile prompts the user to choose a file from their filesystems for our own devious uses this method maintains the last directory the user visited before dismissing the dialog this does not imply they actually chose a file from that directory only that they closed the dialog there it is the caller s responsibility to check to see if the selected file is non null return the j file chooser that interacted with the user after they are finished using it null if no file was chosen see prompt to open file public static j file chooser prompt to save file string filename return prompt to save file filename null jfilechooser prompttoopenfile jfilechooser prompttosavefile prompttosavefile get a j file chooser with a new file filter param filename file name param extensions list of extensions return the file chooser null if no file was chosen public static j file chooser prompt to save file string filename string extensions if lastjfc directory null string start j meter utils get prop default user dir non nls 1 non nls 2 if start length 0 jfc new j file chooser new file start lastjfc directory jfc get current directory get absolute path string ext jmx non nls 1 if filename null jfc set selected file new file lastjfc directory filename int i 1 if i filename last index of 1 non nls 1 ext filename substring i clear file filters if extensions null jfc add choosable file filter new j meter file filter extensions else jfc add choosable file filter new j meter file filter new string ext int ret val jfc show save dialog gui package get instance get main frame lastjfc directory jfc get current directory get absolute path if ret val j file chooser approve option return jfc return null jfilechooser filefilter filechooser jfilechooser prompttosavefile lastjfcdirectory jmeterutils getpropdefault jfilechooser lastjfcdirectory getcurrentdirectory getabsolutepath setselectedfile lastjfcdirectory lastindexof clearfilefilters addchoosablefilefilter jmeterfilefilter addchoosablefilefilter jmeterfilefilter retval showsavedialog guipackage getinstance getmainframe lastjfcdirectory getcurrentdirectory getabsolutepath retval jfilechooser approve_option public report page gui init reportpagegui initialize the components and layout of this component private void init set layout new border layout 10 10 set border make border set background color white j panel pane new j panel pane set layout new border layout 10 10 pane set background color white pane add this get name panel border layout north vertical panel options new vertical panel color white page title set background color white make index set background color white cssurl set background color white headerurl set background color white footerurl set background color white introduction set background color white options add page title options add make index options add cssurl options add headerurl options add footerurl options add introduction add pane border layout north add options border layout center setlayout borderlayout setborder makeborder setbackground jpanel jpanel setlayout borderlayout setbackground getnamepanel borderlayout verticalpanel verticalpanel pagetitle setbackground makeindex setbackground setbackground setbackground setbackground setbackground pagetitle makeindex borderlayout borderlayout public j popup menu create popup menu j popup menu pop new j popup menu j menu add menu new j menu j meter utils get res string add add menu add report menu factory make menu item new table gui get static label table gui class get name add add menu add report menu factory make menu item new bar chart gui get static label bar chart gui class get name add add menu add report menu factory make menu item new line graph gui get static label line graph gui class get name add pop add add menu report menu factory add file menu pop report menu factory add edit menu pop true return pop jpopupmenu createpopupmenu jpopupmenu jpopupmenu jmenu addmenu jmenu jmeterutils getresstring addmenu reportmenufactory makemenuitem tablegui getstaticlabel tablegui getname addmenu reportmenufactory makemenuitem barchartgui getstaticlabel barchartgui getname addmenu reportmenufactory makemenuitem linegraphgui getstaticlabel linegraphgui getname addmenu reportmenufactory addfilemenu reportmenufactory addeditmenu public test element create test element report page element new report page modify test element element return element testelement createtestelement reportpage reportpage modifytestelement public void modify test element test element element super configure test element element report page page report page element page setcss cssurl get text page set footerurl footerurl get text page set headerurl headerurl get text page set index string value of make index is selected page set introduction introduction get text page set title page title get text modifytestelement testelement configuretestelement reportpage reportpage gettext setfooterurl gettext setheaderurl gettext setindex valueof makeindex isselected setintroduction gettext settitle pagetitle gettext public void configure test element element super configure element report page page report page element cssurl set text page getcss footerurl set text page get footerurl headerurl set text page get headerurl make index set selected page get index introduction set text page get introduction page title set text page get title testelement reportpage reportpage settext settext getfooterurl settext getheaderurl makeindex setselected getindex settext getintroduction pagetitle settext gettitle public publisher boolean use props string jndi string url string connfactory string topic boolean use auth string user string pwd super context ctx initjndi use props jndi url use auth user pwd if ctx null init connection ctx connfactory topic else log error could not initialize jndi initial context factory useprops useauth useprops useauth initconnection public context initjndi boolean use props string jndi string url boolean use auth string user string pwd if use props try return new initial context catch naming exception e log error e get message return null else return initial context factory lookup context jndi url use auth user pwd useprops useauth useprops initialcontext namingexception getmessage initialcontextfactory lookupcontext useauth public void init connection context ctx string connfactory string topic try connection factory get topic connection factory ctx connfactory this conn connection factory get topic connection this topic initial context factory lookup topic ctx topic this session this conn create topic session false topic session auto acknowledge this publisher this session create publisher this topic log info created the topic connection successfully catch jms exception e log error connection error e get message initconnection connectionfactory gettopicconnectionfactory connectionfactory gettopicconnection initialcontextfactory lookuptopic createtopicsession topicsession auto_acknowledge createpublisher jmsexception getmessage public void publish string text try text message msg this session create text message text this publisher publish msg catch jms exception e log error e get message textmessage createtextmessage jmsexception getmessage public void publish serializable contents try object message msg this session create object message contents this publisher publish msg catch jms exception e log error e get message objectmessage createobjectmessage jmsexception getmessage clise will close the session public void close try log info publisher closed this publisher close this session close this conn close this publisher null this session null this conn null catch jms exception e log error e get message catch throwable e log error e get message jmsexception getmessage getmessage protected transient array list write functors new array list public abstract tree table model tree node root this root node root arraylist writefunctors arraylist abstracttreetablemodel treenode rootnode public abstract tree table model tree node root boolean editable this root node root abstracttreetablemodel treenode rootnode public abstract tree table model string headers functor read functors functor write functors class editor classes this headers add all arrays as list headers this classes add all arrays as list editor classes this read functors new array list arrays as list read functors this write functors new array list arrays as list write functors abstracttreetablemodel readfunctors writefunctors editorclasses addall aslist addall aslist editorclasses readfunctors arraylist aslist readfunctors writefunctors arraylist aslist writefunctors the root node for the tree table return the root node public object get root node return this root node treetable getrootnode rootnode see org apache jorphan gui tree table model get value at java lang object int public object get value at object node int col return null treetablemodel getvalueat getvalueat see org apache jorphan gui tree table model is cell editable java lang object int public boolean is cell editable object node int col return false treetablemodel iscelleditable iscelleditable see org apache jorphan gui tree table model set value at java lang object java lang object int public void set value at object val object node int column treetablemodel setvalueat setvalueat the implementation is exactly the same as object table model get column count public int get column count return headers size objecttablemodel getcolumncount getcolumncount the implementation is exactly the same as object table model get row count public int get row count if objects null return 0 return objects size objecttablemodel getrowcount getrowcount by default the abstract class returns true it is up to subclasses to override the implementation public boolean is cell editable int row index int column index return true iscelleditable rowindex columnindex public class get column class int arg0 return class classes get arg0 getcolumnclass subclasses need to implement the logic for the method and return the value at the specific cell public object get value at int row index int column index return null getvalueat rowindex columnindex public void set value at object a value int row index int column index setvalueat avalue rowindex columnindex public string get column name int column index return string headers get column index getcolumnname columnindex columnindex public int get child count object parent return 0 getchildcount public object get child object parent int index return null getchild the implementation checks if the object is a treenode if it is it returns is leaf otherwise it returns false param node return whether object is a leaf node or not public boolean is leaf object node if node instanceof tree node return tree node node is leaf else return false isleaf isleaf treenode treenode isleaf public void add table model listener table model listener l this listener add table model listener class l addtablemodellistener tablemodellistener tablemodellistener public void remove table model listener table model listener l this listener remove table model listener class l removetablemodellistener tablemodellistener tablemodellistener public void node structure changed tree node node nodestructurechanged treenode public void fire tree nodes changed tree node source object path int indexes object children firetreenodeschanged treenode public void clear data int size get row count objects clear super fire table rows deleted 0 size cleardata getrowcount firetablerowsdeleted public string from file init if log is debug enabled log debug construct this stringfromfile isdebugenabled private void init my value err ind my name stringfromfile non nls 1 myvalue err_ind myname stringfromfile_ private void close file if my bread null return string tn thread current thread get name log info tn closing file file name non nls 1 try my bread close fis close catch io exception e log error close file error e to string non nls 1 closefile mybread currentthread getname filename mybread ioexception closefile tostring private void open file string tn thread current thread get name file name compound variable values 0 execute string start if values length param start start compound variable values param start 1 execute try my start integer value of start int value catch number format exception e my start count unused don t process invalid numbers have we used my current yet set to 1 if start number is missing to allow for end without start if my current count unused my current my start count unused 1 my start if values length param end string tmp compound variable values param end 1 execute try my end integer value of tmp int value catch number format exception e my end count unused don t process invalid numbers including if values length param start log info tn start my start current my current end my end non nls 1 if my end count unused if my current my end log info tn no more files to process my current my end non nls 1 my bread null return decimal format adds the number to the end of the format if there are no formatting characters so we need a way to prevent this from messing up the file name if my start count unused only try to format if there is a number log info tn using format file name try decimal format my formatter new decimal format file name file name my formatter format my current catch number format exception e log warn bad file name format e my current for next time log info tn opening file file name non nls 1 try fis new file reader file name my bread new buffered reader fis catch exception e log error open file error e to string non nls 1 my bread null openfile currentthread getname filename compoundvariable param_start compoundvariable param_start mystart valueof intvalue numberformatexception mystart count_unused mycurrent mycurrent count_unused mycurrent mystart count_unused mystart param_end compoundvariable param_end myend valueof intvalue numberformatexception myend count_unused param_start mystart mycurrent myend myend count_unused mycurrent myend mycurrent myend mybread decimalformat mystart count_unused filename decimalformat myformatter decimalformat filename filename myformatter mycurrent numberformatexception mycurrent filename filereader filename mybread bufferedreader openfile tostring mybread public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception if values length param name my name compound variable values param name 1 execute trim my value err ind to avoid re opening the file repeatedly after an error only try to open it in the first execute call it may be re opened at eof but that will cause at most one failure if first time open file first time false if null my bread did we open the file try string line my bread read line if line null eof re open file string tn thread current thread get name log info tn eof on file file name non nls 1 close file open file if my bread null line my bread read line else line err ind if my end count unused are we processing a file sequence log info tn detected end of sequence throw new j meter stop thread exception end of sequence my value line catch io exception e string tn thread current thread get name log error tn error reading file e to string non nls 1 else file was not opened successfully if my end count unused are we processing a file sequence string tn thread current thread get name log info tn detected end of sequence throw new j meter stop thread exception end of sequence if my name length 0 j meter variables vars get variables if vars null can be null if called from config item test ended method vars put my name my value if log is debug enabled string tn thread current thread get name log debug tn name non nls 1 my name value my value non nls 1 return my value sampleresult previousresult currentsampler invalidvariableexception param_name myname compoundvariable param_name myvalue err_ind firsttime openfile firsttime mybread mybread readline currentthread getname filename closefile openfile mybread mybread readline err_ind myend count_unused jmeterstopthreadexception myvalue ioexception currentthread getname tostring myend count_unused currentthread getname jmeterstopthreadexception myname jmetervariables getvariables testended myname myvalue isdebugenabled currentthread getname myname myvalue myvalue public synchronized void set parameters collection parameters throws invalid variable exception log debug this string from file set parameters non nls 1 check parameter count parameters min param count max param count values parameters to array string buffer sb new string buffer 40 sb append set parameters non nls 1 for int i 0 i values length i if i 0 sb append sb append compound variable values i get raw parameters sb append non nls 1 log info sb to string n b set parameters is called before the test proper is started and thus variables are not interpreted at this point so defer the file open until later to allow variable file names to be used first time true setparameters invalidvariableexception stringfromfile setparameters checkparametercount min_param_count max_param_count toarray stringbuffer stringbuffer setparameters compoundvariable getrawparameters tostring setparameters firsttime see org apache jmeter functions function get reference key public string get reference key return key getreferencekey getreferencekey see org apache jmeter functions function get argument desc public list get argument desc return desc getargumentdesc getargumentdesc public void test started teststarted public void test started string host teststarted public void test ended this test ended non nls 1 testended testended public void test ended string host close file testended closefile public void test iteration start loop iteration event event testiterationstart loopiterationevent see org apache jmeter gui action command do action action event public void do action action event e j meter tree node nodes gui package get instance get tree listener get selected nodes if e get action command equals action names enable log debug enabling currently selected gui objects enable components nodes true else if e get action command equals action names disable log debug disabling currently selected gui objects enable components nodes false doaction actionevent doaction actionevent jmetertreenode guipackage getinstance gettreelistener getselectednodes getactioncommand actionnames enablecomponents getactioncommand actionnames enablecomponents private void enable components j meter tree node nodes boolean enable gui package pack gui package get instance for int i 0 i nodes length i nodes i set enabled enable pack get gui nodes i get test element set enabled enable enablecomponents jmetertreenode guipackage guipackage getinstance setenabled getgui gettestelement setenabled see org apache jmeter gui action command get action names public set get action names return commands getactionnames getactionnames public class undo variable replacement extends abstract transformer public undo variable replacement compound variable master function map variables super set master function master function set variables variables undovariablereplacement abstracttransformer undovariablereplacement compoundvariable masterfunction setmasterfunction masterfunction setvariables public j meter property transform value j meter property prop throws invalid variable exception iterator iter get variables key set iterator string input prop get string value while iter has next string key string iter next string value string get variables get key input string utilities substitute input key value string property new prop new string property prop get name input return new prop jmeterproperty transformvalue jmeterproperty invalidvariableexception getvariables keyset getstringvalue hasnext getvariables stringutilities stringproperty newprop stringproperty getname newprop private default configuration root config null public test element saver string name this name name defaultconfiguration rootconfig testelementsaver public configuration get configuration return root config getconfiguration rootconfig public void start test element test element el default configuration config new default configuration testelement testelement config set attribute class el get class get name if root config null root config config if name null name length 0 root config set attribute name name else set config name config stack add config starttestelement testelement defaultconfiguration defaultconfiguration setattribute getclass getname rootconfig rootconfig rootconfig setattribute setconfigname public void set config name default configuration config if stack get last instanceof configuration object key stack remove last config set attribute name key to string setconfigname defaultconfiguration getlast removelast setattribute tostring see test element traverser end test element test element public void end test element test element el testelementtraverser endtestelement testelement endtestelement testelement public void simple property value j meter property value try object parent stack get last if parent instanceof configuration default configuration config new default configuration property property config set value value null value to string config set attribute name parent to string config set attribute old save service xml space old save service preserve stack remove last stack add config if parent instanceof default configuration value instanceof configuration default configuration parent add child configuration value else if parent instanceof default configuration value instanceof configuration default configuration config new default configuration string string config set value value null value to string config set attribute old save service xml space old save service preserve default configuration parent add child config catch no such element exception e simplepropertyvalue jmeterproperty getlast defaultconfiguration defaultconfiguration setvalue tostring setattribute tostring setattribute oldsaveservice xml_space oldsaveservice removelast defaultconfiguration defaultconfiguration addchild defaultconfiguration defaultconfiguration defaultconfiguration setvalue tostring setattribute oldsaveservice xml_space oldsaveservice defaultconfiguration addchild nosuchelementexception public void start map map property map default configuration config new default configuration map map config set attribute class map get object value get class get name config set attribute name map get name config set attribute prop type map get class get name stack add config startmap mapproperty defaultconfiguration defaultconfiguration setattribute getobjectvalue getclass getname setattribute getname setattribute proptype getclass getname public void start collection collection property col default configuration config new default configuration collection collection config set attribute class col get object value get class get name config set attribute name col get name config set attribute prop type col get class get name stack add config startcollection collectionproperty defaultconfiguration defaultconfiguration setattribute getobjectvalue getclass getname setattribute getname setattribute proptype getclass getname see test element traverser end property j meter property public void end property j meter property key finish config testelementtraverser endproperty jmeterproperty endproperty jmeterproperty finishconfig private void finish config if stack size 1 configuration config configuration stack remove last default configuration stack get last add child config finishconfig removelast defaultconfiguration getlast addchild public void start property j meter property key if key instanceof collection property start collection collection property key else if key instanceof map property start map map property key else if key instanceof test element property stack add last key get name else default configuration config new default configuration property property config set value key get string value config set attribute name key get name config set attribute prop type key get class get name config set attribute old save service xml space old save service preserve stack add last config startproperty jmeterproperty collectionproperty startcollection collectionproperty mapproperty startmap mapproperty testelementproperty addlast getname defaultconfiguration defaultconfiguration setvalue getstringvalue setattribute getname setattribute proptype getclass getname setattribute oldsaveservice xml_space oldsaveservice addlast linked list stack new linked list public disabled component remover hash tree tree this tree tree linkedlist linkedlist disabledcomponentremover hashtree public void add node object node hash tree sub tree stack add last node addnode hashtree subtree addlast public void subtract node object remove last stack remove last if remove last instanceof test element log warn expected class test element found remove last get class get name return test element last node test element remove last if last node get property as boolean test element enabled log info removing last node todo not sure this is ever called tree get tree stack remove last node subtractnode removelast removelast removelast testelement testelement removelast getclass getname testelement lastnode testelement removelast lastnode getpropertyasboolean testelement lastnode gettree lastnode public void process path processpath default constructor public user parameter modifier userparametermodifier runs before the start of every test reload the sequencer with the latest parameter data for each user public void test started try to populate all users if fail leave as any empty set list all users new linked list try user parameterxml parser readxml parameters new user parameterxml parser all users readxml parameters getxml parameters get xml uri catch exception e do nothing now object all users contains an empty set log error unable to read parameters from xml file get xml uri log error no unique values for http requests will be substituted for each thread e all available users new user sequence all users teststarted allusers allusers linkedlist userparameterxmlparser readxmlparameters userparameterxmlparser allusers readxmlparameters getxmlparameters getxmluri allusers getxmluri allavailableusers usersequence allusers public void test ended testended public void test started string host test started teststarted teststarted public void test ended string host testended modifies an entry object to replace the value of any url parameter that matches a parameter name in the xml file public void process sampler entry get thread context get current sampler if entry instanceof http sampler base return http sampler base config http sampler base entry map current user all available users get next user mods property iterator iter config get arguments iterator while iter has next argument arg argument iter next get object value if parameter name exists in http request then change its value note each jmeter thread ie user gets to have unique values if current user contains key arg get name arg set value string current user get arg get name getthreadcontext getcurrentsampler httpsamplerbase httpsamplerbase httpsamplerbase currentuser allavailableusers getnextusermods propertyiterator getarguments hasnext getobjectvalue currentuser containskey getname setvalue currentuser getname return the current xml file name to be read to obtain the parameter data for all users return the name of the xml file containing parameter data for each user public string get xml uri return this get property as string xmluri getxmluri getpropertyasstring from the gui screen set file name of xml to read param xmluri the name of the xml file containing the http name value pair parameters per user public void set xml uri string xmluri set property xmluri xmluri setxmluri setproperty see test listener test iteration start loop iteration event public void test iteration start loop iteration event event testlistener testiterationstart loopiterationevent testiterationstart loopiterationevent public object clone user parameter modifier clone user parameter modifier super clone clone all available users all available users return clone userparametermodifier userparametermodifier allavailableusers allavailableusers public receive subscriber boolean use props string jndi string url string connfactory string topic boolean use auth string user string pwd context ctx initjndi use props jndi url use auth user pwd topic connection conn null topic topic null topic session session null topic subscriber subscriber null if ctx null try connection factory get topic connection factory ctx connfactory conn connection factory get topic connection topic initial context factory lookup topic ctx topic session this conn create topic session false topic session auto acknowledge subscriber this session create subscriber this topic log info created the topic connection successfully catch jms exception e log error connection error e get message else log error could not initialize jndi initial context factory this conn conn this topic topic this session session this subscriber subscriber receivesubscriber useprops useauth useprops useauth topicconnection _conn _topic topicsession _session topicsubscriber _subscriber connectionfactory gettopicconnectionfactory _conn connectionfactory gettopicconnection _topic initialcontextfactory lookuptopic _session createtopicsession topicsession auto_acknowledge _subscriber createsubscriber jmsexception getmessage _conn _topic _session _subscriber initialize the jndi initial context param use props param jndi param url param use auth param user param pwd return the jndi initial context or null called by ctor private context initjndi boolean use props string jndi string url boolean use auth string user string pwd if use props try return new initial context catch naming exception e log error e get message return null else return initial context factory lookup context jndi url use auth user pwd useprops useauth useprops useauth useprops initialcontext namingexception getmessage initialcontextfactory lookupcontext useauth set the number of iterations for each call to sample param loop public void set loop int loop this loop loop setloop resume will call connection start and begin receiving messages from the jms provider public void resume if this conn null log error connection not set up return try this conn start catch jms exception e log error failed to start recieving jmsexception get the message as a string public synchronized string get message return this buffer to string getmessage tostring get the message s as an array of byte public synchronized byte get byte result return this buffer to string get bytes getbyteresult tostring getbytes close will stop the connection first then it closes the subscriber session and connection public synchronized void close called from test ended thread try this run false this conn stop this subscriber close this session close this conn close this clientthread interrupt this clientthread null this buffer set length 0 catch jms exception e log error e get message catch exception e log error e get message testended setlength jmsexception getmessage getmessage reset the receiver ready for receiving any further messages public synchronized void reset counter 0 this buffer set length 0 setlength increment the count and return the new value param increment public synchronized int count int increment counter increment return counter start will create a new thread and pass this class once the thread is created it calls thread start public void start no point starting thread unless subscriber exists if subscriber null log error subscriber has not been set up return this clientthread new thread this subscriber2 this clientthread start run calls listen to begin listening for inbound messages from the provider updates the count field so the caller can check how many messages have been receieved public void run if subscriber null just in case log error subscriber has not been set up return while run try message message this subscriber receive if message null message instanceof text message text message msg text message message string text msg get text if text trim length 0 synchronized this this buffer append text count 1 catch jms exception e log error communication error e get message textmessage textmessage textmessage gettext jmsexception getmessage private static final thread local local input new thread local protected object initial value return new pattern matcher input new char 0 threadlocal localinput threadlocal initialvalue patternmatcherinput protected boolean is reusable return true isreusable make sure to compile the regular expression upon instantiation protected regexphtml parser super regexphtmlparser public iterator get embedded resourceur ls byte html url base url url collection urls perl5 matcher matcher j meter utils get matcher pattern matcher input input pattern matcher input local input get todo find a way to avoid the cost of creating a string here probably a new pattern matcher input working on a byte would do better input set input new string html pattern pattern j meter utils get pattern cache get pattern regexp perl5 compiler case insensitive mask perl5 compiler singleline mask perl5 compiler read only mask while matcher contains input pattern match result match matcher get match string s if log is debug enabled log debug match groups match groups match to string check for a base href for int g 1 g num base groups g match groups g s match group g if s null if log is debug enabled log debug new base url s base url to string try base url conversion utils make relativeurl base url s catch malformedurl exception e doesn t even look like a url maybe it isn t ignore the exception if log is debug enabled log debug can t build base url from rl s in page base url e for int g num base groups 1 g match groups g s match group g if s null if log is debug enabled log debug group g match group g urls addurl s base url return urls iterator getembeddedresourceurls baseurl urlcollection perl5matcher jmeterutils getmatcher patternmatcherinput patternmatcherinput localinput patternmatcherinput setinput jmeterutils getpatterncache getpattern perl5compiler case_insensitive_mask perl5compiler singleline_mask perl5compiler read_only_mask matchresult getmatch isdebugenabled tostring num_base_groups isdebugenabled baseurl baseurl tostring baseurl conversionutils makerelativeurl baseurl malformedurlexception isdebugenabled baseurl num_base_groups isdebugenabled baseurl protected string value public nv pair nvpair the constructor takes a name and value which represent http request parameters param name param value public nv pair string name string value this name name this value value nvpair set the name param name public void set name string name this name name setname set the value param value public void set value string value this value value setvalue return the name return name public string get name return this name getname return the value return value public string get value return this value getvalue create a new name panel with the default name public assertion scope panel init namepanel assertionscopepanel initialize the gui components and layout private void init set layout new border layout 5 0 set border border factory create titled border j meter utils get res string assertion scope non nls 1 all button new j radio button j meter utils get res string assertion scope all parent button new j radio button j meter utils get res string assertion scope parent parent button set selected true child button new j radio button j meter utils get res string assertion scope children button group group new button group group add all button group add parent button group add child button j panel button panel new horizontal panel button panel add parent button button panel add child button button panel add all button add button panel setlayout borderlayout setborder borderfactory createtitledborder jmeterutils getresstring assertion_scope allbutton jradiobutton jmeterutils getresstring assertion_scope_all parentbutton jradiobutton jmeterutils getresstring assertion_scope_parent parentbutton setselected childbutton jradiobutton jmeterutils getresstring assertion_scope_children buttongroup buttongroup allbutton parentbutton childbutton jpanel buttonpanel horizontalpanel buttonpanel parentbutton buttonpanel childbutton buttonpanel allbutton buttonpanel public void clear gui parent button set selected true cleargui parentbutton setselected public int get selection if parent button is selected return 0 return 1 getselection parentbutton isselected public void set scope all all button set selected true setscopeall allbutton setselected public void set scope children child button set selected true setscopechildren childbutton setselected public void set scope parent parent button set selected true setscopeparent parentbutton setselected public boolean is scope parent return parent button is selected isscopeparent parentbutton isselected public boolean is scope children return child button is selected isscopechildren childbutton isselected private final random random new random private file server base new file default base log info default base default base fileserver default_base default_base public static file server get file server return server fileserver getfileserver public void reset base throws io exception set basedir default base resetbase ioexception setbasedir default_base public synchronized void set basedir string basedir throws io exception if files open throw new io exception files are still open cannot change base directory files clear if basedir null base new file basedir if base is directory base base get parent file log info set new base base setbasedir ioexception filesopen ioexception isdirectory getparentfile public synchronized string get base dir return base get absolute path getbasedir getabsolutepath creates an association between a filename and a file input output object and stores it for later use unless it is already stored param filename relative to base or absolute file name must not be null public synchronized void reserve file string filename reserve file filename null inputoutputobject reservefile reservefile creates an association between a filename and a file input output object and stores it for later use unless it is already stored param filename relative to base or absolute file name must not be null param charset name the character set encoding to use for the file may be null public synchronized void reserve file string filename string charset name reserve file filename charset name filename inputoutputobject charsetname reservefile charsetname reservefile charsetname creates an association between a filename and a file input output object and stores it for later use unless it is already stored param filename relative to base or absolute file name must not be null param charset name the character set encoding to use for the file may be null param alias the name to be used to access the object must not be null public synchronized void reserve file string filename string charset name string alias if filename null throw new illegal argument exception filename must not be null if alias null throw new illegal argument exception alias must not be null if files contains key alias file f new file filename file entry file new file entry f is absolute f new file base filename null charset name if filename equals alias log info stored filename else log info stored filename alias alias files put alias file inputoutputobject charsetname reservefile charsetname illegalargumentexception illegalargumentexception containskey fileentry fileentry isabsolute charsetname get the next line of the named file recycle by default param filename return string containing the next line in the file throws io exception public string read line string filename throws io exception return read line filename true ioexception readline ioexception readline get the next line of the named file param filename param recycle should file be restarted at eof return string containing the next line in the file null if eof reached and not recycle throws io exception public synchronized string read line string filename boolean recycle throws io exception file entry file entry file entry files get filename if file entry null if file entry input output object null file entry input output object create buffered reader file entry filename else if file entry input output object instanceof reader throw new io exception file filename already in use buffered reader reader buffered reader file entry input output object string line reader read line if line null recycle reader close reader create buffered reader file entry filename file entry input output object reader line reader read line if log is debug enabled log debug read line return line throw new io exception file never reserved filename ioexception readline ioexception fileentry fileentry fileentry fileentry fileentry inputoutputobject fileentry inputoutputobject createbufferedreader fileentry fileentry inputoutputobject ioexception bufferedreader bufferedreader fileentry inputoutputobject readline createbufferedreader fileentry fileentry inputoutputobject readline isdebugenabled ioexception private buffered reader create buffered reader file entry file entry string filename throws io exception file input stream fis new file input stream file entry file input stream reader isr null if file encoding is specified read using that encoding otherwise use default platform encoding string charset name file entry char set encoding if charset name null charset name trim length 0 isr new input stream reader fis charset name else isr new input stream reader fis return new buffered reader isr bufferedreader createbufferedreader fileentry fileentry ioexception fileinputstream fileinputstream fileentry inputstreamreader charsetname fileentry charsetencoding charsetname charsetname inputstreamreader charsetname inputstreamreader bufferedreader public synchronized void write string filename string value throws io exception file entry file entry file entry files get filename if file entry null if file entry input output object null file entry input output object create buffered writer file entry filename else if file entry input output object instanceof writer throw new io exception file filename already in use buffered writer writer buffered writer file entry input output object if log is debug enabled log debug write value writer write value else throw new io exception file never reserved filename ioexception fileentry fileentry fileentry fileentry fileentry inputoutputobject fileentry inputoutputobject createbufferedwriter fileentry fileentry inputoutputobject ioexception bufferedwriter bufferedwriter fileentry inputoutputobject isdebugenabled ioexception private buffered writer create buffered writer file entry file entry string filename throws io exception file output stream fos new file output stream file entry file output stream writer osw null if file encoding is specified write using that encoding otherwise use default platform encoding string charset name file entry char set encoding if charset name null charset name trim length 0 osw new output stream writer fos charset name else osw new output stream writer fos return new buffered writer osw bufferedwriter createbufferedwriter fileentry fileentry ioexception fileoutputstream fileoutputstream fileentry outputstreamwriter charsetname fileentry charsetencoding charsetname charsetname outputstreamwriter charsetname outputstreamwriter bufferedwriter public void close files throws io exception iterator iter files entry set iterator while iter has next map entry me map entry iter next close file string me get key file entry me get value files clear closefiles ioexception entryset hasnext closefile getkey fileentry getvalue param name throws io exception public synchronized void close file string name throws io exception file entry file entry file entry files get name close file name file entry ioexception closefile ioexception fileentry fileentry fileentry closefile fileentry private void close file string name file entry file entry throws io exception if file entry null file entry input output object null log info close name if file entry input output object instanceof reader reader file entry input output object close else if file entry input output object instanceof writer writer file entry input output object close else log error unknown input output object type file entry input output object get class file entry input output object null closefile fileentry fileentry ioexception fileentry fileentry inputoutputobject fileentry inputoutputobject fileentry inputoutputobject fileentry inputoutputobject fileentry inputoutputobject inputoutputobject fileentry inputoutputobject getclass fileentry inputoutputobject protected boolean files open iterator iter files values iterator while iter has next file entry file entry file entry iter next if file entry input output object null return true return false filesopen hasnext fileentry fileentry fileentry fileentry inputoutputobject method will get a random file in a base directory todo hey not sure this method belongs here file server is for threadsafe file access relative to current test s base directory param basedir return a random file from the basedir that matches one of the extensions public file get random file string basedir string extensions file input null if basedir null file src new file basedir if src is directory src list null file lfiles src list files new j meter file filter extensions int count lfiles length input lfiles random next int count return input fileserver getrandomfile isdirectory listfiles jmeterfilefilter nextint private string char set encoding file entry file f object o string e file f input output object o char set encoding e charsetencoding fileentry inputoutputobject charsetencoding public default page summary super defaultpagesummary returns the elapsed time in milliseconds public long get elapsed time return end start getelapsedtime public long get end time stamp return end getendtimestamp see org apache jmeter report writers page summary get file name public string get file name return file name pagesummary getfilename getfilename filename see org apache jmeter report writers page summary get page title public string get page title return title pagesummary getpagetitle getpagetitle public long get start time stamp return start getstarttimestamp see org apache jmeter report writers page summary is successful public boolean is successful return success pagesummary issuccessful issuccessful see org apache jmeter report writers page summary page started public void page started start system current time millis pagesummary pagestarted pagestarted currenttimemillis see org apache jmeter report writers page summary page ended public void page ended end system current time millis pagesummary pageended pageended currenttimemillis see org apache jmeter report writers page summary set file name java lang string public void set file name string file this file name file pagesummary setfilename setfilename filename see org apache jmeter report writers page summary set page title java lang string public void set page title string title this title title pagesummary setpagetitle setpagetitle see org apache jmeter report writers page summary set successful boolean public void set successful boolean success this success success pagesummary setsuccessful setsuccessful private string query string never null public http sample result super set data encoding default http encoding default if encoding not provided be the page querystring httpsampleresult setdataencoding default_http_encoding public http sample result long elapsed super elapsed true httpsampleresult construct a parent result for an already existing result essentially cloning it param res existing sample result public http sample result http sample result res super res method res method cookies res cookies query string res query string redirect location res redirect location httpsampleresult httpsampleresult querystring querystring redirectlocation redirectlocation public void sethttp method string method this method method sethttpmethod public string gethttp method return method gethttpmethod public void set redirect location string redirect location this redirect location redirect location setredirectlocation redirectlocation redirectlocation redirectlocation public string get redirect location return redirect location getredirectlocation redirectlocation determine whether this result is a redirect return true iif res is an http redirect response public boolean is redirect final string redirect codes 301 302 303 not 304 string code get response code for int i 0 i redirect codes length i if redirect codes i equals code return true return false isredirect redirect_codes getresponsecode redirect_codes redirect_codes public string get sampler data string buffer sb new string buffer sb append method url u super geturl if u null sb append sb append u to string sb append n include request body if it is a post or put if http constants post equals method http constants put equals method sb append npost data n sb append query string sb append n if cookies length 0 sb append n cookie data n sb append cookies else sb append n no cookies sb append n final string samp data super get sampler data if samp data null sb append samp data return sb to string getsamplerdata stringbuffer stringbuffer tostring httpconstants httpconstants querystring ncookie sampdata getsamplerdata sampdata sampdata tostring return cookies as a string public string get cookies return cookies getcookies param string representing the cookies public void set cookies string string if string null cookies non nls 1 else cookies string setcookies fetch the query string return the query string public string get query string return query string getquerystring querystring save the query string param string the query string public void set query string string string if string null query string non nls 1 else query string string setquerystring querystring querystring overrides the method from sample result so the encoding can be extracted from the meta content type if necessary updates the data encoding field if the content type is found return the data encoding value as a string public string get data encoding with default if get data encoding no default null get content type starts with text html non nls 1 byte bytes get response data get the start of the file string prefix new string bytes 0 math min bytes length 1000 to lower case java util locale english extract the content type if present final string metatag meta http equiv content type content non nls 1 int tagstart prefix index of metatag if tagstart 1 tagstart metatag length int tagend prefix index of tagstart non nls 1 if tagend 1 final string ct new string bytes tagstart tagend tagstart set encoding and type ct update the data encoding return super get data encoding with default sampleresult dataencoding dataencoding getdataencodingwithdefault getdataencodingnodefault getcontenttype startswith getresponsedata tolowercase indexof indexof setencodingandtype dataencoding getdataencodingwithdefault private static final string condition while controller condition non nls 1 public while controller whilecontroller whilecontroller private boolean end of loop boolean loop end string cnd get condition trim log debug condition string cnd boolean res if blank only check previous sample when at end of loop if loop end cnd length 0 last equals ignore case cnd non nls 1 j meter variables thread vars j meter context service get context get variables res false equals ignore case thread vars get j meter thread last sample ok non nls 1 else cnd may be null if next called us res false equals ignore case cnd non nls 1 log debug condition value res return res endofloop loopend getcondition loopend equalsignorecase jmetervariables threadvars jmetercontextservice getcontext getvariables equalsignorecase threadvars jmeterthread last_sample_ok equalsignorecase protected sampler next is null throws next is null exception re initialize if end of loop true return null return next nextisnull nextisnullexception reinitialize endofloop public sampler next if is first if end of loop false return null return super next isfirst endofloop param string the condition to save public void set condition string string log debug set condition string set property new string property condition string setcondition setcondition setproperty stringproperty return the condition public string get condition string cnd j meter property prop get property condition prop recover running version this cnd prop get string value return cnd getcondition jmeterproperty getproperty recoverrunningversion getstringvalue creates a generic controller public generic controller genericcontroller public void initialize reset current reset iter count done false todo should this use set done first true todo should this use set first test element elem for int i 0 i sub controllers and samplers size i elem test element sub controllers and samplers get i if elem instanceof controller controller elem initialize resetcurrent resetitercount setdone setfirst testelement subcontrollersandsamplers testelement subcontrollersandsamplers resets the controller ul li reset current i e current 0 li li increment iteration count li li sets first true li li recover running version to set the controller back to the initial state li ul protected void re initialize reset current increment iter count set first true recover running version resetcurrent recoverrunningversion reinitialize resetcurrent incrementitercount setfirst recoverrunningversion p determines the next sampler to be processed p p if is done returns null p p gets the list element using current pointer if this is null calls link next is null p p if the list element is a sampler calls link next isa sampler sampler otherwise calls link next isa controller controller p p if any of the called methods throws next is null exception returns null otherwise the value obtained above is returned p return the next sampler or null public sampler next fire iter events if log is debug enabled log debug calling next on this get class get name if is done return null sampler return value null try test element current element get current element set current element current element if current element null increment current return value next is null else if current element instanceof sampler return value next isa sampler sampler current element else must be a controller return value next isa controller controller current element catch next is null exception e return return value isdone nextisnull nextisasampler nextisacontroller nextisnullexception fireiterevents isdebugenabled getclass getname isdone returnvalue testelement currentelement getcurrentelement setcurrentelement currentelement currentelement incrementcurrent returnvalue nextisnull currentelement returnvalue nextisasampler currentelement returnvalue nextisacontroller currentelement nextisnullexception returnvalue see org apache jmeter control controller is done public boolean is done return done isdone isdone protected void set done boolean done this done done setdone protected boolean is first return first isfirst public void set first boolean b first b setfirst called by next if the element is a controller and returns the next sampler from the controller if this is null then updates the current pointer and makes recursive call to next param controller return the next sampler throws next is null exception protected sampler next isa controller controller controller throws next is null exception sampler sampler controller next if sampler null current returned null controller sampler next return sampler nextisnullexception nextisacontroller nextisnullexception currentreturnednull increment the current pointer and return the element called by next if the element is a sampler may be overriden by sub classes param element return input element throws next is null exception protected sampler next isa sampler sampler element throws next is null exception increment current return element nextisnullexception nextisasampler nextisnullexception incrementcurrent called by next when get current element returns null reinitialises the controller return null always for this class throws next is null exception protected sampler next is null throws next is null exception re initialize return null getcurrentelement nextisnullexception nextisnull nextisnullexception reinitialize if the controller is done remove it from the list otherwise increment to next entry in list param c controller protected void current returned null controller c if c is done remove current element else increment current currentreturnednull isdone removecurrentelement incrementcurrent gets the sub controllers attribute of the generic controller object return the sub controllers value protected list get sub controllers return sub controllers and samplers subcontrollers genericcontroller subcontrollers getsubcontrollers subcontrollersandsamplers private void add element test element child sub controllers and samplers add child addelement testelement subcontrollersandsamplers empty implementation does nothing param current element throws next is null exception protected void set current element test element current element throws next is null exception currentelement nextisnullexception setcurrentelement testelement currentelement nextisnullexception p gets the element indicated by the code current code index if one exists from the code sub controllers and samplers code list p p if the code sub controllers and samplers code list is empty then set done true and throw next is null exception p return the current element or null if current index too large throws next is null exception if list is empty protected test element get current element throws next is null exception if current sub controllers and samplers size return test element sub controllers and samplers get current if sub controllers and samplers size 0 set done true throw new next is null exception return null subcontrollersandsamplers subcontrollersandsamplers nextisnullexception nextisnullexception testelement getcurrentelement nextisnullexception subcontrollersandsamplers testelement subcontrollersandsamplers subcontrollersandsamplers setdone nextisnullexception protected void remove current element sub controllers and samplers remove current removecurrentelement subcontrollersandsamplers increments the current pointer called by current returned null to move the controller on to its next child protected void increment current current currentreturnednull incrementcurrent protected void reset current current 0 resetcurrent public void add test element test element child if child instanceof controller child instanceof sampler add element child addtestelement testelement addelement public void add iteration listener loop iteration listener lis a little hack add each listener to the start of the list this ensures that the thread running the show is the first listener and can modify certain values before other listeners are called iteration listeners add first lis additerationlistener loopiterationlistener iterationlisteners addfirst protected void fire iter events if is first fire iteration start first false todo should this use set first fireiterevents isfirst fireiterationstart setfirst protected void fire iteration start iterator iter iteration listeners iterator loop iteration event event new loop iteration event this get iter count while iter has next loop iteration listener item loop iteration listener iter next item iteration start event fireiterationstart iterationlisteners loopiterationevent loopiterationevent getitercount hasnext loopiterationlistener loopiterationlistener iterationstart protected int get iter count return iter count getitercount itercount protected void increment iter count iter count incrementitercount itercount protected void reset iter count iter count 0 resetitercount itercount creates an empty new hash tree public hash tree data new hash map hashtree hashtree hashmap allow subclasses to provide their own map protected hash tree map map data map hashtree _map _map creates a new hash tree and adds the given object as a top level node param key public hash tree object key data new hash map data put key new hash tree hashtree hashtree hashmap hashtree the map given must also be a hash tree otherwise an unsupported operation exception is thrown if it is a hash tree this is like calling the add hash tree method see add hash tree see java util map put all map public void put all map map if map instanceof hash tree this add hash tree map else throw new unsupported operation exception can only put all other hash tree objects hashtree unsupportedoperationexception hashtree hashtree hashtree putall putall hashtree hashtree unsupportedoperationexception putall hashtree exists to satisfy the map interface see java util map entry set public set entry set return data entry set entryset entryset entryset implemented as required by the map interface but is not very useful here all values in a hash tree are hash tree s themselves param value object to be tested as a value return true if the hash tree contains the value false otherwise see java util map contains value object public boolean contains value object value return data contains value value hashtree hashtree hashtree containsvalue containsvalue containsvalue this is the same as calling hash tree add key value param key to use param value to store against key see java util map put object object public object put object key object value object previous data get key add key value return previous hashtree clears the hash tree of all contents see java util map clear public void clear data clear hashtree returns a collection of all the sub trees of the current tree see java util map values public collection values return data values adds a key as a node at the current level and then adds the given hash tree to that new node param key key to create in this tree param sub tree sub tree to add to the node created for the first argument public void add object key hash tree sub tree add key get tree key add sub tree hashtree subtree hashtree subtree gettree subtree adds all the nodes and branches of the given tree to this tree is like merging two trees duplicates are ignored param new tree public void add hash tree new tree iterator iter new tree list iterator while iter has next object item iter next add item get tree item add new tree get tree item newtree hashtree newtree newtree hasnext gettree newtree gettree creates a new hash tree and adds all the objects in the given collection as top level nodes in the tree param keys a collection of objects to be added to the created hash tree public hash tree collection keys data new hash map iterator it keys iterator while it has next data put it next new hash tree hashtree hashtree hashtree hashmap hasnext hashtree creates a new hash tree and adds all the objects in the given array as top level nodes in the tree public hash tree object keys data new hash map for int x 0 x keys length x data put keys x new hash tree hashtree hashtree hashmap hashtree if the hash tree contains the given object as a key at the top level then a true result is returned otherwise false param o object to be tested as a key return true if the hash tree contains the key false otherwise see java util map contains key object public boolean contains key object o return data contains key o hashtree hashtree containskey containskey containskey if the hash tree is empty true is returned false otherwise return true if hash tree is empty false otherwise public boolean is empty return data is empty hashtree hashtree isempty isempty sets a key and it s value in the hash tree it actually sets up a key and then creates a node for the key and sets the value to the new node as a key any previous nodes that existed under the given key are lost param key key to be set up param value value to be set up as a key in the secondary node public void set object key object value data put key create new tree value hashtree createnewtree sets a key into the current tree and assigns it a hash tree as its subtree any previous entries under the given key are removed param key key to be set up param t hash tree that the key maps to public void set object key hash tree t data put key t hashtree hashtree hashtree sets a key and its values in the hash tree it sets up a key in the current node and then creates a node for that key and sets all the values in the array as keys in the new node any keys previously held under the given key are lost param key key to be set up param values array of objects to be added as keys in the secondary node public void set object key object values data put key create new tree arrays as list values hashtree createnewtree aslist sets a key and its values in the hash tree it sets up a key in the current node and then creates a node for that key and set all the values in the array as keys in the new node any keys previously held under the given key are removed param key key to be set up param values collection of objects to be added as keys in the secondary node public void set object key collection values data put key create new tree values hashtree createnewtree sets a series of keys into the hash tree it sets up the first object in the key array as a key in the current node recurses into the next hash tree node through that key and adds the second object in the array continues recursing in this manner until the end of the first array is reached at which point all the values of the second array are set as keys to the bottom most node all previous keys of that bottom most node are removed param tree path array of keys to put into hash tree param values array of values to be added as keys to bottom most node public void set object tree path object values if tree path null values null set arrays as list tree path arrays as list values hashtree hashtree treepath hashtree treepath treepath aslist treepath aslist sets a series of keys into the hash tree it sets up the first object in the key array as a key in the current node recurses into the next hash tree node through that key and adds the second object in the array continues recursing in this manner until the end of the first array is reached at which point all the values of the collection of values are set as keys to the bottom most node any keys previously held by the bottom most node are lost param tree path array of keys to put into hash tree param values collection of values to be added as keys to bottom most node public void set object tree path collection values if tree path null set arrays as list tree path values hashtree hashtree treepath hashtree treepath treepath aslist treepath sets a series of keys into the hash tree it sets up the first object in the key list as a key in the current node recurses into the next hash tree node through that key and adds the second object in the list continues recursing in this manner until the end of the first list is reached at which point all the values of the array of values are set as keys to the bottom most node any previously existing keys of that bottom node are removed param tree path collection of keys to put into hash tree param values array of values to be added as keys to bottom most node public void set collection tree path object values hash tree tree add tree path tree path tree set arrays as list values hashtree hashtree treepath hashtree treepath hashtree addtreepath treepath aslist sets the nodes of the current tree to be the objects of the given collection any nodes previously in the tree are removed param values collection of objects to set as nodes public void set collection values clear this add values sets a series of keys into the hash tree it sets up the first object in the key list as a key in the current node recurses into the next hash tree node through that key and adds the second object in the list continues recursing in this manner until the end of the first list is reached at which point all the values of the collection of values are set as keys to the bottom most node any previously existing keys of that bottom node are lost param tree path list of keys to put into hash tree param values collection of values to be added as keys to bottom most node public void set collection tree path collection values hash tree tree add tree path tree path tree set values hashtree hashtree treepath hashtree treepath hashtree addtreepath treepath adds an key into the hash tree at the current level param key key to be added to hash tree public hash tree add object key if data contains key key hash tree new tree create new tree data put key new tree return new tree return get tree key hashtree hashtree hashtree containskey hashtree newtree createnewtree newtree newtree gettree adds all the given objects as nodes at the current level param keys array of keys to be added to hash tree public void add object keys for int x 0 x keys length x add keys x hashtree adds a bunch of keys into the hash tree at the current level param keys collection of keys to be added to hash tree public void add collection keys iterator it keys iterator while it has next add it next hashtree hashtree hasnext adds a key and it s value in the hash tree the first argument becomes a node at the current level and the second argument becomes a node of it param key key to be added param value value to be added as a key in the secondary node public hash tree add object key object value add key return get tree key add value hashtree hashtree gettree adds a key and it s values in the hash tree the first argument becomes a node at the current level and adds all the values in the array to the new node param key key to be added param values array of objects to be added as keys in the secondary node public void add object key object values add key get tree key add values hashtree gettree adds a key as a node at the current level and then adds all the objects in the second argument as nodes of the new node param key key to be added param values collection of objects to be added as keys in the secondary node public void add object key collection values add key get tree key add values gettree adds a series of nodes into the hash tree using the given path the first argument is an array that represents a path to a specific node in the tree if the path doesn t already exist it is created the objects are added along the way at the path all the objects in the second argument are added as nodes param tree path an array of objects representing a path param values array of values to be added as keys to bottom most node public void add object tree path object values if tree path null add arrays as list tree path arrays as list values hashtree treepath treepath treepath aslist treepath aslist adds a series of nodes into the hash tree using the given path the first argument is an array that represents a path to a specific node in the tree if the path doesn t already exist it is created the objects are added along the way at the path all the objects in the second argument are added as nodes param tree path an array of objects representing a path param values collection of values to be added as keys to bottom most node public void add object tree path collection values if tree path null add arrays as list tree path values hashtree treepath treepath treepath aslist treepath public hash tree add object tree path object value return add arrays as list tree path value hashtree treepath aslist treepath adds a series of nodes into the hash tree using the given path the first argument is a list that represents a path to a specific node in the tree if the path doesn t already exist it is created the objects are added along the way at the path all the objects in the second argument are added as nodes param tree path a list of objects representing a path param values array of values to be added as keys to bottom most node public void add collection tree path object values hash tree tree add tree path tree path tree add arrays as list values hashtree treepath treepath hashtree addtreepath treepath aslist adds a series of nodes into the hash tree using the given path the first argument is a list that represents a path to a specific node in the tree if the path doesn t already exist it is created the objects are added along the way at the path the object in the second argument is added as a node param tree path a list of objects representing a path param value object to add as a node to bottom most node public hash tree add collection tree path object value hash tree tree add tree path tree path return tree add value hashtree treepath hashtree treepath hashtree addtreepath treepath adds a series of nodes into the hash tree using the given path the first argument is a sorted set that represents a path to a specific node in the tree if the path doesn t already exist it is created the objects are added along the way at the path all the objects in the second argument are added as nodes param tree path a sorted set of objects representing a path param values collection of values to be added as keys to bottom most node public void add collection tree path collection values hash tree tree add tree path tree path tree add values hashtree sortedset treepath sortedset treepath hashtree addtreepath treepath protected hash tree add tree path collection tree path hash tree tree this iterator iter tree path iterator while iter has next object temp iter next tree add temp tree tree get tree temp return tree hashtree addtreepath treepath hashtree treepath hasnext gettree gets the hash tree mapped to the given key param key key used to find appropriate hash tree public hash tree get tree object key return hash tree data get key hashtree hashtree hashtree gettree hashtree returns the hash tree object associated with the given key same as calling link get tree object see java util map get object public object get object key return get tree key hashtree gettree gettree gets the hash tree object mapped to the last key in the array by recursing through the hash tree structure one key at a time param tree path array of keys return hash tree at the end of the recursion public hash tree get tree object tree path if tree path null return get tree arrays as list tree path return this hashtree hashtree treepath hashtree hashtree gettree treepath treepath gettree aslist treepath create a clone of this hash tree this is not a deep clone ie the contents of the tree are not cloned public object clone hash tree new tree new hash tree clone tree new tree return new tree hashtree hashtree newtree hashtree clonetree newtree newtree protected void clone tree hash tree new tree iterator iter list iterator while iter has next object key iter next new tree set key hash tree get tree key clone clonetree hashtree newtree hasnext newtree hashtree gettree creates a new tree this method exists to allow inheriting classes to generate the appropriate types of nodes for instance when a node is added it s value is a hash tree rather than directly calling the hash tree constructor the create new tree method is called inheriting classes should override these methods and create the appropriate subclass of hash tree return hash tree protected hash tree create new tree return new hash tree hashtree hashtree createnewtree hashtree hashtree hashtree createnewtree hashtree creates a new tree this method exists to allow inheriting classes to generate the appropriate types of nodes for instance when a node is added it s value is a hash tree rather than directly calling the hash tree constructor the create new tree method is called inheriting classes should override these methods and create the appropriate subclass of hash tree return hash tree protected hash tree create new tree object key return new hash tree key hashtree hashtree createnewtree hashtree hashtree hashtree createnewtree hashtree creates a new tree this method exists to allow inheriting classes to generate the appropriate types of nodes for instance when a node is added it s value is a hash tree rather than directly calling the hash tree constructor the create new tree method is called inheriting classes should override these methods and create the appropriate subclass of hash tree return hash tree protected hash tree create new tree collection values return new hash tree values hashtree hashtree createnewtree hashtree hashtree hashtree createnewtree hashtree gets the hash tree object mapped to the last key in the sorted set by recursing through the hash tree structure one key at a time param tree path collection of keys return hash tree at the end of the recursion public hash tree get tree collection tree path return get tree path tree path hashtree sortedset hashtree treepath hashtree hashtree gettree treepath gettreepath treepath gets a collection of all keys in the current hash tree node if the hash tree represented a file system this would be like getting a collection of all the files in the current folder return set of all keys in this hash tree public collection list return data key set hashtree hashtree hashtree keyset gets a set of all keys in the hash tree mapped to the given key of the current hash tree object in other words one level down if the hash tree represented a file system this would like getting a list of all files in a sub directory of the current directory specified by the key argument param key key used to find hash tree to get list of return set of all keys in found hash tree public collection list object key hash tree temp hash tree data get key if temp null return temp list return new linked list hashtree hashtree hashtree hashtree hashtree hashtree hashtree linkedlist removes the entire branch specified by the given key see java util map remove object public object remove object key return data remove key recurses down into the hash tree stucture using each subsequent key in the array of keys and returns the set of keys of the hash tree object at the end of the recursion if the hash tree represented a file system this would be like getting a list of all the files in a directory specified by the tree path relative from the current directory param tree path array of keys used to recurse into hash tree structure return set of all keys found in end hash tree public collection list object tree path if tree path null return list arrays as list tree path return list hashtree hashtree hashtree treepath treepath hashtree hashtree treepath treepath aslist treepath recurses down into the hash tree stucture using each subsequent key in the list of keys and returns the set of keys of the hash tree object at the end of the recursion if the hash tree represented a file system this would be like getting a list of all the files in a directory specified by the tree path relative from the current directory param tree path list of keys used to recurse into hash tree structure return set of all keys found in end hash tree public collection list collection tree path hash tree tree get tree path tree path if tree null return tree list return new linked list hashtree hashtree hashtree treepath treepath hashtree hashtree treepath hashtree gettreepath treepath linkedlist finds the given current key and replaces it with the given new key any tree structure found under the original key is moved to the new key public void replace object current key object new key hash tree tree get tree current key data remove current key data put new key tree currentkey newkey hashtree gettree currentkey currentkey newkey gets an array of all keys in the current hash tree node if the hash tree represented a file system this would be like getting an array of all the files in the current folder return array of all keys in this hash tree public object get array return data key set to array hashtree hashtree hashtree getarray keyset toarray gets an array of all keys in the hash tree mapped to the given key of the current hash tree object in other words one level down if the hash tree represented a file system this would like getting a list of all files in a sub directory of the current directory specified by the key argument param key key used to find hash tree to get list of return array of all keys in found hash tree public object get array object key hash tree t get tree key if t null return t get array return null hashtree hashtree hashtree hashtree hashtree getarray hashtree gettree getarray recurses down into the hash tree stucture using each subsequent key in the array of keys and returns an array of keys of the hash tree object at the end of the recursion if the hash tree represented a file system this would be like getting a list of all the files in a directory specified by the tree path relative from the current directory param tree path array of keys used to recurse into hash tree structure return array of all keys found in end hash tree public object get array object tree path if tree path null return get array arrays as list tree path return get array hashtree hashtree hashtree treepath treepath hashtree hashtree getarray treepath treepath getarray aslist treepath getarray recurses down into the hash tree stucture using each subsequent key in the tree path argument and returns an array of keys of the hash tree object at the end of the recursion if the hash tree represented a file system this would be like getting a list of all the files in a directory specified by the tree path relative from the current directory param tree path list of keys used to recurse into hash tree structure return array of all keys found in end hash tree public object get array collection tree path hash tree tree get tree path tree path return tree null tree get array null hashtree treepath hashtree hashtree treepath treepath hashtree hashtree getarray treepath hashtree gettreepath treepath getarray protected hash tree get tree path collection tree path hash tree tree this iterator iter tree path iterator while iter has next if tree null return null object temp iter next tree tree get tree temp return tree hashtree gettreepath treepath hashtree treepath hasnext gettree returns a hashcode for this hash tree see java lang object hash code public int hash code return data hash code 7 hashtree hashcode hashcode hashcode compares all objects in the tree and verifies that the two trees contain the same objects at the same tree levels returns true if they do false otherwise param o object to be compared against see java lang object equals object public boolean equals object o if o instanceof hash tree return false hash tree oo hash tree o if oo size this size return false return data equals oo data boolean flag true if o instanceof hash tree hash tree oo hash tree o iterator it data key set iterator while it has next if oo contains key it next flag false break if flag it data key set iterator while it has next object temp it next flag get temp equals oo get temp if flag break else flag false return flag hashtree hashtree hashtree hashtree hashtree hashtree keyset hasnext containskey keyset hasnext returns a set of all the keys in the top level of this hash tree see java util map key set public set key set return data key set hashtree keyset keyset keyset searches the hash tree structure for the given key if it finds the key it returns the hash tree mapped to the key if it finds nothing it returns null param key key to search for return hash tree mapped to key if found otherwise code null code public hash tree search object key todo does not appear to be used hash tree result get tree key if result null return result tree searcher searcher new tree searcher key try traverse searcher catch runtime exception e if e get message equals found throw e do nothing means object is found return searcher get result hashtree hashtree hashtree hashtree hashtree gettree treesearcher treesearcher runtimeexception getmessage getresult method read object private void read object object input stream ois throws class not found exception io exception ois default read object readobject readobject objectinputstream classnotfoundexception ioexception defaultreadobject private void write object object output stream oos throws io exception oos default write object writeobject objectoutputstream ioexception defaultwriteobject returns the number of top level entries in the hash tree see java util map size public int size return data size hashtree allows any implementation of the hash tree traverser interface to easily traverse depth first all the nodes of the hash tree the traverser implementation will be given notification of each node visited see hash tree traverser public void traverse hash tree traverser visitor iterator iter list iterator while iter has next object item iter next visitor add node item get tree item get tree item traverse into visitor hashtreetraverser hashtree hashtreetraverser hashtreetraverser hasnext addnode gettree gettree traverseinto the recursive method that accomplishes the tree traversal and performs the callbacks to the hash tree traverser private void traverse into hash tree traverser visitor if list size 0 visitor process path else iterator iter list iterator while iter has next object item iter next final hash tree tree item get tree item visitor add node item tree item tree item traverse into visitor visitor subtract node hashtreetraverser traverseinto hashtreetraverser processpath hasnext hashtree treeitem gettree addnode treeitem treeitem traverseinto subtractnode generate a printable representation of the tree return a representation of the tree public string to string convert to string converter new convert to string try traverse converter catch exception e just in case converter report error e return converter to string tostring converttostring converttostring reporterror tostring private hash tree result public tree searcher object t target t hashtree treesearcher public hash tree get result return result hashtree getresult inherit doc public void add node object node hash tree sub tree result sub tree get tree target if result null short circuit traversal when found throw new runtime exception found inheritdoc addnode hashtree subtree subtree gettree runtimeexception inherit doc public void process path not used inheritdoc processpath inherit doc public void subtract node not used inheritdoc subtractnode public void add node object key hash tree sub tree depth string append n append get spaces append key string append addnode hashtree subtree getspaces public void subtract node string append n get spaces depth subtractnode getspaces public void process path processpath public string to string string append n return string to string tostring tostring void report error throwable t string append error append t to string reporterror tostring private string get spaces if spaces length depth 2 while spaces length depth 2 spaces append else if spaces length depth 2 spaces set length depth 2 return spaces to string getspaces setlength tostring create a new daemon with the specified port and target param port the port to listen on public http mirror server int port super http mirror server this daemon port port httpmirrorserver httpmirrorserver daemonport listen on the daemon port and handle incoming requests this method will not exit until link stop server is called or an error occurs public void run except null running true server socket main socket null try log info creating http mirror on port daemon port main socket new server socket daemon port main socket set so timeout accept timeout log info http mirror up and running while running try listen on main socket socket client socket main socket accept if running pass request to new thread http mirror thread thd new http mirror thread client socket log info starting new mirror thread thd start else log warn server not running j orphan utils close quietly client socket catch interruptedio exception e timeout occurred ignore and keep looping until we re told to stop running log info http mirror server stopped catch exception e except e log warn http mirror server stopped e finally j orphan utils close quietly main socket stopserver serversocket mainsocket httpmirror daemonport mainsocket serversocket daemonport mainsocket setsotimeout accept_timeout httpmirror clientsocket mainsocket httpmirrorthread httpmirrorthread clientsocket jorphanutils closequietly clientsocket interruptedioexception httpmirror httpmirror jorphanutils closequietly mainsocket public void stop server running false stopserver public exception get exception return except getexception public static void main string args int port 8080 if args length 0 port integer parse int args 0 http mirror server serv new http mirror server port serv start parseint httpmirrorserver httpmirrorserver constructor for the once only controller object public once only controller onceonlycontroller onceonlycontroller see loop iteration listener iteration start loop iteration event public void iteration start loop iteration event event int num iteration 1 bug 39509 iteration to 0 for all controller which not loop controller and tg if event get source instanceof loop controller num iteration 0 if event get iteration num iteration re initialize loopiterationlistener iterationstart loopiterationevent iterationstart loopiterationevent numiteration loopcontroller getsource loopcontroller numiteration getiteration numiteration reinitialize protected sampler next is null throws next is null exception return null nextisnull nextisnullexception constructor for the close object public collapse expand collapseexpand gets the action names attribute of the close object return the action names value public set get action names return commands actionnames actionnames getactionnames this method performs the actual command processing param e the generic ui action event public void do action action event e boolean collapse action names collapse all equals e get action command gui package gui instance gui package get instance j tree j tree gui instance get main frame get tree if collapse for int i j tree get row count 1 i 0 i j tree collapse row i return for int i 0 i j tree get row count i j tree expand row i doaction actionevent actionnames collapse_all getactioncommand guipackage guiinstance guipackage getinstance jtree jtree guiinstance getmainframe gettree jtree getrowcount jtree collapserow jtree getrowcount jtree expandrow get the scope setting return the scope default parent public string fetch scope return get property as string scope scope parent fetchscope getpropertyasstring scope_parent is the assertion to be applied to the main parent sample param scope return if the assertion is to be applied to the parent sample public boolean is scope parent string scope return scope equals scope parent isscopeparent scope_parent is the assertion to be applied to the sub samples children param scope return if the assertion is to be applied to the children public boolean is scope children string scope return scope equals scope children isscopechildren scope_children is the assertion to be applied to the all samples param scope return if the assertion is to be applied to the all samples public boolean is scope all string scope return scope equals scope all isscopeall scope_all public void set scope parent remove property scope setscopeparent removeproperty public void set scope children set property scope scope children setscopechildren setproperty scope_children public void set scope all set property scope scope all setscopeall setproperty scope_all todo does not appear to be used public static string encode string s return util substitute expression s prevent instantiation of utility class private argument encoder argumentencoder private j meter context jmctx public xml schema assertion test string arg0 super arg0 jmetercontext xmlschemaassertiontest protected void set up throws exception super set up jmctx j meter context service get context assertion new xml schema assertion assertion set thread context jmctx this would be done by the run command result new sample result vars new j meter variables jmctx set variables vars jmctx set previous result result logging manager set priority debug jmeter setup setup jmetercontextservice getcontext xmlschemaassertion setthreadcontext sampleresult jmetervariables setvariables setpreviousresult loggingmanager setpriority protected void tear down throws exception super tear down teardown teardown private byte array output stream readba string name throws io exception buffered input stream bis new buffered input stream new file input stream find test file name byte array output stream baos new byte array output stream 1000 int len 0 byte data new byte 512 while len bis read data 0 baos write data 0 len bis close return baos bytearrayoutputstream ioexception bufferedinputstream bufferedinputstream fileinputstream findtestfile bytearrayoutputstream bytearrayoutputstream private byte read file string name throws io exception return readba name to byte array readfile ioexception tobytearray public void test assertionok throws exception result set response data read file testfiles xml schematest xml assertion set xsd file name testfiles xml schema pass xsd assertion result res assertion get result jmctx get previous result test log debug is error res is error is failure res is failure test log debug failure res get failure message assert false should not be an error res is error assert false should not be a failure res is failure testassertionok setresponsedata readfile xmlschematest setxsdfilename xmlschema assertionresult getresult getpreviousresult testlog iserror iserror isfailure isfailure testlog getfailuremessage assertfalse iserror assertfalse isfailure public void test assertion fail throws exception result set response data read file testfiles xml schematest xml assertion set xsd file name testfiles xml schema fail xsd assertion result res assertion get result jmctx get previous result test log debug is error res is error is failure res is failure test log debug failure res get failure message assert true res is error assert false res is failure testassertionfail setresponsedata readfile xmlschematest setxsdfilename xmlschema assertionresult getresult getpreviousresult testlog iserror iserror isfailure isfailure testlog getfailuremessage asserttrue iserror assertfalse isfailure public void test assertion badxsd file throws exception result set response data read file testfiles xml schematest xml assertion set xsd file name xtestfiles xml schema fail xsd assertion result res assertion get result jmctx get previous result test log debug is error res is error is failure res is failure test log debug failure res get failure message assert true res get failure message index of failed to read schema document 0 assert true res is error todo should this be a failure assert false res is failure testassertionbadxsdfile setresponsedata readfile xmlschematest setxsdfilename xmlschema assertionresult getresult getpreviousresult testlog iserror iserror isfailure isfailure testlog getfailuremessage asserttrue getfailuremessage indexof asserttrue iserror assertfalse isfailure public void test assertion no file throws exception result set response data read file testfiles xml schematest xml assertion set xsd file name assertion result res assertion get result jmctx get previous result test log debug is error res is error is failure res is failure test log debug failure res get failure message assert equals xml schema assertion file name is required res get failure message assert false res is error assert true res is failure testassertionnofile setresponsedata readfile xmlschematest setxsdfilename assertionresult getresult getpreviousresult testlog iserror iserror isfailure isfailure testlog getfailuremessage assertequals xmlschemaassertion file_name_is_required getfailuremessage assertfalse iserror asserttrue isfailure public void test assertion no result throws exception result set response data not set assertion set xsd file name testfiles xml schema fail xsd assertion result res assertion get result jmctx get previous result test log debug is error res is error is failure res is failure test log debug failure res get failure message assert equals assertion result response was null res get failure message assert false res is error assert true res is failure testassertionnoresult setresponsedata setxsdfilename xmlschema assertionresult getresult getpreviousresult testlog iserror iserror isfailure isfailure testlog getfailuremessage assertequals assertionresult response_was_null getfailuremessage assertfalse iserror asserttrue isfailure public void test assertion empty result throws exception result set response data get bytes assertion set xsd file name testfiles xml schema fail xsd assertion result res assertion get result jmctx get previous result test log debug is error res is error is failure res is failure test log debug failure res get failure message assert equals assertion result response was null res get failure message assert false res is error assert true res is failure testassertionemptyresult setresponsedata getbytes setxsdfilename xmlschema assertionresult getresult getpreviousresult testlog iserror iserror isfailure isfailure testlog getfailuremessage assertequals assertionresult response_was_null getfailuremessage assertfalse iserror asserttrue isfailure public void test assertion blank result throws exception result set response data get bytes assertion set xsd file name testfiles xml schema fail xsd assertion result res assertion get result jmctx get previous result test log debug is error res is error is failure res is failure test log debug failure res get failure message assert true res get failure message index of premature end of file 0 assert true res is error assert false res is failure testassertionblankresult setresponsedata getbytes setxsdfilename xmlschema assertionresult getresult getpreviousresult testlog iserror iserror isfailure isfailure testlog getfailuremessage asserttrue getfailuremessage indexof asserttrue iserror assertfalse isfailure public void testxml trailingcontent throws exception byte array output stream baos readba testfiles xml schematest xml baos write extra get bytes result set response data baos to byte array assertion set xsd file name testfiles xml schema pass xsd assertion result res assertion get result jmctx get previous result test log debug is error res is error is failure res is failure test log debug failure res get failure message assert true res get failure message index of content is not allowed in trailing section 0 assert true res is error assert false res is failure testxmltrailingcontent bytearrayoutputstream xmlschematest getbytes setresponsedata tobytearray setxsdfilename xmlschema assertionresult getresult getpreviousresult testlog iserror iserror isfailure isfailure testlog getfailuremessage asserttrue getfailuremessage indexof asserttrue iserror assertfalse isfailure public void testxml trailingwhitespace throws exception byte array output stream baos readba testfiles xml schematest xml baos write t n get bytes result set response data baos to byte array assertion set xsd file name testfiles xml schema pass xsd assertion result res assertion get result jmctx get previous result test log debug xis error res is error is failure res is failure test log debug failure res get failure message assert false res is error assert false res is failure testxmltrailingwhitespace bytearrayoutputstream xmlschematest getbytes setresponsedata tobytearray setxsdfilename xmlschema assertionresult getresult getpreviousresult testlog xiserror iserror isfailure isfailure testlog getfailuremessage assertfalse iserror assertfalse isfailure public class bean shell post processor bean info extends bean shell bean info support public bean shell post processor bean info super bean shell post processor class beanshellpostprocessorbeaninfo beanshellbeaninfosupport beanshellpostprocessorbeaninfo beanshellpostprocessor public server panel monitor model model super data model init model serverpanel monitormodel deprecated only for use in unit testing public server panel log warn only for use in unit testing serverpanel init will create the j label widgets for the host health load and timestamp param model private void init monitor model model this set layout new flow layout server field new j label model geturl this add server field health icon new j label get healthy image icon model get health health icon set preferred size prefsize this add health icon load icon new j label get load image icon model get load this add load icon timestamp field new j label model get timestamp string this add timestamp field jlabel monitormodel setlayout flowlayout serverfield jlabel serverfield healthicon jlabel gethealthyimageicon gethealth healthicon setpreferredsize healthicon loadicon jlabel getloadimageicon getload loadicon timestampfield jlabel gettimestampstring timestampfield static method for getting the right image icon for the health param health return image for the status private static image icon get healthy image icon int health image icon i null switch health case stats healthy i healthy break case stats active i active break case stats warning i warning break case stats dead i dead break return i imageicon imageicon gethealthyimageicon imageicon static method looks up the right image icon from the load value param load return image for the load private static image icon get load image icon int load if load 0 return load 0 else if load 0 load 10 return load 1 else if load 10 load 20 return load 2 else if load 20 load 30 return load 3 else if load 30 load 40 return load 4 else if load 40 load 50 return load 5 else if load 50 load 60 return load 6 else if load 60 load 70 return load 7 else if load 70 load 80 return load 8 else if load 80 load 90 return load 9 else return load 10 imageicon imageicon getloadimageicon load_0 load_1 load_2 load_3 load_4 load_5 load_6 load_7 load_8 load_9 load_10 method will update the server panel s health load and timestamp for efficiency it uses the static method to lookup the images public void update gui monitor model stat this data null this data stat load icon set icon get load image icon stat get load health icon set icon get healthy image icon stat get health timestamp field set text stat get timestamp string this update gui serverpanel updategui monitormodel loadicon seticon getloadimageicon getload healthicon seticon gethealthyimageicon gethealth timestampfield settext gettimestampstring updategui update the gui public void update gui this repaint updategui public void process j meter context ctx get thread context sampler sampler ctx get current sampler if sampler instanceof http sampler base ignore non http samplers return sample result response text ctx get previous result if response text null return init regex get argument name string text new string response text get response data perl5 matcher matcher j meter utils get matcher string value if is path extension is path extension no equals is path extension no questionmark if matcher contains text path extension no equals no questionmark regexp match result result matcher get match value result group 1 else if is path extension is path extension no equals is path extension no questionmark if matcher contains text path extension no equals questionmark regexp match result result matcher get match value result group 1 else if is path extension is path extension no questionmark is path extension no equals if matcher contains text path extension equals no questionmark regexp match result result matcher get match value result group 1 else if is path extension is path extension no equals is path extension no questionmark if matcher contains text path extension equals questionmark regexp match result result matcher get match value result group 1 else if is path extension if matcher contains text parameter regexp match result result matcher get match for int i 1 i result groups i value result group i if value null break bug 15025 save session value across samplers if should cache if value null value length 0 value saved value else saved value value modify http sampler base sampler value jmetercontext getthreadcontext getcurrentsampler httpsamplerbase sampleresult responsetext getpreviousresult responsetext initregex getargumentname responsetext getresponsedata perl5matcher jmeterutils getmatcher ispathextension ispathextensionnoequals ispathextensionnoquestionmark pathextensionnoequalsnoquestionmarkregexp matchresult getmatch ispathextension ispathextensionnoequals ispathextensionnoquestionmark pathextensionnoequalsquestionmarkregexp matchresult getmatch ispathextension ispathextensionnoquestionmark ispathextensionnoequals pathextensionequalsnoquestionmarkregexp matchresult getmatch ispathextension ispathextensionnoequals ispathextensionnoquestionmark pathextensionequalsquestionmarkregexp matchresult getmatch ispathextension parameterregexp matchresult getmatch shouldcache savedvalue savedvalue httpsamplerbase private void modify http sampler base sampler string value if is path extension if is path extension no equals sampler set path sampler get path semi colon get argument name value non nls 1 else sampler set path sampler get path semi colon get argument name value non nls 1 non nls 2 else sampler get arguments remove argument get argument name sampler get arguments add argument new http argument get argument name value true httpsamplerbase ispathextension ispathextensionnoequals setpath getpath semi_colon getargumentname setpath getpath semi_colon getargumentname getarguments removeargument getargumentname getarguments addargument httpargument getargumentname public void set argument name string arg name set property argument name arg name setargumentname argname setproperty argument_name argname private void init regex string arg name string quoted arg perl5 compiler quotemeta arg name don t get tripped up by re chars in the arg name path extension equals questionmark regexp j meter utils get pattern cache get pattern semi colon quoted arg s s non nls 1 perl5 compiler multiline mask perl5 compiler read only mask path extension equals no questionmark regexp j meter utils get pattern cache get pattern semi colon quoted arg s s non nls 1 perl5 compiler multiline mask perl5 compiler read only mask path extension no equals questionmark regexp j meter utils get pattern cache get pattern semi colon quoted arg s s non nls 1 perl5 compiler multiline mask perl5 compiler read only mask path extension no equals no questionmark regexp j meter utils get pattern cache get pattern semi colon quoted arg s s non nls 1 perl5 compiler multiline mask perl5 compiler read only mask parameter regexp j meter utils get pattern cache get pattern sessionid value quoted arg s s non nls 1 name sessionid value value s nn aa mm ee s s quoted arg non nls 1 s vv aa ll uu ee s s non nls 1 non nls 1 value value name sessionid s vv aa ll uu ee s s non nls 1 non nls 1 non nls 2 non nls 3 s nn aa mm ee s s non nls 1 quoted arg non nls 1 perl5 compiler multiline mask perl5 compiler read only mask note the handling of simple vs double quotes could be formally more accurate but i can t imagine a session id containing either so we should be ok the whole set of expressions is a quick hack anyway so who cares initregex argname quotedarg perl5compiler argname pathextensionequalsquestionmarkregexp jmeterutils getpatterncache getpattern semi_colon quotedarg perl5compiler multiline_mask perl5compiler read_only_mask pathextensionequalsnoquestionmarkregexp jmeterutils getpatterncache getpattern semi_colon quotedarg perl5compiler multiline_mask perl5compiler read_only_mask pathextensionnoequalsquestionmarkregexp jmeterutils getpatterncache getpattern semi_colon quotedarg perl5compiler multiline_mask perl5compiler read_only_mask pathextensionnoequalsnoquestionmarkregexp jmeterutils getpatterncache getpattern semi_colon quotedarg perl5compiler multiline_mask perl5compiler read_only_mask parameterregexp jmeterutils getpatterncache getpattern quotedarg quotedarg quotedarg perl5compiler multiline_mask perl5compiler read_only_mask public string get argument name return get property as string argument name getargumentname getpropertyasstring argument_name public void set path extension boolean path ext set property new boolean property path extension path ext setpathextension pathext setproperty booleanproperty path_extension pathext public void set path extension no equals boolean path ext no equals set property new boolean property path extension no equals path ext no equals setpathextensionnoequals pathextnoequals setproperty booleanproperty path_extension_no_equals pathextnoequals public void set path extension no questionmark boolean path ext no questionmark set property new boolean property path extension no questionmark path ext no questionmark setpathextensionnoquestionmark pathextnoquestionmark setproperty booleanproperty path_extension_no_questionmark pathextnoquestionmark public void set should cache boolean b set property new boolean property should cache b setshouldcache setproperty booleanproperty should_cache public boolean is path extension return get property as boolean path extension ispathextension getpropertyasboolean path_extension public boolean is path extension no equals return get property as boolean path extension no equals ispathextensionnoequals getpropertyasboolean path_extension_no_equals public boolean is path extension no questionmark return get property as boolean path extension no questionmark ispathextensionnoquestionmark getpropertyasboolean path_extension_no_questionmark public boolean should cache return get property as boolean should cache true shouldcache getpropertyasboolean should_cache protected html parserhtml parser super log info using htmlparser version parser get version htmlparserhtmlparser getversion protected boolean is reusable return true isreusable public iterator get embedded resourceur ls byte html url base url url collection urls throws html parse exception if log is debug enabled log debug parsing html of base url parser html parser null try string contents new string html html parser new parser html parser set inputhtml contents catch exception e throw new html parse exception e now parse the dom tree try we start to iterate through the elements parse nodes html parser elements new url pointer base url urls log debug end parse nodes catch parser exception e throw new html parse exception e return urls iterator getembeddedresourceurls baseurl urlcollection htmlparseexception isdebugenabled baseurl htmlparser htmlparser htmlparser setinputhtml htmlparseexception parsenodes htmlparser urlpointer baseurl parsenodes parserexception htmlparseexception private static class url pointer private url pointer url new url url new url urlpointer urlpointer newurl newurl recursively parse all nodes to pick up all url s see e the nodes to be parsed see base url base url from which the html code was obtained see urls url collection private void parse nodes final node iterator e final url pointer base url final url collection urls throws html parse exception parser exception while e has more nodes node node e next node a url is always in a tag if node instanceof tag continue tag tag tag node string tagname tag get tag name string bin url str null first we check to see if body tag has a background set if tag instanceof body tag bin url str tag get attribute att background else if tag instanceof base href tag base href tag base href base href tag tag string baseref base href get base url try if baseref equals bugzilla 30713 base url url conversion utils make relativeurl base url url base href get base url catch malformedurl exception e1 throw new html parse exception e1 else if tag instanceof image tag image tag image image tag tag bin url str image get imageurl else if tag instanceof applet tag look for applets this will only work with an applet class file ideally this should be upgraded to work with objects ie and archives jar and zip files as well applet tag applet applet tag tag bin url str applet get applet class else if tag instanceof input tag we check the input tag type for image if att is image equals ignore case tag get attribute att type then we need to download the binary bin url str tag get attribute att src else if tag instanceof link tag link tag link link tag tag if link get child 0 instanceof image tag image tag img image tag link get child 0 bin url str img get imageurl else if tag instanceof script tag bin url str tag get attribute att src else if tag instanceof frame tag bin url str tag get attribute att src else if tagname equals ignore case tag embed tagname equals ignore case tag bgsound bin url str tag get attribute att src else if tagname equals ignore case tag link putting the string first means it works even if the attribute is null if stylesheet equals ignore case tag get attribute att rel bin url str tag get attribute att href else bin url str tag get attribute att background if bin url str null urls addurl bin url str base url url now look for ur ls in the style attribute string style tag str tag get attribute att style if style tag str null html parsing utils extract styleur ls base url url urls style tag str second if the tag was a composite tag recursively parse its children if tag instanceof composite tag composite tag composite composite tag tag parse nodes composite elements base url urls baseurl urlcollection parsenodes nodeiterator urlpointer baseurl urlcollection htmlparseexception parserexception hasmorenodes nextnode gettagname binurlstr bodytag binurlstr getattribute att_background basehreftag basehreftag basehref basehreftag basehref getbaseurl baseurl conversionutils makerelativeurl baseurl basehref getbaseurl malformedurlexception htmlparseexception imagetag imagetag imagetag binurlstr getimageurl applettag applettag applettag binurlstr getappletclass inputtag att_is_image equalsignorecase getattribute att_type binurlstr getattribute att_src linktag linktag linktag getchild imagetag imagetag imagetag getchild binurlstr getimageurl scripttag binurlstr getattribute att_src frametag binurlstr getattribute att_src equalsignorecase tag_embed equalsignorecase tag_bgsound binurlstr getattribute att_src equalsignorecase tag_link equalsignorecase getattribute att_rel binurlstr getattribute att_href binurlstr getattribute att_background binurlstr binurlstr baseurl urls styletagstr getattribute att_style styletagstr htmlparsingutils extractstyleurls baseurl styletagstr compositetag compositetag compositetag parsenodes baseurl j meter utils get prop default server rmi create true non nls 1 private remotej meter engine impl int port throws remote exception super port create this object using the specified port 0 means anonymous system out println created remote object this get ref remote to string jmeterutils getpropdefault remotejmeterengineimpl remoteexception getref remotetostring public static void start server int port throws remote exception remotej meter engine impl engine new remotej meter engine impl default local port engine init port 0 default rmi port port startserver remoteexception remotejmeterengineimpl remotejmeterengineimpl default_local_port default_rmi_port private void init int port throws remote exception log info starting backing engine on port inet address local host null try local host inet address get local host catch unknown host exception e1 throw new remote exception cannot start unable to get local host ip address log info ip address local host get host address string host name local host get host name if local host is loopback address throw new remote exception cannot start host name is a loopback address log debug this this if create server log info creating rmi registry server rmi create true try locate registry create registry port catch remote exception e string msg problem creating registry e log warn msg system err println msg system err println continuing try registry reg locate registry get registry port reg rebind jmeter engine rmi name this log info bound to registry on port port catch exception ex log error rmiregistry needs to be running to start j meter in server mode n t ex to string throw an exception to ensure caller knows throw new remote exception cannot start see server log file remoteexception inetaddress localhost localhost inetaddress getlocalhost unknownhostexception remoteexception localhost gethostaddress hostname localhost gethostname localhost isloopbackaddress remoteexception hostname createserver locateregistry createregistry remoteexception locateregistry getregistry jmeter_engine_rmi_name jmeter tostring remoteexception adds a feature to the thread group attribute of the remotej meter engine impl object param test tree the feature to be added to the thread group attribute public void configure hash tree test tree string host throws remote exception log info creating j meter engine on host host backing engine new standardj meter engine host backing engine configure test tree threadgroup remotejmeterengineimpl testtree threadgroup hashtree testtree remoteexception jmeter backingengine standardjmeterengine backingengine testtree public void run test throws remote exception j meter engine exception log info running test backing engine run test runtest remoteexception jmeterengineexception backingengine runtest public void reset throws remote exception log info reset backing engine reset remoteexception backingengine public void stop test throws remote exception log info stopping test backing engine stop test todo ask threads to stop instead stoptest remoteexception backingengine stoptest askthreadstostop public void exit throws remote exception log info exitting backing engine exit remoteexception backingengine public void set properties properties p throws remote exception backing engine set properties p setproperties remoteexception backingengine setproperties private j text area text area public assertion visualizer init set name get static label jtextarea textarea assertionvisualizer setname getstaticlabel public string get label resource return assertion visualizer title non nls 1 getlabelresource assertion_visualizer_title public void add sample result sample string buffer sb new string buffer 100 sb append sample get sample label sb append get assertion result sample sb append n non nls 1 synchronized text area text area append sb to string sampleresult stringbuffer stringbuffer getsamplelabel getassertionresult textarea textarea tostring public void clear data text area set text non nls 1 cleardata textarea settext private string get assertion result sample result res if res null string buffer display new string buffer assertion result assertion results res get assertion results for int i 0 i assertion results length i assertion result item assertion results i if item is failure item is error display append n t non nls 1 display append item get name null item get name non nls 1 display append item get failure message return display to string return getassertionresult sampleresult stringbuffer stringbuffer assertionresult assertionresults getassertionresults assertionresults assertionresult assertionresults isfailure iserror getname getname getfailuremessage tostring private void init this set layout new border layout main panel border margin new empty border 10 10 5 10 this set border margin name this add make title panel border layout north textarea label j label text area label new j label j meter utils get res string assertion textarea label non nls 1 box main panel box create vertical box main panel add text area label textarea text area new j text area text area set editable false text area set line wrap false j scroll pane area scroll pane new j scroll pane text area area scroll pane set vertical scroll bar policy j scroll pane vertical scrollbar always area scroll pane set horizontal scroll bar policy j scroll pane horizontal scrollbar as needed area scroll pane set preferred size new dimension main panel get width main panel get height main panel add area scroll pane this add main panel border layout center setlayout borderlayout emptyborder setborder maketitlepanel borderlayout jlabel textarealabel jlabel jmeterutils getresstring assertion_textarea_label mainpanel createverticalbox mainpanel textarealabel textarea jtextarea textarea seteditable textarea setlinewrap jscrollpane areascrollpane jscrollpane textarea areascrollpane setverticalscrollbarpolicy jscrollpane vertical_scrollbar_always areascrollpane sethorizontalscrollbarpolicy jscrollpane horizontal_scrollbar_as_needed areascrollpane setpreferredsize mainpanel getwidth mainpanel getheight mainpanel areascrollpane mainpanel borderlayout creates a new spline curve by calculating the coefficients of each part of the curve i e by resolving the equation system implied by the interpolation condition on every interval param r an array of float containing the vertical coordinates of the nodes to interpolate the vertical coordinates start at 0 and are equidistant with a step of 1 public spline3 float r int n r length the number of nodes is defined by the length of r this m n grab the nodes this r new float n for int i 0 i n i r i r i the number of non extreme nodes is the number of intervals minus 1 i e the length of r minus 2 this n n 2 computes interpolation coefficients try long start time system current time millis this interpolation if log is debug enabled long end time system current time millis long elapsed time end time start time log debug new spline curve interpolated in log debug elapsed time ms catch exception e log error error when interpolating e _m _r _r _n starttime currenttimemillis isdebugenabled endtime currenttimemillis elapsedtime endtime starttime elapsedtime computes the coefficients of the spline interpolated curve on each interval the matrix system to resolve is code ax b code protected void interpolation creation of the interpolation structure rs new float m b new float n a new float n n coefficients new float n 1 4 local variables int i 0 j 0 initialize system structures just to be safe for i 0 i n i b i 0 for j 0 j n j a i j 0 for j 0 j 4 j coefficients i j 0 for i 0 i n i rs i 0 initialize the diagonal of the system matrix a to 4 for i 0 i n i a i i 4 initialize the two minor diagonals of a to 1 for i 1 i n i a i i 1 1 a i 1 i 1 initialize b for i 0 i n i b i 6 r i 2 2 r i 1 r i jacobi system resolving this jacobi results are stored in rs computes the coefficients di ci bi ai from the results for i 0 i n 1 i di degree 0 coefficients i 0 r i ci degree 1 coefficients i 1 r i 1 r i rs i 1 2 rs i 6 bi degree 2 coefficients i 2 rs i 2 ai degree 3 coefficients i 3 rs i 1 rs i 6 _rs _m _b _n _a _n _n _coefficients _n _n _b _n _a _coefficients _n _rs _n _a _n _a _a _n _b _r _r _r _rs _n _coefficients _r _coefficients _r _r _rs _rs _coefficients _rs _coefficients _rs _rs resolves the equation system by a jacobi algorithm the use of the slower jacobi algorithm instead of gauss seidel is choosen here because jacobi is assured of to be convergent for this particular equation system as the system matrix has a strong diagonal protected void jacobi local variables int i 0 j 0 iterations 0 intermediate arrays float newx new float n float oldx new float n jacobi convergence test if converge if log is debug enabled log debug warning equation system resolving is unstable init newx and oldx arrays to 0 for i 0 i n i newx i 0 oldx i 0 main iteration while this precision oldx newx this minprecision iterations this maxiterations for i 0 i n i oldx i newx i for i 0 i n i newx i b i for j 0 j i j newx i newx i a i j oldx j for j i 1 j n j newx i newx i a i j oldx j newx i newx i a i i iterations if this precision oldx newx this minprecision if log is debug enabled log debug minimal precision log debug this minprecision reached after log debug iterations iterations else if iterations this maxiterations if log is debug enabled log debug maximal number of iterations log debug this maxiterations reached log debug warning precision is only log debug this precision oldx newx log debug divergence is possible for i 0 i n i rs i 1 newx i _n _n isdebugenabled _n _minprecision _maxiterations _n _n _b _a _n _a _a _minprecision isdebugenabled _minprecision _maxiterations isdebugenabled _maxiterations _n _rs test if the jacobi resolution of the equation system converges it s ok if a has a strong diagonal protected boolean converge boolean converge true int i 0 j 0 float line sum 0f for i 0 i n i if converge line sum 0 for j 0 j n j line sum line sum math abs a i j line sum line sum math abs a i i if line sum math abs a i i converge false return converge linesum _n linesum _n linesum linesum _a linesum linesum _a linesum _a computes the current precision reached protected float precision float oldx float newx float n 0f d 0f erreur 0f int i 0 for i 0 i n i n n math abs newx i oldx i d d math abs newx i if d 0f erreur n d else erreur float max value return erreur _n max_value computes a vertical y axis value of the global curve param t abscissa return computed ordinate public float value float t int i 0 spline number 0 float abscissa 0f result 0f verify t belongs to the curve range 0 m 1 if t 0 t m 1 if log is debug enabled log debug warning abscissa t out of bounds 0 m 1 silent error consider the curve is constant outside its range if t 0 t 0 else t m 1 seek the good interval for t and get the piece of curve on it spline number int math floor t if t m 1 the upper limit of the curve range belongs by definition to the last interval spline number computes the value of the curve at the pecified abscissa and relative to the beginning of the right piece of spline curve abscissa t spline number the polynomial calculation is done by the fast euler method for i 0 i 4 i result result abscissa result result coefficients spline number 3 i return result splinenumber _m _m isdebugenabled _m _m splinenumber _m splinenumber splinenumber _coefficients splinenumber manual check of the curve at the interpolated points public void debug check int i 0 for i 0 i m i log info point i log info r i value i debugcheck _m _r computes drawable plots from the curve for a given draw space the values returned are drawable vertically and from the b bottom b of a panel param width width within the plots have to be computed param height height within the plots are expected to be drawed return drawable plots within the limits defined in an array of int as many int as the value of the code width code parameter public int get plots int width int height int plot new int width computes auto scaling and absolute plots float y new float width float max java lang integer min value float min java lang integer max value for int i 0 i width i y i value float i m 1 width if y i min min y i if y i max max y i if min 0 min 0 shouldn t draw negative values computes relative auto scaled plots to fit in the specified area for int i 0 i width i plot i math round y i min height 1 max min return plot getplots min_value max_value _m public void set precision float precision this minprecision precision setprecision _minprecision public float get precision return this minprecision getprecision _minprecision public void set to default precision this minprecision default precision settodefaultprecision _minprecision default_precision public float get default precision return default precision getdefaultprecision default_precision public void set max iterations int iterations this maxiterations iterations setmaxiterations _maxiterations public int get max iterations return this maxiterations getmaxiterations _maxiterations public void set to default max iterations this maxiterations default max iterations settodefaultmaxiterations _maxiterations default_max_iterations public int get default max iterations return default max iterations getdefaultmaxiterations default_max_iterations constructor for the start object public report start reportstart gets the action names attribute of the start object return the action names value public set get action names return commands actionnames actionnames getactionnames public void do action action event e if e get action command equals action names action start popup should save e start engine else if e get action command equals action names action stop if engine null report gui package get instance get main frame show stopping message engine stop test engine null else if e get action command equals action names action shutdown if engine null report gui package get instance get main frame show stopping message engine ask threads to stop engine null doaction actionevent getactioncommand actionnames action_start popupshouldsave startengine getactioncommand actionnames action_stop reportguipackage getinstance getmainframe showstoppingmessage stoptest getactioncommand actionnames action_shutdown reportguipackage getinstance getmainframe showstoppingmessage askthreadstostop protected void start engine this will need to be changed report gui package gui report gui package get instance engine new standardj meter engine hash tree test tree gui get tree model get test plan convert sub tree test tree disabled component remover remover new disabled component remover test tree test tree traverse remover test tree add test tree get array 0 gui get main frame log debug test plan before cloning is running version test plan test tree get array 0 is running version tree cloner cloner new tree cloner false test tree traverse cloner engine configure cloner get cloned tree try engine run test catch j meter engine exception e j option pane show message dialog gui get main frame e get message j meter utils get res string error occurred j option pane error message log debug test plan after cloning and running test is running version test plan test tree get array 0 is running version startengine reportguipackage reportguipackage getinstance standardjmeterengine hashtree testtree gettreemodel gettestplan convertsubtree testtree disabledcomponentremover disabledcomponentremover testtree testtree testtree testtree getarray getmainframe testplan testtree getarray isrunningversion treecloner treecloner testtree getclonedtree runtest jmeterengineexception joptionpane showmessagedialog getmainframe getmessage jmeterutils getresstring joptionpane error_message testplan testtree getarray isrunningversion compile a general string into a list of elements for a compound variable calls link make function string reader if it detects an unescaped removes escapes from and param value string containing the function variable references if any return list of strings or objects representing functions linked list compile string string value throws invalid variable exception string reader reader new string reader value linked list result new linked list string buffer buffer new string buffer char previous todo why use space char current new char 1 try while reader read current 1 if current 0 handle escapes previous current 0 if reader read current 0 break keep the unless it is one of the escapable chars or n b this method is used to parse function parameters so must treat as special if current 0 current 0 current 0 buffer append previous i e previous buffer append current 0 continue else if current 0 previous found buffer delete char at buffer length 1 if buffer length 0 save leading text result add buffer to string buffer set length 0 result add make function reader previous else buffer append current 0 previous current 0 if buffer length 0 result add buffer to string catch io exception e log error error parsing function value e result clear result add value if result size 0 result add return result compoundvariable makefunction stringreader linkedlist compilestring invalidvariableexception stringreader stringreader linkedlist linkedlist stringbuffer stringbuffer deletecharat tostring setlength makefunction tostring ioexception compile a string into a function or simple variable called by link compile string string when that has detected calls link compound variable get named function string if it detects start of parameter list end of function call param reader points to input after the return the function or variable object or a string object make function string reader reader throws invalid variable exception char current new char 1 char previous todo why use space string buffer buffer new string buffer object function try while reader read current 1 if current 0 if reader read current 0 break previous buffer append current 0 continue else if current 0 previous string func name buffer to string function compound variable get named function func name if function instanceof function function function set parameters parse params reader if reader read current 0 current 0 reader reset set to start of string char cb new char 100 reader read cb return deliberately ignored throw new invalid variable exception expected after func name function call in new string cb if function instanceof test listener standardj meter engine register test listener function return function else function does not exist so treat as per missing variable buffer append current 0 continue else if current 0 variable or function with no parameter list function compound variable get named function buffer to string if function instanceof function ensure that set parameters is called function function set parameters new linked list buffer set length 0 return function else buffer append current 0 previous current 0 catch io exception e log error error parsing function buffer to string e return null log warn probably an invalid function string buffer to string return buffer to string simplevariable compilestring compoundvariable getnamedfunction makefunction stringreader invalidvariableexception stringbuffer stringbuffer funcname tostring compoundvariable getnamedfunction funcname setparameters parseparams invalidvariableexception funcname testlistener standardjmeterengine testlistener compoundvariable getnamedfunction tostring setparameters setparameters linkedlist setlength ioexception tostring tostring tostring compile a string into a list of parameters each made into a compound variable parses strings of the following form ul li text li li text text li li li ul param reader a string reader pointing to the current input location just after linked list parse params string reader reader throws invalid variable exception linked list result new linked list string buffer buffer new string buffer char current new char 1 char previous int function recursion 0 int paren recursion 0 try while reader read current 1 if current 0 process escaped characters buffer append current 0 store the if reader read current 0 break end of buffer previous buffer append current 0 store the following character continue else if current 0 function recursion 0 compound variable param new compound variable param set parameters buffer to string buffer set length 0 result add param else if current 0 function recursion 0 paren recursion 0 detect function name so this does not generate empty string as the parameter if buffer length 0 result is empty return result normal exit occurs here compound variable param new compound variable param set parameters buffer to string buffer set length 0 result add param return result else if current 0 previous buffer append current 0 previous current 0 function recursion else if current 0 function recursion 0 buffer append current 0 previous current 0 function recursion else if current 0 function recursion 0 paren recursion 0 buffer append current 0 previous current 0 paren recursion else if current 0 function recursion 0 buffer append current 0 previous current 0 paren recursion else buffer append current 0 previous current 0 catch io exception e should not happen with string reader log error error parsing function buffer to string e dropped out i e did not find closing log warn probably an invalid function string buffer to string compound variable var new compound variable var set parameters buffer to string result add var return result compoundvariable stringreader linkedlist parseparams stringreader invalidvariableexception linkedlist linkedlist stringbuffer stringbuffer functionrecursion parenrecursion functionrecursion compoundvariable compoundvariable setparameters tostring setlength functionrecursion parenrecursion functionname isempty compoundvariable compoundvariable setparameters tostring setlength functionrecursion functionrecursion functionrecursion functionrecursion parenrecursion parenrecursion functionrecursion parenrecursion ioexception stringreader tostring tostring compoundvariable compoundvariable setparameters tostring parse all user parameter data defined in xml file param xmluri name of the xml to load users parameter data return all users name value pairs obtained from xml file public list getxml parameters string xmluri throws sax exception io exception create instances needed for parsing xml reader reader j meter utils getxml parser xml reader factory createxml reader vendor parse class user parameterxml content handler thread parameters content handler new user parameterxml content handler user parameterxml error handler parameter error handler new user parameterxml error handler register content handler reader set content handler thread parameters content handler register error handler reader set error handler parameter error handler request validation reader set feature http xml org sax features validation true non nls 1 parse input source input source new input source xmluri reader parse input source return thread parameters content handler get parsed parameters getxmlparameters saxexception ioexception xmlreader jmeterutils getxmlparser xmlreaderfactory createxmlreader vendorparseclass userparameterxmlcontenthandler threadparameterscontenthandler userparameterxmlcontenthandler userparameterxmlerrorhandler parametererrorhandler userparameterxmlerrorhandler setcontenthandler threadparameterscontenthandler seterrorhandler parametererrorhandler setfeature inputsource inputsource inputsource inputsource threadparameterscontenthandler getparsedparameters list loop iter listeners new array list public test compiler hash tree test tree j meter variables vars this test tree test tree loopiterlisteners arraylist testcompiler hashtree testtree jmetervariables testtree testtree clears the pairing set called by standard jmeter engine at the start of a test run public static void initialize synch is probably not needed as only called before run starts synchronized pairing pairing clear standardjmeterengine public sample package configure sampler sampler sampler sample package pack sample package sampler config map get sampler pack set sampler sampler configure with config elements sampler pack get configs return pack samplepackage configuresampler samplepackage samplepackage samplerconfigmap setsampler configurewithconfigelements getconfigs public sample package configure transaction sampler transaction sampler transaction sampler transaction controller controller transaction sampler get transaction controller sample package pack sample package transaction controller config map get controller pack set sampler transaction sampler return pack samplepackage configuretransactionsampler transactionsampler transactionsampler transactioncontroller transactionsampler gettransactioncontroller samplepackage samplepackage transactioncontrollerconfigmap setsampler transactionsampler public void done sample package pack pack recover running version samplepackage recoverrunningversion public void add node object node hash tree sub tree stack add last node addnode hashtree subtree addlast public void subtract node log debug subtracting node stack size stack size test element child test element stack get last track iteration listeners stack if child instanceof sampler save sampler configs sampler child else if child instanceof transaction controller save transaction controller configs transaction controller child stack remove last if stack size 0 object pair pair new object pair child test element stack get last synchronized pairing called from multiple threads if pairing contains pair pair add test elements pairing add pair subtractnode testelement testelement getlast trackiterationlisteners savesamplerconfigs transactioncontroller savetransactioncontrollerconfigs transactioncontroller removelast objectpair objectpair testelement getlast addtestelements private void track iteration listeners linked list p stack test element child test element p stack get last if child instanceof loop iteration listener list iterator iter p stack list iterator p stack size while iter has previous test element item test element iter previous if item child continue if item instanceof controller test bean helper prepare child controller item add iteration listener loop iteration listener child break trackiterationlisteners linkedlist p_stack testelement testelement p_stack getlast loopiterationlistener listiterator p_stack listiterator p_stack hasprevious testelement testelement testbeanhelper additerationlistener loopiterationlistener public void process path processpath private void save sampler configs sampler sam list configs new linked list list modifiers new linked list list controllers new linked list list response modifiers new linked list list listeners new linked list list timers new linked list list assertions new linked list linked list posts new linked list linked list pres new linked list for int i stack size i 0 i add direct parent controllers controllers test element stack get i 1 iterator iter test tree list stack sub list 0 i iterator list temp pre new linked list list temp post new linked list while iter has next test element item test element iter next if item instanceof config test element configs add item if item instanceof sample listener listeners add item if item instanceof timer timers add item if item instanceof assertion assertions add item if item instanceof post processor temp post add item if item instanceof pre processor temp pre add item pres add all 0 temp pre posts add all 0 temp post sample package pack new sample package configs modifiers response modifiers listeners timers assertions posts pres controllers pack set sampler sam pack set running version true sampler config map put sam pack savesamplerconfigs linkedlist linkedlist linkedlist responsemodifiers linkedlist linkedlist linkedlist linkedlist linkedlist linkedlist linkedlist linkedlist adddirectparentcontrollers testelement testtree sublist temppre linkedlist temppost linkedlist hasnext testelement testelement configtestelement samplelistener postprocessor temppost preprocessor temppre addall temppre addall temppost samplepackage samplepackage responsemodifiers setsampler setrunningversion samplerconfigmap private void save transaction controller configs transaction controller tc list configs new linked list list modifiers new linked list list controllers new linked list list response modifiers new linked list list listeners new linked list list timers new linked list list assertions new linked list linked list posts new linked list linked list pres new linked list for int i stack size i 0 i add direct parent controllers controllers test element stack get i 1 iterator iter test tree list stack sub list 0 i iterator while iter has next test element item test element iter next if item instanceof sample listener listeners add item if item instanceof assertion assertions add item sample package pack new sample package configs modifiers response modifiers listeners timers assertions posts pres controllers pack set sampler new transaction sampler tc tc get name pack set running version true transaction controller config map put tc pack savetransactioncontrollerconfigs transactioncontroller linkedlist linkedlist linkedlist responsemodifiers linkedlist linkedlist linkedlist linkedlist linkedlist linkedlist linkedlist linkedlist adddirectparentcontrollers testelement testtree sublist hasnext testelement testelement samplelistener samplepackage samplepackage responsemodifiers setsampler transactionsampler getname setrunningversion transactioncontrollerconfigmap param controllers param i private void add direct parent controllers list controllers test element maybe controller if maybe controller instanceof controller log debug adding controller maybe controller to sampler config controllers add maybe controller adddirectparentcontrollers testelement maybecontroller maybecontroller maybecontroller maybecontroller test element child parent public object pair test element one test element two this child one this parent two testelement objectpair testelement testelement public void add test elements if parent instanceof controller child instanceof sampler child instanceof controller parent add test element child addtestelements addtestelement public int hash code return child hash code parent hash code hashcode hashcode hashcode public boolean equals object o if o instanceof object pair return child object pair o child parent object pair o parent return false objectpair objectpair objectpair private void configure with config elements sampler sam list configs iterator iter configs iterator while iter has next config test element config config test element iter next sam add test element config configurewithconfigelements hasnext configtestelement configtestelement addtestelement public void process try bsf manager mgr get manager if mgr null return process file or script mgr mgr terminate catch bsf exception e log warn problem in bsf script e bsfmanager getmanager processfileorscript bsfexception private object values public char function charfunction public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception str builder sb new str builder values length for int i 0 i values length i string number string compound variable values i execute trim long value 0 try if number string starts with 0x non nls 1 value long parse long number string substring 2 16 else value long parse long number string catch number format exception e log warn could not parse number string e char ch char value sb append ch return sb to string sampleresult previousresult currentsampler invalidvariableexception strbuilder strbuilder numberstring compoundvariable numberstring startswith parselong numberstring parselong numberstring numberformatexception numberstring tostring public synchronized void set parameters collection parameters throws invalid variable exception check min parameter count parameters 1 values parameters to array setparameters invalidvariableexception checkminparametercount toarray public string get reference key return key getreferencekey public list get argument desc return desc getargumentdesc constructor public graph accum model log debug start graph accum model1 listeners new linked list samples collections synchronized list new linked list log debug end graph accum model1 graphaccummodel graphaccummodel1 linkedlist synchronizedlist linkedlist graphaccummodel1 sets the name attribute of the graph model object param name the new name value public void set name string name this name name graphmodel setname gets the sample count attribute of the graph accum model object return the sample count value public int get sample count return samples size samplecount graphaccummodel samplecount getsamplecount gets the list attribute of the graph accum model object return the list value public list get list return samples graphaccummodel getlist gets the name attribute of the graph model object return the name value public string get name return name graphmodel getname gets the max attribute of the graph accum model object return the max value public long get max log debug get max1 returning max return max graphaccummodel getmax getmax1 adds a feature to the model listener attribute of the graph accum model object param listener the feature to be added to the graph accum listener attribute public void add graph accum listener graph accum listener listener listeners add listener modellistener graphaccummodel graphaccumlistener addgraphaccumlistener graphaccumlistener clear the results public void clear data log debug start clear1 samples clear max 1 big change true this fire data changed log debug end clear1 cleardata bigchange firedatachanged add the new sample to the results param res sample containing the results public void add new sample sample result res log debug start add new sample1 set time to time taken to load this url without components e g images etc long total time res get time if log is debug enabled log debug add new sample1 time total time log debug add new sample1 max max if total time max big change true max total time current res samples add res log debug end add new sample1 fire data changed addnewsample sampleresult addnewsample1 totaltime gettime isdebugenabled addnewsample1 totaltime addnewsample1 totaltime bigchange totaltime addnewsample1 firedatachanged depending on whether the graph needs to be rescale call the appropriate methods protected void fire data changed log debug start fire data changed1 iterator iter listeners iterator if big change while iter has next graph accum listener iter next update gui big change false else quick update current log debug end fire data changed1 firedatachanged firedatachanged1 bigchange hasnext graphaccumlistener updategui bigchange quickupdate firedatachanged1 the sample to be added did not exceed the current set of samples so do not need to rescale graph protected void quick update sample result s iterator iter listeners iterator while iter has next graph accum listener iter next update gui s quickupdate sampleresult hasnext graphaccumlistener updategui create a new transaction controller gui instance public transaction controller gui init transactioncontrollergui transactioncontrollergui implements j metergui component create test element public test element create test element transaction controller lc new transaction controller configure test element lc return lc jmeterguicomponent createtestelement testelement createtestelement transactioncontroller transactioncontroller configuretestelement public void configure test element el super configure el parent set selected transaction controller el is parent testelement setselected transactioncontroller isparent implements j metergui component modify test element test element public void modify test element test element el configure test element el transaction controller el set parent parent is selected jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement transactioncontroller setparent isselected public string get label resource return transaction controller title non nls 1 getlabelresource transaction_controller_title initialize the gui components and layout for this component private void init set layout new vertical layout 5 vertical layout both vertical layout top set border make border add make title panel parent new j check box j meter utils get res string transaction controller parent non nls 1 add parent setlayout verticallayout verticallayout verticallayout setborder makeborder maketitlepanel jcheckbox jmeterutils getresstring transaction_controller_parent constructor public if controller super ifcontroller constructor public if controller string condition super this set condition condition ifcontroller setcondition condition accessor this is gonna be like count 10 public void set condition string condition set property new string property condition condition setcondition setproperty stringproperty condition accessor this is gonna be like count 10 public string get condition return get property as string condition getcondition getpropertyasstring evaluate the condition clause log error if bad condition private static boolean evaluate condition string cond logger debug get condition cond string result str boolean result false now evaluate the condition using java script context cx context enter try scriptable scope cx init standard objects null object cx result object cx evaluate string scope cond condition string cmd 1 null result str context to string cx result object if result str equals false non nls 1 result false else if result str equals true non nls 1 result true else throw new exception bad condition cond expected true or false logger debug evaluate condition cond results is result catch exception e logger error e get message e finally context exit return result evaluatecondition getcondition resultstr javascript initstandardobjects cxresultobject evaluatestring conditionstring resultstr tostring cxresultobject resultstr resultstr getmessage private static boolean evaluate expression string cond return cond equals ignore case true non nls 1 evaluateexpression equalsignorecase this is overriding the parent method is done indicates whether the termination condition is reached i e if the condition evaluates to false then is done returns true public boolean is done boolean result true try result evaluate condition catch exception e logger error e get message e set done true return result set done false return false isdone isdone isdone evaluatecondition getmessage setdone setdone see org apache jmeter control controller next public sampler next we should only evalute the condition if it is the first time first iteration we are called for subsequent calls we are inside the if controller group so then we just pass the control to the next item inside the if control boolean result true if is evaluate all is first result is use expression evaluate expression get condition evaluate condition get condition if result return super next try return next is null catch next is null exception e1 return null ifcontrollergroup isevaluateall isfirst isuseexpression evaluateexpression getcondition evaluatecondition getcondition nextisnull nextisnullexception public boolean is evaluate all return get property as boolean evaluate all false isevaluateall getpropertyasboolean evaluate_all public void set evaluate all boolean b set property evaluate all b setevaluateall setproperty evaluate_all public boolean is use expression return get property as boolean use expression false isuseexpression getpropertyasboolean use_expression public void set use expression boolean selected set property use expression selected false setuseexpression setproperty use_expression private j dialog stopping message public report main frame log warn constructor only intended for use in testing non nls 1 jdialog stoppingmessage reportmainframe create a new j meter frame param action handler this parameter is not used param tree model the model for the test tree param tree listener the listener for the test tree public report main frame action listener action handler tree model tree model report tree listener tree listener running indicator new j button stopped icon running indicator set margin new insets 0 0 0 0 running indicator set border border factory create empty border this tree this make tree tree model tree listener report gui package get instance set main frame this init set default close operation do nothing on close jmeter actionhandler treemodel treelistener reportmainframe actionlistener actionhandler treemodel treemodel reporttreelistener treelistener runningindicator jbutton stoppedicon runningindicator setmargin runningindicator setborder borderfactory createemptyborder maketree treemodel treelistener reportguipackage getinstance setmainframe setdefaultcloseoperation do_nothing_on_close specify whether or not the file load menu item should be enabled param enabled true if the menu item should be enabled false otherwise public void set file load enabled boolean enabled menu bar set file load enabled enabled setfileloadenabled menubar setfileloadenabled specify whether or not the file save menu item should be enabled param enabled true if the menu item should be enabled false otherwise public void set file save enabled boolean enabled menu bar set file save enabled enabled setfilesaveenabled menubar setfilesaveenabled set the menu that should be used for the edit menu param menu the new edit menu public void set edit menu j popup menu menu menu bar set edit menu menu seteditmenu jpopupmenu menubar seteditmenu specify whether or not the edit menu item should be enabled param enabled true if the menu item should be enabled false otherwise public void set edit enabled boolean enabled menu bar set edit enabled enabled seteditenabled menubar seteditenabled set the menu that should be used for the edit add menu param menu the new edit add menu public void set edit add menu j menu menu menu bar set edit add menu menu seteditaddmenu jmenu menubar seteditaddmenu specify whether or not the edit add menu item should be enabled param enabled true if the menu item should be enabled false otherwise public void set edit add enabled boolean enabled menu bar set edit add enabled enabled seteditaddenabled menubar seteditaddenabled specify whether or not the edit remove menu item should be enabled param enabled true if the menu item should be enabled false otherwise public void set edit remove enabled boolean enabled menu bar set edit remove enabled enabled seteditremoveenabled menubar seteditremoveenabled close the currently selected menu public void close menu if menu bar is selected menu element menu element menu bar get sub elements if menu element null for int i 0 i menu element length i j menu menu j menu menu element i if menu is selected menu set popup menu visible false menu set selected false break closemenu menubar isselected menuelement menuelement menubar getsubelements menuelement menuelement jmenu jmenu menuelement isselected setpopupmenuvisible setselected show a dialog indicating that j meter threads are stopping on a particular host param host the host where j meter threads are stopping public void show stopping message string host stopping message new j dialog this j meter utils get res string stopping test title true non nls 1 j label stop label new j label j meter utils get res string stopping test host non nls 1 stop label set border border factory create empty border 20 20 20 20 stopping message get content pane add stop label stopping message pack component util center component in component this stopping message swing utilities invoke later new runnable public void run if stopping message null stopping message show jmeter jmeter showstoppingmessage stoppingmessage jdialog jmeterutils getresstring stopping_test_title jlabel stoplabel jlabel jmeterutils getresstring stopping_test stoplabel setborder borderfactory createemptyborder stoppingmessage getcontentpane stoplabel stoppingmessage componentutil centercomponentincomponent stoppingmessage swingutilities invokelater stoppingmessage stoppingmessage swing utilities invoke later new runnable public void run if stopping message null stopping message show swingutilities invokelater stoppingmessage stoppingmessage public void set main panel j component comp main panel set viewport view comp setmainpanel jcomponent mainpanel setviewportview public j tree get tree return this tree jtree gettree not sure if this should be in the report main frame since the report component doesn t really test it generates reports for now i will use it to trigger reporting later we can refactor main frame and create an abstract base class public void test started super test started reportmainframe mainframe teststarted teststarted not sure if this should be in the report main frame since the report component doesn t really test it generates reports for now i will use it to trigger reporting later we can refactor main frame and create an abstract base class public void test started string host super test started host reportmainframe mainframe teststarted teststarted not sure if this should be in the report main frame since the report component doesn t really test it generates reports for now i will use it to trigger reporting later we can refactor main frame and create an abstract base class public void test ended super test ended reportmainframe mainframe testended testended not sure if this should be in the report main frame since the report component doesn t really test it generates reports for now i will use it to trigger reporting later we can refactor main frame and create an abstract base class public void test ended string host super test ended host reportmainframe mainframe testended testended implements test listener test iteration start loop iteration event public void test iteration start loop iteration event event testlistener testiterationstart loopiterationevent testiterationstart loopiterationevent create the gui components and layout private void init called from ctor so must not be overridable menu bar new report menu bar setj menu bar menu bar j panel all new j panel new border layout all add create tool bar border layout north j split pane tree and main new j split pane j split pane horizontal split tree panel create tree panel tree and main set left component tree panel main panel create main panel tree and main set right component main panel tree and main set resize weight 2 tree and main set continuous layout true all add tree and main border layout center get content pane add all tree set selection row 1 add window listener new window happenings set title default title set icon image j meter utils get image jmeter jpg get image non nls 1 menubar reportmenubar setjmenubar menubar jpanel jpanel borderlayout createtoolbar borderlayout jsplitpane treeandmain jsplitpane jsplitpane horizontal_split treepanel createtreepanel treeandmain setleftcomponent treepanel mainpanel createmainpanel treeandmain setrightcomponent mainpanel treeandmain setresizeweight treeandmain setcontinuouslayout treeandmain borderlayout getcontentpane setselectionrow addwindowlistener windowhappenings settitle default_title seticonimage jmeterutils getimage getimage public void set extended frame title string fname file new operation may set to null so just return app name if fname null set title default title return allow for windows chars in filename string temp fname replace non nls 1 non nls 2 string simple name temp substring temp last index of 1 non nls 1 set title simple name fname default title non nls 1 non nls 2 setextendedframetitle settitle default_title simplename lastindexof settitle simplename default_title create the j meter tool bar pane containing the running indicator return a panel containing the running indicator protected component create tool bar box tool panel new box box layout x axis tool panel add box create rigid area new dimension 10 15 tool panel add box create glue tool panel add running indicator return tool panel jmeter createtoolbar toolpanel boxlayout x_axis toolpanel createrigidarea toolpanel createglue toolpanel runningindicator toolpanel create the panel where the gui representation of the test tree is displayed the tree should already be created before calling this method return a scroll pane containing the test tree gui protected j scroll pane create tree panel j scroll pane treep new j scroll pane tree treep set minimum size new dimension 100 0 return treep jscrollpane createtreepanel jscrollpane jscrollpane setminimumsize create the main panel where components can display their gu is return the main scroll pane protected j scroll pane create main panel return new j scroll pane guis jscrollpane createmainpanel jscrollpane create and initialize the gui representation of the test tree param tree model the test tree model param tree listener the test tree listener return the initialized test tree gui private j tree make tree tree model tree model report tree listener tree listener j tree treevar new j tree tree model treevar set cell renderer get cell renderer treevar set root visible false treevar set shows root handles true tree listener setj tree treevar treevar add tree selection listener tree listener treevar add mouse listener tree listener treevar add mouse motion listener tree listener treevar add key listener tree listener return treevar treemodel treelistener jtree maketree treemodel treemodel reporttreelistener treelistener jtree jtree treemodel setcellrenderer getcellrenderer setrootvisible setshowsroothandles treelistener setjtree addtreeselectionlistener treelistener addmouselistener treelistener addmousemotionlistener treelistener addkeylistener treelistener create the tree cell renderer used to draw the nodes in the test tree return a renderer to draw the test tree nodes protected tree cell renderer get cell renderer default tree cell renderer rend new report cell renderer rend set font new font dialog font plain 11 return rend treecellrenderer getcellrenderer defaulttreecellrenderer reportcellrenderer setfont public void draw dragged component component drag icon int x int y dimension size drag icon get preferred size tree panel paint immediately previous dragx location previous dragy location size width size height this get layered pane set layer drag icon 400 swing utilities paint component tree panel get graphics drag icon tree panel x y size width size height previous dragx location x previous dragy location y drawdraggedcomponent dragicon dragicon getpreferredsize treepanel paintimmediately previousdragxlocation previousdragylocation getlayeredpane setlayer dragicon swingutilities paintcomponent treepanel getgraphics dragicon treepanel previousdragxlocation previousdragylocation protected static class window happenings extends window adapter called when the main j meter frame is being closed sends a notification so that j meter can react appropriately param event the window event to handle public void window closing window event event report action router get instance action performed new action event this event getid exit windowhappenings windowadapter jmeter jmeter windowevent windowclosing windowevent reportactionrouter getinstance actionperformed actionevent get result public assertion result get result sample result response assertion result result new assertion result get name note initialised with error failure false byte data response get response data if data length 0 return result set result for null string result data new string get result body data string xsd file name get xsd file name if log is debug enabled log debug xml string result data log debug xsd file name xsd file name if xsd file name null xsd file name length 0 result set result for failure file name is required else set schema result result result data xsd file name return result getresult assertionresult getresult sampleresult assertionresult assertionresult getname getresponsedata setresultfornull resultdata getresultbody xsdfilename getxsdfilename isdebugenabled xmlstring resultdata xsdfilename xsdfilename xsdfilename xsdfilename setresultforfailure file_name_is_required setschemaresult resultdata xsdfilename private byte get result body byte result data for int i 0 i result data length 1 i if result data i n result data i 1 n return j orphan utils get byte array slice result data i 2 result data length 1 return result data getresultbody resultdata resultdata resultdata resultdata jorphanutils getbytearrayslice resultdata resultdata resultdata public void set xsd file name string xml schema file name throws illegal argument exception set property xsd filename key xml schema file name setxsdfilename xmlschemafilename illegalargumentexception setproperty xsd_filename_key xmlschemafilename public string get xsd file name return get property as string xsd filename key getxsdfilename getpropertyasstring xsd_filename_key set schema result param result param xml str param xsd file name private void set schema result assertion result result string xml str string xsd file name try boolean to return true document doc null document builder factory parser factory document builder factory new instance parser factory set validating true parser factory set namespace aware true parser factory set attribute jaxp schema language w3c xml schema parser factory set attribute jaxp schema source xsd file name create a parser document builder parser parser factory new document builder parser set error handler new sax error handler result doc parser parse new input source new string reader xml str if everything went fine then xml schema validation is valid catch sax parse exception e only set message if error not yet flagged if result is error result is failure result set error true result set failure message error details e catch sax exception e log warn e to string result set result for failure e get message catch io exception e log warn io error e result set result for failure e get message catch parser configuration exception e log warn problem with parser config e result set result for failure e get message xmlstr xsdfilename setschemaresult assertionresult xmlstr xsdfilename toreturn documentbuilderfactory parserfactory documentbuilderfactory newinstance parserfactory setvalidating parserfactory setnamespaceaware parserfactory setattribute jaxp_schema_language w3c_xml_schema parserfactory setattribute jaxp_schema_source xsdfilename documentbuilder parserfactory newdocumentbuilder seterrorhandler saxerrorhandler inputsource stringreader xmlstr saxparseexception iserror isfailure seterror setfailuremessage errordetails saxexception tostring setresultforfailure getmessage ioexception setresultforfailure getmessage parserconfigurationexception setresultforfailure getmessage helper method to construct sax error details private static string error details sax parse exception spe string buffer str new string buffer 80 int i i spe get line number if i 1 str append line str append i str append col str append spe get column number str append str append spe get localized message return str to string errordetails saxparseexception stringbuffer stringbuffer getlinenumber getcolumnnumber getlocalizedmessage tostring private assertion result result public sax error handler assertion result result this result result assertionresult saxerrorhandler assertionresult public void error sax parse exception exception throws sax parse exception string msg error error details exception log debug msg result set failure message msg result set error true throw exception saxparseexception saxparseexception errordetails setfailuremessage seterror public void fatal error sax parse exception exception throws sax parse exception string msg fatal error details exception log debug msg result set failure message msg result set error true throw exception fatalerror saxparseexception saxparseexception errordetails setfailuremessage seterror public void warning sax parse exception exception throws sax parse exception string msg warning error details exception log debug msg result set failure message msg result set error true todo is this the correct strategy throw exception allow assertion to pass saxparseexception saxparseexception errordetails setfailuremessage seterror private j labeled text field embeddedre regular expression used to match against embedded resource ur ls public http test sample gui init jlabeledtextfield urls httptestsamplegui public void configure test element element super configure element final http sampler base sampler base http sampler base element url config gui configure element get images set selected sampler base is image parser is mon set selected sampler base is monitor usemd5 set selected sampler base usemd5 embeddedre set text sampler base get embedded urlre testelement httpsamplerbase samplerbase httpsamplerbase urlconfiggui getimages setselected samplerbase isimageparser ismon setselected samplerbase ismonitor setselected samplerbase settext samplerbase getembeddedurlre public test element create test element http sampler base sampler http sampler factory new instance create default sampler modify test element sampler return sampler testelement createtestelement httpsamplerbase httpsamplerfactory newinstance modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element sampler sampler clear url config gui modify test element sampler final http sampler base sampler base http sampler base sampler if get images is selected sampler base set image parser true else the default is false so we can remove the property to simplify jmx files this also allows http defaults to work for this checkbox sampler remove property http sampler base image parser sampler base set monitor is mon is selected sampler base setmd5 usemd5 is selected sampler base set embedded urlre embeddedre get text this configure test element sampler testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement urlconfiggui modifytestelement httpsamplerbase samplerbase httpsamplerbase getimages isselected samplerbase setimageparser httpdefaults removeproperty httpsamplerbase image_parser samplerbase setmonitor ismon isselected samplerbase isselected samplerbase setembeddedurlre gettext configuretestelement public string get label resource return web testing title non nls 1 getlabelresource web_testing_title private void init called from ctor so must not be overridable set layout new border layout 0 5 set border make border add make title panel border layout north url config url config gui new multipart url config gui add url config gui border layout center optional tasks add create optional tasks panel border layout south setlayout borderlayout setborder makeborder maketitlepanel borderlayout urlconfiggui multiparturlconfiggui urlconfiggui borderlayout createoptionaltaskspanel borderlayout private j panel create optional tasks panel optional tasks j panel optional tasks panel new vertical panel optional tasks panel set border border factory create titled border border factory create etched border j meter utils get res string optional tasks non nls 1 j panel check box panel new horizontal panel retrieve images get images new j check box j meter utils get res string web testing retrieve images non nls 1 is monitor is mon new j check box j meter utils get res string monitor is title non nls 1 use md5 usemd5 new j check box j meter utils get res string response save as md5 non nls 1 check box panel add get images check box panel add is mon check box panel add usemd5 optional tasks panel add check box panel embedded url match regex embeddedre new j labeled text field j meter utils get res string web testing embedded url pattern 30 non nls 1 optional tasks panel add embeddedre return optional tasks panel jpanel createoptionaltaskspanel jpanel optionaltaskspanel verticalpanel optionaltaskspanel setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring optional_tasks jpanel checkboxpanel horizontalpanel getimages jcheckbox jmeterutils getresstring web_testing_retrieve_images ismon jcheckbox jmeterutils getresstring monitor_is_title jcheckbox jmeterutils getresstring response_save_as_md5 checkboxpanel getimages checkboxpanel ismon checkboxpanel optionaltaskspanel checkboxpanel jlabeledtextfield jmeterutils getresstring web_testing_embedded_url_pattern optionaltaskspanel optionaltaskspanel public dimension get preferred size return get minimum size getpreferredsize getminimumsize public void clear gui super clear gui get images set selected false is mon set selected false usemd5 set selected false url config gui clear embeddedre set text non nls 1 cleargui cleargui getimages setselected ismon setselected setselected urlconfiggui settext public httpssl protocol socket factory jssessl manager ssl manager super this ssl manager ssl manager cps 0 httpsslprotocolsocketfactory jssesslmanager sslmanager sslmanager sslmanager public httpssl protocol socket factory jssessl manager ssl manager int cps super this ssl manager ssl manager cps cps httpsslprotocolsocketfactory jssesslmanager sslmanager sslmanager sslmanager private void set socket socket socket if socket instanceof ssl socket throw new illegal argument exception expected ssl socket ssl socket sock ssl socket socket if protocol list length 0 try sock set enabled protocols protocols catch illegal argument exception e log warn could not set protocol list protocol list log warn valid protocols are join sock get supported protocols setsocket sslsocket illegalargumentexception sslsocket sslsocket sslsocket protocollist setenabledprotocols illegalargumentexception protocollist getsupportedprotocols private string join string strings string buffer sb new string buffer for int i 0 i strings length i if i 0 sb append sb append strings i return sb to string stringbuffer stringbuffer tostring private ssl socket factory getssl socket factory throws io exception try ssl context ssl context this ssl manager get context return ssl context get socket factory catch general security exception ex throw new io exception ex get message sslsocketfactory getsslsocketfactory ioexception sslcontext sslcontext sslmanager getcontext sslcontext getsocketfactory generalsecurityexception ioexception getmessage private socket wrap socket socket sock if cps 0 return new slowssl socket ssl socket sock cps return sock wrapsocket slowsslsocket sslsocket attempts to get a new socket connection to the given host within the given time limit param host the host name ip param port the port on the host param local address the local host name ip to bind the socket to param local port the port on the local machine param params link http connection params http connection parameters return socket a new socket throws io exception if an i o error occurs while creating the socket throws unknown host exception if the ip address of the host cannot be determined public socket create socket final string host final int port final inet address local address final int local port final http connection params params throws io exception unknown host exception connect timeout exception if params null throw new illegal argument exception parameters may not be null int timeout params get connection timeout ssl socket factory sslfac getssl socket factory socket socket if timeout 0 socket sslfac create socket host port local address local port else socket sslfac create socket socket address localaddr new inet socket address local address local port socket address remoteaddr new inet socket address host port socket bind localaddr socket connect remoteaddr timeout set socket socket return wrap socket socket localaddress localport httpconnectionparams ioexception unknownhostexception createsocket inetaddress localaddress localport httpconnectionparams ioexception unknownhostexception connecttimeoutexception illegalargumentexception getconnectiontimeout sslsocketfactory getsslsocketfactory createsocket localaddress localport createsocket socketaddress inetsocketaddress localaddress localport socketaddress inetsocketaddress setsocket wrapsocket see secure protocol socket factory create socket java lang string int public socket create socket string host int port throws io exception unknown host exception ssl socket factory sslfac getssl socket factory socket sock sslfac create socket host port set socket sock return wrap socket sock secureprotocolsocketfactory createsocket createsocket ioexception unknownhostexception sslsocketfactory getsslsocketfactory createsocket setsocket wrapsocket see javax net socket factory create socket public socket create socket throws io exception unknown host exception ssl socket factory sslfac getssl socket factory socket sock sslfac create socket set socket sock return wrap socket sock socketfactory createsocket createsocket ioexception unknownhostexception sslsocketfactory getsslsocketfactory createsocket setsocket wrapsocket see secure protocol socket factory create socket java net socket java lang string int boolean public socket create socket socket socket string host int port boolean auto close throws io exception unknown host exception ssl socket factory sslfac getssl socket factory socket sock sslfac create socket socket host port auto close set socket sock return wrap socket sock secureprotocolsocketfactory createsocket createsocket autoclose ioexception unknownhostexception sslsocketfactory getsslsocketfactory createsocket autoclose setsocket wrapsocket see secure protocol socket factory create socket java lang string int java net inet address int public socket create socket string host int port inet address client host int client port throws io exception unknown host exception ssl socket factory sslfac getssl socket factory socket sock sslfac create socket host port client host client port set socket sock return wrap socket sock secureprotocolsocketfactory createsocket inetaddress createsocket inetaddress clienthost clientport ioexception unknownhostexception sslsocketfactory getsslsocketfactory createsocket clienthost clientport setsocket wrapsocket public socket create socket inet address host int port throws io exception ssl socket factory sslfac getssl socket factory socket sock sslfac create socket host port set socket sock return wrap socket sock createsocket inetaddress ioexception sslsocketfactory getsslsocketfactory createsocket setsocket wrapsocket public socket create socket inet address address int port inet address local address int local port throws io exception ssl socket factory sslfac getssl socket factory socket sock sslfac create socket address port local address local port set socket sock return wrap socket sock createsocket inetaddress inetaddress localaddress localport ioexception sslsocketfactory getsslsocketfactory createsocket localaddress localport setsocket wrapsocket public string get default cipher suites try ssl socket factory sslfac getssl socket factory return sslfac get default cipher suites catch io exception ex return new string getdefaultciphersuites sslsocketfactory getsslsocketfactory getdefaultciphersuites ioexception public string get supported cipher suites try ssl socket factory sslfac getssl socket factory return sslfac get supported cipher suites catch io exception ex return new string getsupportedciphersuites sslsocketfactory getsslsocketfactory getsupportedciphersuites ioexception new token object with a type and value token final int type final string value m type type m value value m_type m_value get the value of the token final string get value return m value getvalue m_value get the type of the token final int get type return m type gettype m_type convert to a string public final string to string final string buffer sb new string buffer sb append m type sb append sb append m value return sb to string tostring stringbuffer stringbuffer m_type m_value tostring public edit command editcommand public void do action action event e gui package gui package gui package get instance gui package get main frame set main panel javax swing j component gui package get current gui gui package get main frame set edit menu gui package get tree listener get current node create popup menu todo i believe the following code to the end of the method is obsolete since name panel no longer seems to be the gui for any component if gui package get current gui instanceof name panel gui package get main frame set file load enabled true gui package get main frame set file save enabled true else gui package get main frame set file load enabled false gui package get main frame set file save enabled false doaction actionevent guipackage guipackage guipackage getinstance guipackage getmainframe setmainpanel jcomponent guipackage getcurrentgui guipackage getmainframe seteditmenu guipackage gettreelistener getcurrentnode createpopupmenu namepanel guipackage getcurrentgui namepanel guipackage getmainframe setfileloadenabled guipackage getmainframe setfilesaveenabled guipackage getmainframe setfileloadenabled guipackage getmainframe setfilesaveenabled public set get action names return commands getactionnames call no args constructor for a class param class name return an instance of the class throws j meter exception if class cannot be created public static object construct string class name throws j meter exception object instance null try instance class utils get class class name new instance catch class not found exception e throw new j meter exception e catch instantiation exception e throw new j meter exception e catch illegal access exception e throw new j meter exception e return instance classname jmeterexception classname jmeterexception classutils getclass classname newinstance classnotfoundexception jmeterexception instantiationexception jmeterexception illegalaccessexception jmeterexception call a class constructor with an integer parameter param class name param parameter integer return an instance of the class throws j meter exception if class cannot be created public static object construct string class name int parameter throws j meter exception object instance null try class clazz class utils get class class name clazz get constructor new class integer type instance class utils get class class name new instance catch class not found exception e throw new j meter exception e catch instantiation exception e throw new j meter exception e catch illegal access exception e throw new j meter exception e catch security exception e throw new j meter exception e catch no such method exception e throw new j meter exception e return instance classname jmeterexception classname jmeterexception classutils getclass classname getconstructor classutils getclass classname newinstance classnotfoundexception jmeterexception instantiationexception jmeterexception illegalaccessexception jmeterexception securityexception jmeterexception nosuchmethodexception jmeterexception invoke a public method on a class instance param instance param method name throws security exception throws illegal argument exception throws j meter exception public static void invoke object instance string method name throws security exception illegal argument exception j meter exception method m try m class utils get public method instance get class method name new class m invoke instance null catch no such method exception e throw new j meter exception e catch illegal access exception e throw new j meter exception e catch invocation target exception e throw new j meter exception e methodname securityexception illegalargumentexception jmeterexception methodname securityexception illegalargumentexception jmeterexception classutils getpublicmethod getclass methodname nosuchmethodexception jmeterexception illegalaccessexception jmeterexception invocationtargetexception jmeterexception public entry config set new hash map cloned set new hash set assertions new linked list configset hashmap clonedset hashset linkedlist public void add assertion assertion assertion assertions add assertion addassertion public list get assertions return assertions getassertions public void set sampler class class sampler class this sampler sampler class setsamplerclass samplerclass samplerclass public class get sampler class return this sampler getsamplerclass public config element get config element class config class return config element config set get config class configelement getconfigelement configclass configelement configset configclass public void add config element config element config add config element config config get class addconfigelement configelement addconfigelement getclass add a config element as a specific class usually this is done to add a subclass as one of it s parent classes public void add config element config element config class as class if config null config element current config element config set get as class if current null config set put as class clone if necessary config else current add config element config addconfigelement configelement asclass configelement configelement configset asclass configset asclass cloneifnecessary addconfigelement private config element clone if necessary config element config if config expects modification return config return config element config clone configelement cloneifnecessary configelement expectsmodification configelement no arg constructor public report page reportpage public static report page create report page string name report page page new report page return page reportpage createreportpage reportpage reportpage public string get title return get property as string report page title gettitle getpropertyasstring report_page_title public void set title string title set property report page title title settitle setproperty report_page_title public boolean get index return get property as boolean report page index getindex getpropertyasboolean report_page_index public void set index string make index set property report page index make index setindex makeindex setproperty report_page_index makeindex public string getcss return get property as string report page css getpropertyasstring report_page_css public void setcss string css set property report page css css setproperty report_page_css public string get headerurl return get property as string report page header getheaderurl getpropertyasstring report_page_header public void set headerurl string url set property report page header url setheaderurl setproperty report_page_header public string get footerurl return get property as string report page footer getfooterurl getpropertyasstring report_page_footer public void set footerurl string url set property report page footer url setfooterurl setproperty report_page_footer public string get introduction return get property as string report page intro getintroduction getpropertyasstring report_page_intro public void set introduction string intro set property report page intro intro setintroduction setproperty report_page_intro private object values public eval function evalfunction public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception string parameter compound variable values 0 execute compound variable cv new compound variable parameter return cv execute sampleresult previousresult currentsampler invalidvariableexception compoundvariable compoundvariable compoundvariable public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters min parameter count max parameter count values parameters to array setparameters invalidvariableexception checkparametercount min_parameter_count max_parameter_count toarray public string get reference key return key getreferencekey public list get argument desc return desc getargumentdesc private static final sample save configuration static new sample save configuration public int get var count only for use by csv save service return var count samplesaveconfiguration _static samplesaveconfiguration getvarcount csvsaveservice varcount public void set var count int var count only for use by csv save service this var count var count setvarcount varcount csvsaveservice varcount varcount give access to initial configuration public static sample save configuration static config return static samplesaveconfiguration staticconfig _static public sample save configuration samplesaveconfiguration alternate constructor for use by old save service param value initial setting for boolean fields used in config dialogue public sample save configuration boolean value assertions value bytes value code value data type value encoding value field names value file name value hostname value label value latency value message value print milliseconds printmilliseconds is derived from properties only request headers value response data value response data on error value response headers value sampler data value save assertion results failure message value subresults value success value thread counts value sample count value thread name value time value timestamp value url value xml value oldsaveservice samplesaveconfiguration datatype fieldnames filename printmilliseconds _printmilliseconds requestheaders responsedata responsedataonerror responseheaders samplerdata saveassertionresultsfailuremessage threadcounts samplecount threadname private object read resolve formatter formatter return this readresolve _formatter public object clone try sample save configuration clone sample save configuration super clone if this formatter null clone formatter simple date format this formatter clone return clone catch clone not supported exception e throw new runtime exception should not happen e samplesaveconfiguration samplesaveconfiguration simpledateformat clonenotsupportedexception runtimeexception public boolean equals object obj if this obj return true if obj null obj get class this get class return false we know we are comparing to another sample save configuration sample save configuration s sample save configuration obj boolean primitive values s time time s latency latency s timestamp timestamp s success success s label label s code code s message message s thread name thread name s data type data type s encoding encoding s assertions assertions s subresults subresults s response data response data s sampler data sampler data s xml xml s field names field names s response headers response headers s request headers request headers s assertions results to save assertions results to save s save assertion results failure message save assertion results failure message s print milliseconds print milliseconds s response data on error response data on error s url url s bytes bytes s file name file name s hostname hostname s sample count sample count s thread counts thread counts boolean string values false if primitive values string values s delimiter delimiter delimiter null delimiter equals s delimiter boolean complex values false if primitive values string values complex values s formatter formatter formatter null formatter equals s formatter return primitive values string values complex values getclass getclass samplesaveconfiguration samplesaveconfiguration samplesaveconfiguration primitivevalues threadname threadname datatype datatype responsedata responsedata samplerdata samplerdata fieldnames fieldnames responseheaders responseheaders requestheaders requestheaders assertionsresultstosave assertionsresultstosave saveassertionresultsfailuremessage saveassertionresultsfailuremessage printmilliseconds printmilliseconds responsedataonerror responsedataonerror filename filename samplecount samplecount threadcounts threadcounts stringvalues primitivevalues stringvalues complexvalues primitivevalues stringvalues complexvalues primitivevalues stringvalues complexvalues public int hash code int hash 7 hash 31 hash time 1 0 hash 31 hash latency 1 0 hash 31 hash timestamp 1 0 hash 31 hash success 1 0 hash 31 hash label 1 0 hash 31 hash code 1 0 hash 31 hash message 1 0 hash 31 hash thread name 1 0 hash 31 hash data type 1 0 hash 31 hash encoding 1 0 hash 31 hash assertions 1 0 hash 31 hash subresults 1 0 hash 31 hash response data 1 0 hash 31 hash sampler data 1 0 hash 31 hash xml 1 0 hash 31 hash field names 1 0 hash 31 hash response headers 1 0 hash 31 hash request headers 1 0 hash 31 hash assertions results to save hash 31 hash save assertion results failure message 1 0 hash 31 hash print milliseconds 1 0 hash 31 hash response data on error 1 0 hash 31 hash url 1 0 hash 31 hash bytes 1 0 hash 31 hash file name 1 0 hash 31 hash hostname 1 0 hash 31 hash thread counts 1 0 hash 31 hash delimiter null delimiter hash code 0 hash 31 hash formatter null formatter hash code 0 hash 31 hash sample count 1 0 return hash hashcode threadname datatype responsedata samplerdata fieldnames responseheaders requestheaders assertionsresultstosave saveassertionresultsfailuremessage printmilliseconds responsedataonerror filename threadcounts hashcode hashcode samplecount start of standard save set access methods public boolean save response headers return response headers saveresponseheaders responseheaders public void set response headers boolean r response headers r setresponseheaders responseheaders public boolean save request headers return request headers saverequestheaders requestheaders public void set request headers boolean r request headers r setrequestheaders requestheaders public boolean save assertions return assertions saveassertions public void set assertions boolean assertions this assertions assertions setassertions public boolean save code return code savecode public void set code boolean code this code code setcode public boolean save data type return data type savedatatype datatype public void set data type boolean data type this data type data type setdatatype datatype datatype datatype public boolean save encoding return encoding saveencoding public void set encoding boolean encoding this encoding encoding setencoding public boolean save label return label savelabel public void set label boolean label this label label setlabel public boolean save latency return latency savelatency public void set latency boolean latency this latency latency setlatency public boolean save message return message savemessage public void set message boolean message this message message setmessage public boolean save response data sample result res return response data test plan get functional mode response data on error res is successful saveresponsedata sampleresult responsedata testplan getfunctionalmode responsedataonerror issuccessful public boolean save response data return response data saveresponsedata responsedata public void set response data boolean response data this response data response data setresponsedata responsedata responsedata responsedata public boolean save sampler data sample result res return sampler data test plan get functional mode as per 2 0 branch response data on error res is successful savesamplerdata sampleresult samplerdata testplan getfunctionalmode responsedataonerror issuccessful public boolean save sampler data return sampler data savesamplerdata samplerdata public void set sampler data boolean sampler data this sampler data sampler data setsamplerdata samplerdata samplerdata samplerdata public boolean save subresults return subresults savesubresults public void set subresults boolean subresults this subresults subresults setsubresults public boolean save success return success savesuccess public void set success boolean success this success success setsuccess public boolean save thread name return thread name savethreadname threadname public void set thread name boolean thread name this thread name thread name setthreadname threadname threadname threadname public boolean save time return time savetime public void set time boolean time this time time settime public boolean save timestamp return timestamp savetimestamp public void set timestamp boolean timestamp this timestamp timestamp settimestamp public boolean save as xml return xml saveasxml public void set as xml boolean xml this xml xml setasxml public boolean save field names return field names savefieldnames fieldnames public void set field names boolean print field names this field names print field names setfieldnames printfieldnames fieldnames printfieldnames public boolean save url return url saveurl public void set url boolean save this url save seturl public boolean save bytes return bytes savebytes public void set bytes boolean save this bytes save setbytes public boolean save file name return file name savefilename filename public void set file name boolean save this file name save setfilename filename public boolean save assertion results failure message return save assertion results failure message saveassertionresultsfailuremessage saveassertionresultsfailuremessage public void set assertion results failure message boolean b save assertion results failure message b setassertionresultsfailuremessage saveassertionresultsfailuremessage public boolean save thread counts return thread counts savethreadcounts threadcounts public void set thread counts boolean save this thread counts save setthreadcounts threadcounts public boolean save sample count return sample count savesamplecount samplecount public void set sample count boolean save this sample count save setsamplecount samplecount only intended for use by old save service and test cases public void set formatter date format fmt print milliseconds fmt null maintain relationship formatter fmt oldsaveservice setformatter dateformat printmilliseconds public boolean print milliseconds return print milliseconds printmilliseconds printmilliseconds public date format formatter return formatter dateformat public int assertions results to save return assertions results to save assertionsresultstosave assertionsresultstosave public string get delimiter return delimiter getdelimiter public string get xml pi return j meter utils getj meter properties get property xml pi defaults to empty getxmlpi jmeterutils getjmeterproperties getproperty xml_pi used by old save service public void set delimiter string delim delimiter delim setdelimiter used by sample save configuration converter unmarshall public void set default delimiter delimiter delimiter samplesaveconfigurationconverter setdefaultdelimiter _delimiter used by sample save configuration converter unmarshall public void set default time stamp format print milliseconds printmilliseconds formatter formatter samplesaveconfigurationconverter setdefaulttimestampformat printmilliseconds _printmilliseconds _formatter public boolean save hostname return hostname savehostname public void set hostname boolean save hostname save sethostname no arg constructor public long sum longsum execute the function see function execute sample result sampler public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception j meter variables vars get variables long sum 0 string var name compound variable values values length 1 execute trim for int i 0 i values length 1 i sum long parse long compound variable values i execute try sum long parse long var name var name null there is no variable name catch number format exception ignored string total string long to string sum if vars null var name null var name length 0 vars will be null on test plan vars put var name total string return total string sampleresult sampleresult previousresult currentsampler invalidvariableexception jmetervariables getvariables varname compoundvariable parselong compoundvariable parselong varname varname numberformatexception totalstring tostring varname varname testplan varname totalstring totalstring set the parameters for the function see function set parameters collection public synchronized void set parameters collection parameters throws invalid variable exception check min parameter count parameters 2 values parameters to array setparameters setparameters invalidvariableexception checkminparametercount toarray get the invocation key for this function see function get reference key public string get reference key return key getreferencekey getreferencekey get the description of this function see function get argument desc public list get argument desc return desc getargumentdesc getargumentdesc constructor for the ldap client object public ldap client ldapclient ldapclient connect to server public void connect string host string port string rootdn string username string password throws naming exception hashtable env new hashtable env put context initial context factory com sun jndi ldap ldap ctx factory non nls 1 env put context provider url ldap host port rootdn non nls 1 non nls 2 non nls 3 env put context referral throw non nls 1 env put context security credentials password env put context security principal username dir context new initial dir context env namingexception initial_context_factory ldapctxfactory provider_url security_credentials security_principal dircontext initialdircontext disconnect from the server public void disconnect try if dir context null dir context close dir context null catch naming exception e log error ldap client e dircontext dircontext dircontext namingexception filter the data in the ldap directory for the given search base param search base where the search should start param search filter filter this value from the base public boolean search test string search base string search filter throws naming exception system out println base search base filter search filter search controls searchcontrols new search controls search controls subtree scope 1l count limit 0 time limit null attributes null all false return object false dereference links naming enumeration ne dir context search search base search filter searchcontrols system out println loop ne to string ne has more while ne has more object tmp ne next system out println tmp get class get name search result sr search result tmp attributes at sr get attributes system out println at get cn system out println done ne has more return ne has more searchbase searchfilter searchtest searchbase searchfilter namingexception searchbase searchfilter searchcontrols searchcontrols searchcontrols subtree_scope namingenumeration dircontext searchbase searchfilter tostring hasmore hasmore getclass getname searchresult searchresult getattributes hasmore hasmore modify the attribute in the ldap directory for the given string param mods add all the entry in to the modification item param string the string dn value public void modify test modification item mods string string throws naming exception dir context modify attributes string mods modificationitem modifytest modificationitem namingexception dircontext modifyattributes create the attribute in the ldap directory for the given string param basicattributes add all the entry in to the basicattribute param string the string dn value public void create test basic attributes basicattributes string string throws naming exception dir context dc todo perhaps return this dir context create subcontext string basicattributes createtest basicattributes namingexception dircontext dircontext createsubcontext delete the attribute from the ldap directory param string the string dn value public void delete test string string throws naming exception dir context destroy subcontext string deletetest namingexception dircontext destroysubcontext private sample save configuration save config public save property dialog log warn constructor only intended for use in testing non nls 1 samplesaveconfiguration saveconfig savepropertydialog param owner param title param modal throws java awt headless exception public save property dialog frame owner string title boolean modal sample save configuration s throws headless exception super owner title modal save config s log debug sample save configuration save config non nls 1 dialog init headlessexception savepropertydialog samplesaveconfiguration headlessexception saveconfig samplesaveconfiguration saveconfig dialoginit private int count methods method m int count 0 for int i 0 i m length i if m i get name starts with name save pfx count return count countmethods getname startswith name_save_pfx protected void dialog init if save config null super dialog init this get content pane set layout new border layout method methods sample save configuration class get methods int x count methods methods 3 1 log debug grid panel is 3 by x j panel check panel new j panel new grid layout x 3 for int i 0 i methods length i string name methods i get name if name starts with name save pfx methods i get parameter types length 0 try name name substring name save pfx len j check box check new j check box j meter utils get res string resource prefix name non nls 1 boolean methods i invoke save config new object 0 boolean value check panel add check border layout north check add action listener this string action command name set prefix name non nls 1 check set action command action command if functors contains key action command functors put action command new functor action command catch exception e log warn problem creating save config dialog e get content pane add check panel border layout north j button exit new j button j meter utils get res string done non nls 1 this get content pane add exit border layout south exit add action listener new action listener public void action performed action event e dispose dialoginit saveconfig dialoginit getcontentpane setlayout borderlayout samplesaveconfiguration getmethods countmethods jpanel checkpanel jpanel gridlayout getname startswith name_save_pfx getparametertypes name_save_pfx_len jcheckbox jcheckbox jmeterutils getresstring resource_prefix saveconfig booleanvalue checkpanel borderlayout addactionlistener actioncommand name_set_prefix setactioncommand actioncommand containskey actioncommand actioncommand actioncommand getcontentpane checkpanel borderlayout jbutton jbutton jmeterutils getresstring getcontentpane borderlayout addactionlistener actionlistener actionperformed actionevent this get content pane add exit border layout south exit add action listener new action listener public void action performed action event e dispose getcontentpane borderlayout addactionlistener actionlistener actionperformed actionevent public void action performed action event e string action e get action command functor f functor functors get action f invoke save config new object boolean value of j check box e get source is selected actionperformed actionevent getactioncommand saveconfig valueof jcheckbox getsource isselected return returns the save config public sample save configuration get save config return save config saveconfig samplesaveconfiguration getsaveconfig saveconfig param save config the save config to set public void set save config sample save configuration save config this save config save config saveconfig saveconfig setsaveconfig samplesaveconfiguration saveconfig saveconfig saveconfig public monitor accum model server list map new hash map string list listeners new linked list monitor listener monitoraccummodel serverlistmap hashmap linkedlist monitorlistener public int get buffer size return default buffer size getbuffersize defaultbuffersize public void set buffer size int buffer default buffer size buffer setbuffersize defaultbuffersize public void set prefix string prefix connector prefix prefix setprefix connectorprefix added this method we that we can save the calculated stats return current sample public monitor model get last sample return this current monitormodel getlastsample method will look up the server in the map the monitor model will be added to an existing list or a new one will be created param model public void add sample monitor model model this current model if server list map contains key model geturl list newlist update array model list server list map get model geturl server list map put model geturl newlist else list samples collections synchronized list new linked list samples add model server list map put model geturl samples monitormodel addsample monitormodel serverlistmap containskey updatearray serverlistmap serverlistmap synchronizedlist linkedlist serverlistmap we want to keep only 240 entries for each server so we handle the object array ourselves param model private list update array monitor model model list list if list size default buffer size list add model else list add model list remove 0 return list updatearray monitormodel defaultbuffersize get all monitor models matching the url param url return list public list get all samples string url if server list map contains key url return collections synchronized list new linked list else return list server list map get url monitormodels getallsamples serverlistmap containskey synchronizedlist linkedlist serverlistmap get the monitor model matching the url param url return list public monitor model get sample string url if server list map contains key url array list list array list server list map get url return monitor model list get 0 else return null monitormodel monitormodel getsample serverlistmap containskey arraylist arraylist serverlistmap monitormodel method will try to parse the response data if the request was a monitor request but the response was incomplete bad or the server refused the connection we will set the server s health to dead if the request was not a monitor sample the method will ignore it param sample public void add sample sample result sample url surl null if sample instanceof http sample result surl http sample result sample geturl string rescontent new string sample get response data if sample is response codeok http sample result sample is monitor object factory of object factory get instance status st of parse bytes sample get response data st set connector prefix connector prefix if surl null surl can be null if read from a file monitor stats stat new monitor stats stats calculate status st stats calculate load st 0 stats calculate memory load st stats calculate thread load st surl get host string value of surl get port surl get protocol system current time millis monitor model mo new monitor model stat this add sample mo notify listeners mo else no response surl else if http sample result sample is monitor no response surl addsample sampleresult httpsampleresult httpsampleresult getresponsedata isresponsecodeok httpsampleresult ismonitor objectfactory objectfactory getinstance parsebytes getresponsedata setconnectorprefix connectorprefix monitorstats monitorstats calculatestatus calculateload calculatememoryload calculatethreadload gethost valueof getport getprotocol currenttimemillis monitormodel monitormodel addsample notifylisteners noresponse httpsampleresult ismonitor noresponse if there is no response from the server we create a new monitor stats object with the current timestamp and health dead param url public void no response url url notify listeners create new monitor model url monitorstats noresponse notifylisteners createnewmonitormodel method will return a new monitor model object with the given url this is used when the server fails to respond fully or is dead param url return new monitor model public monitor model create new monitor model url url monitor stats stat new monitor stats stats dead 0 0 0 0 url get host string value of url get port url get protocol system current time millis monitor model mo new monitor model stat return mo monitormodel monitormodel monitormodel createnewmonitormodel monitorstats monitorstats gethost valueof getport getprotocol currenttimemillis monitormodel monitormodel clears everything except the listener do not clear the listeners if we clear listeners subsequent run will not notify the gui of data changes public void clear data iterator itr this server list map key set iterator while itr has next list lt list this server list map get itr next lt clear this server list map clear cleardata serverlistmap keyset hasnext serverlistmap serverlistmap notify the listeners with the monitor model object param model public void notify listeners monitor model model for int idx 0 idx listeners size idx monitor listener ml monitor listener listeners get idx ml add sample model monitormodel notifylisteners monitormodel monitorlistener monitorlistener addsample add a listener when samples are added the class will notify the listener of the change param listener public void add listener monitor listener listener listeners add listener addlistener monitorlistener private j check box per user field public counter config gui super init jcheckbox peruserfield counterconfiggui public string get label resource return counter config title non nls 1 getlabelresource counter_config_title see org apache jmeter gui j metergui component create test element public test element create test element counter config config new counter config modify test element config return config jmeterguicomponent createtestelement testelement createtestelement counterconfig counterconfig modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element c if c instanceof counter config counter config config counter config c config set start start field get text bug 22820 if end field get text length 0 config set end end field get text config set increment incr field get text config set var name var name field get text config set format format field get text config set is per user per user field is selected super configure test element c testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement counterconfig counterconfig counterconfig setstart startfield gettext endfield gettext setend endfield gettext setincrement incrfield gettext setvarname varnamefield gettext setformat formatfield gettext setisperuser peruserfield isselected configuretestelement implements j metergui component clear gui public void clear gui super clear gui start field set text non nls 1 incr field set text non nls 1 end field set text non nls 1 var name field set text non nls 1 format field set text non nls 1 per user field set selected false jmeterguicomponent cleargui cleargui cleargui startfield settext incrfield settext endfield settext varnamefield settext formatfield settext peruserfield setselected public void configure test element element super configure element counter config config counter config element start field set text config get start as string end field set text config get end as string incr field set text config get increment as string format field set text config get format var name field set text config get var name per user field set selected config is per user testelement counterconfig counterconfig startfield settext getstartasstring endfield settext getendasstring incrfield settext getincrementasstring formatfield settext getformat varnamefield settext getvarname peruserfield setselected isperuser private void init set border make border set layout new vertical layout 5 vertical layout both start field new j labeled text field j meter utils get res string start non nls 1 incr field new j labeled text field j meter utils get res string increment non nls 1 end field new j labeled text field j meter utils get res string max non nls 1 var name field new j labeled text field j meter utils get res string var name non nls 1 format field new j labeled text field j meter utils get res string format non nls 1 per user field new j check box j meter utils get res string counter per user non nls 1 add make title panel add start field add incr field add end field add format field add var name field add per user field setborder makeborder setlayout verticallayout verticallayout startfield jlabeledtextfield jmeterutils getresstring incrfield jlabeledtextfield jmeterutils getresstring endfield jlabeledtextfield jmeterutils getresstring varnamefield jlabeledtextfield jmeterutils getresstring var_name formatfield jlabeledtextfield jmeterutils getresstring peruserfield jcheckbox jmeterutils getresstring counter_per_user maketitlepanel startfield incrfield endfield formatfield varnamefield peruserfield private void init per thead number new thread local protected synchronized object initial value return new long get start pertheadnumber threadlocal initialvalue getstart private void init per thead number new thread local protected synchronized object initial value return new long get start pertheadnumber threadlocal initialvalue getstart public counter config super init counterconfig private object read resolve init return this readresolve see loop iteration listener iteration start loop iteration event public synchronized void iteration start loop iteration event event cannot use get thread context as not cloned per thread j meter variables variables j meter context service get context get variables long start get start end get end increment get increment if is per user if global counter long min value global counter end global counter start variables put get var name format number global counter global counter increment else long current long per thead number get long value variables put get var name format number current current increment if current end current start per thead number set new long current loopiterationlistener iterationstart loopiterationevent iterationstart loopiterationevent getthreadcontext jmetervariables jmetercontextservice getcontext getvariables getstart getend getincrement isperuser globalcounter min_value globalcounter globalcounter getvarname formatnumber globalcounter globalcounter pertheadnumber longvalue getvarname formatnumber pertheadnumber use format to create number if it fails use the default private string format number long value string format get format if format null format length 0 try decimal format my formatter new decimal format format return my formatter format value catch number format exception ignored catch illegal argument exception ignored return long to string value formatnumber getformat decimalformat myformatter decimalformat myformatter numberformatexception illegalargumentexception tostring public void set start long start set property new long property start start setstart setproperty longproperty public void set start string start set property start start setstart setproperty public long get start return get property as long start getstart getpropertyaslong public string get start as string return get property as string start getstartasstring getpropertyasstring public void set end long end set property new long property end end setend setproperty longproperty public void set end string end set property end end setend setproperty return counter upper limit default long max value public long get end long property as long get property as long end if property as long 0 equals get property end get string value property as long long max value return property as long max_value getend propertyaslong getpropertyaslong propertyaslong getproperty getstringvalue propertyaslong max_value propertyaslong public string get end as string return get property as string end getendasstring getpropertyasstring public void set increment long inc set property new long property increment inc setincrement setproperty longproperty public void set increment string incr set property increment incr setincrement setproperty public long get increment return get property as long increment getincrement getpropertyaslong public string get increment as string return get property as string increment getincrementasstring getpropertyasstring public void set is per user boolean is per set property new boolean property per user is per setisperuser isper setproperty booleanproperty per_user isper public boolean is per user return get property as boolean per user isperuser getpropertyasboolean per_user public void set var name string name set property var name name setvarname setproperty var_name public string get var name return get property as string var name getvarname getpropertyasstring var_name public void set format string format set property format format setformat setproperty public string get format return get property as string format getformat getpropertyasstring param arg0 public bar chart test string arg0 super arg0 barcharttest public void test generate bar chart log info jtl version j meter utils get property file format testlog string sample log c eclipse3 workspace jmeter 21 bin testfiles sample log1 jtl string sample log testfiles sample log1 jtl string sample log2 testfiles sample log1b jtl string sample log3 testfiles sample log1c jtl jtl data input new jtl data jtl data input2 new jtl data jtl data input3 new jtl data input set data source sample log input load data input2 set data source sample log2 input2 load data input3 set data source sample log3 input3 load data assert true input get start timestamp 0 assert true input get end timestamp input get start timestamp assert true input getur ls size 0 log info url count input getur ls size java util array list list new java util array list list add input list add input2 list add input3 bar chart bchart new bar chart bchart set title sample chart bchart set caption sample bchart set name sample bchart sety axis milliseconds bchart sety label test runs bchart setx axis abstract table report table 90 percent bchart setx label abstract chart x data date label bchart seturl jakarta home j component gr bchart render chart list assert not null gr save graphics service serv new save graphics service string filename bchart get title filename filename replace if true equals ignore case system get property java awt headless serv savej component testfiles filename save graphics service png gr testgeneratebarchart jmeterutils getproperty file_format samplelog sample_log1 samplelog sample_log1 samplelog2 sample_log1b samplelog3 sample_log1c jtldata jtldata jtldata jtldata jtldata jtldata setdatasource samplelog loaddata setdatasource samplelog2 loaddata setdatasource samplelog3 loaddata asserttrue getstarttimestamp asserttrue getendtimestamp getstarttimestamp asserttrue geturls geturls arraylist arraylist barchart barchart settitle setcaption setname setyaxis setylabel setxaxis abstracttable report_table_90_percent setxlabel abstractchart x_data_date_label jakarta_home jcomponent renderchart assertnotnull savegraphicsservice savegraphicsservice gettitle _ equalsignorecase getproperty savejcomponent savegraphicsservice public class debug sampler bean info extends bean info support public debug sampler bean info super debug sampler class property descriptor p p property displayj meter variables p set value not undefined boolean true p set value not expression boolean true p set value not other boolean true p set value default boolean true p property displayj meter properties p set value not undefined boolean true p set value not expression boolean true p set value not other boolean true p set value default boolean false p property display system properties p set value not undefined boolean true p set value not expression boolean true p set value not other boolean true p set value default boolean false debugsamplerbeaninfo beaninfosupport debugsamplerbeaninfo debugsampler propertydescriptor displayjmetervariables setvalue not_undefined setvalue not_expression setvalue not_other setvalue displayjmeterproperties setvalue not_undefined setvalue not_expression setvalue not_other setvalue displaysystemproperties setvalue not_undefined setvalue not_expression setvalue not_other setvalue deprecated only for use in unit testing public monitor performance panel log warn only for use in unit testing monitorperformancepanel public monitor performance panel monitor accum model model monitor graph graph super this servermap new hash map this model model this model add listener this this graph graph init monitorperformancepanel monitoraccummodel monitorgraph hashmap addlistener init will create all the necessary swing panels labels and icons for the performance panel private void init called from ctor so must not be overridable rootsample new sample result rootsample set sample label server title rootsample set successful true rootnode new default mutable tree node rootsample treemodel new default tree model rootnode servertree new j tree treemodel servertree get selection model set selection mode tree selection model single tree selection servertree add tree selection listener this servertree set shows root handles true treepane new j scroll pane servertree treepane set preferred size new dimension 150 200 this add treepane j split pane left this set divider location 0 18 j panel right new j panel right set layout new border layout j label title new j label perf title title set preferred size new dimension 200 40 graphpanel new j panel graphpanel set layout new border layout graphpanel set maximum size new dimension model get buffer size model get buffer size graphpanel set background color white graphpanel add graph border layout center right add graphpanel border layout center right add title border layout north right add create legend border layout south right add create left grid labels border layout west right add create right grid labels border layout east this add right j split pane right sampleresult setsamplelabel server_title setsuccessful defaultmutabletreenode defaulttreemodel jtree getselectionmodel setselectionmode treeselectionmodel single_tree_selection addtreeselectionlistener setshowsroothandles jscrollpane setpreferredsize jsplitpane setdividerlocation jpanel jpanel setlayout borderlayout jlabel jlabel perf_title setpreferredsize jpanel setlayout borderlayout setmaximumsize getbuffersize getbuffersize setbackground borderlayout borderlayout borderlayout createlegend borderlayout createleftgridlabels borderlayout createrightgridlabels borderlayout jsplitpane method will create the legends at the bottom of the performance tab explaining the meaning of each line return j panel private j panel create legend dimension lsize new dimension 130 18 j panel legend new j panel legend set layout new flow layout j label load new j label legend load load set font plaintext load set preferred size lsize load set icon legend load icon legend add load j label mem new j label legend mem mem set font plaintext mem set preferred size lsize mem set icon legend mem icon legend add mem j label thd new j label legend thread thd set font plaintext thd set preferred size lsize thd set icon legend thread icon legend add thd j label health new j label legend health health set font plaintext health set preferred size lsize health set icon legend health icon legend add health return legend jpanel jpanel createlegend jpanel jpanel setlayout flowlayout jlabel jlabel legend_load setfont setpreferredsize seticon legend_load_icon jlabel jlabel legend_mem setfont setpreferredsize seticon legend_mem_icon jlabel jlabel legend_thread setfont setpreferredsize seticon legend_thread_icon jlabel jlabel legend_health setfont setpreferredsize seticon legend_health_icon method is responsible for creating the left grid labels return j panel private j panel create left grid labels dimension lsize new dimension 33 20 j panel labels new j panel labels set layout new border layout j label top new j label grid label top top set font plaintext top set preferred size lsize labels add top border layout north j label mid new j label grid label middle mid set font plaintext mid set preferred size lsize labels add mid border layout center j label bottom new j label grid label bottom bottom set font plaintext bottom set preferred size lsize labels add bottom border layout south return labels jpanel jpanel createleftgridlabels jpanel jpanel setlayout borderlayout jlabel jlabel grid_label_top setfont setpreferredsize borderlayout jlabel jlabel grid_label_middle setfont setpreferredsize borderlayout jlabel jlabel grid_label_bottom setfont setpreferredsize borderlayout method is responsible for creating the grid labels on the right for healthy and dead return j panel private j panel create right grid labels j panel labels new j panel labels set layout new border layout labels set preferred size new dimension 40 graphpanel get width 100 dimension lsize new dimension 40 20 j label h new j label grid label healthy h set font plaintext h set preferred size lsize labels add h border layout north j label d new j label grid label dead d set font plaintext d set preferred size lsize labels add d border layout south return labels jpanel jpanel createrightgridlabels jpanel jpanel setlayout borderlayout setpreferredsize getwidth jlabel jlabel grid_label_healthy setfont setpreferredsize borderlayout jlabel jlabel grid_label_dead setfont setpreferredsize borderlayout monitor accum model will call this method to notify the component data has changed public synchronized void add sample monitor model model if servermap contains key model geturl default mutable tree node newnode new default mutable tree node model newnode set allows children false servermap put model geturl newnode rootnode add newnode this treepane updateui default mutable tree node node default mutable tree node servertree get last selected path component if node null object usrobj node get user object if usrobj instanceof monitor model graph update gui monitor model usrobj monitoraccummodel addsample monitormodel containskey defaultmutabletreenode defaultmutabletreenode setallowschildren defaultmutabletreenode defaultmutabletreenode getlastselectedpathcomponent getuserobject monitormodel updategui monitormodel when the user selects a different node in the tree we get the selected node from the node we get the user object used to create the treenode in the constructor public void value changed tree selection event e we check to see if the last selected path is null after we clear it would return null if servertree get last selected path component null default mutable tree node node default mutable tree node servertree get last selected path component object usrobj node get user object if usrobj null usrobj instanceof monitor model monitor model mo monitor model usrobj graph update gui mo this updateui treepane updateui userobject valuechanged treeselectionevent lastselectedpath getlastselectedpathcomponent defaultmutabletreenode defaultmutabletreenode getlastselectedpathcomponent getuserobject monitormodel monitormodel monitormodel updategui clear will remove all child nodes from the rootnode clear the hash map update the graph and jpanel for the server tree public void clear data this servermap clear rootnode remove all children servertree updateui graph clear data hashmap cleardata removeallchildren cleardata protected password editor super text field new j password field text field add action listener this text field add focus listener this passwordeditor textfield jpasswordfield textfield addactionlistener textfield addfocuslistener public string get as text return new string text field get password getastext textfield getpassword public void set as text string value initial value value text field set text value setastext initialvalue textfield settext public object get value return get as text getvalue getastext public void set value object value if value instanceof string set as text string value else throw new illegal argument exception setvalue setastext illegalargumentexception see java beans property editor get custom editor public component get custom editor return text field propertyeditor getcustomeditor getcustomeditor textfield public boolean supports custom editor return true supportscustomeditor public void fire property change string new value get as text if initial value equals new value return initial value new value super fire property change firepropertychange newvalue getastext initialvalue newvalue initialvalue newvalue firepropertychange see java awt event action listener action performed java awt event action event public void action performed action event e fire property change actionlistener actionperformed actionevent actionperformed actionevent firepropertychange see java awt event focus listener focus gained java awt event focus event public void focus gained focus event e focuslistener focusgained focusevent focusgained focusevent see java awt event focus listener focus lost java awt event focus event public void focus lost focus event e fire property change focuslistener focuslost focusevent focuslost focusevent firepropertychange public thread group gui super init init gui threadgroupgui initgui public collection get menu categories return null getmenucategories public test element create test element thread group tg new thread group modify test element tg return tg testelement createtestelement threadgroup threadgroup modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element tg super configure test element tg if tg instanceof thread group thread group tg set sampler controller loop controller loop panel create test element tg set property thread group num threads thread input get text tg set property thread group ramp time ramp input get text tg set property new long property thread group start time start get date get time tg set property new long property thread group end time end get date get time tg set property new boolean property thread group scheduler scheduler is selected tg set property new string property thread group on sample error on sample error tg set property thread group duration duration get text tg set property thread group delay delay get text testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement threadgroup threadgroup setsamplercontroller loopcontroller looppanel createtestelement setproperty threadgroup num_threads threadinput gettext setproperty threadgroup ramp_time rampinput gettext setproperty longproperty threadgroup start_time getdate gettime setproperty longproperty threadgroup end_time getdate gettime setproperty booleanproperty threadgroup isselected setproperty stringproperty threadgroup on_sample_error onsampleerror setproperty threadgroup gettext setproperty threadgroup gettext private void set sample error boxes thread group te if te get on error stop test stop test box set selected true else if te get on error stop test now stop test now box set selected true else if te get on error stop thread stop thrd box set selected true else continue box set selected true setsampleerrorboxes threadgroup getonerrorstoptest stoptestbox setselected getonerrorstoptestnow stoptestnowbox setselected getonerrorstopthread stopthrdbox setselected continuebox setselected private string on sample error if stop test box is selected return thread group on sample error stoptest if stop test now box is selected return thread group on sample error stoptest now if stop thrd box is selected return thread group on sample error stopthread defaults to continue return thread group on sample error continue onsampleerror stoptestbox isselected threadgroup on_sample_error_stoptest stoptestnowbox isselected threadgroup on_sample_error_stoptest_now stopthrdbox isselected threadgroup on_sample_error_stopthread threadgroup on_sample_error_continue public void configure test element tg super configure tg thread input set text tg get property as string thread group num threads ramp input set text tg get property as string thread group ramp time loop panel configure test element tg get property thread group main controller get object value scheduler set selected tg get property as boolean thread group scheduler if scheduler is selected main panel set visible true else main panel set visible false check if the property exists string s tg get property as string thread group start time if s length 0 must be an old test plan start set date new date end set date new date else start set date new date tg get property as long thread group start time end set date new date tg get property as long thread group end time duration set text tg get property as string thread group duration delay set text tg get property as string thread group delay set sample error boxes thread group tg testelement threadinput settext getpropertyasstring threadgroup num_threads rampinput settext getpropertyasstring threadgroup ramp_time looppanel testelement getproperty threadgroup main_controller getobjectvalue setselected getpropertyasboolean threadgroup isselected mainpanel setvisible mainpanel setvisible getpropertyasstring threadgroup start_time setdate setdate setdate getpropertyaslong threadgroup start_time setdate getpropertyaslong threadgroup end_time settext getpropertyasstring threadgroup settext getpropertyasstring threadgroup setsampleerrorboxes threadgroup public void item state changed item event ie if ie get item equals scheduler if scheduler is selected main panel set visible true else main panel set visible false itemstatechanged itemevent getitem isselected mainpanel setvisible mainpanel setvisible public j popup menu create popup menu j popup menu pop new j popup menu pop add menu factory make menus new string menu factory controllers menu factory config elements menu factory timers menu factory pre processors menu factory samplers menu factory post processors menu factory assertions menu factory listeners j meter utils get res string add non nls 1 action names add menu factory add edit menu pop true menu factory add file menu pop return pop jpopupmenu createpopupmenu jpopupmenu jpopupmenu menufactory makemenus menufactory menufactory config_elements menufactory menufactory pre_processors menufactory menufactory post_processors menufactory menufactory jmeterutils getresstring actionnames menufactory addeditmenu menufactory addfilemenu private j panel create controller panel loop panel new loop control panel false loop controller looper loop controller loop panel create test element looper set loops 1 loop panel configure looper return loop panel jpanel createcontrollerpanel looppanel loopcontrolpanel loopcontroller loopcontroller looppanel createtestelement setloops looppanel looppanel create a panel containing the start time field and corresponding label return a gui panel containing the start time field private j panel create start time panel j panel panel new j panel new border layout 5 0 j label label new j label j meter utils get res string starttime non nls 1 panel add label border layout west start new j date field panel add start border layout center return panel starttime starttime jpanel createstarttimepanel jpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring borderlayout jdatefield borderlayout create a panel containing the end time field and corresponding label return a gui panel containing the end time field private j panel create end time panel j panel panel new j panel new border layout 5 0 j label label new j label j meter utils get res string endtime non nls 1 panel add label border layout west end new j date field panel add end border layout center return panel endtime endtime jpanel createendtimepanel jpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring borderlayout jdatefield borderlayout create a panel containing the duration field and corresponding label return a gui panel containing the duration field private j panel create duration panel j panel panel new j panel new border layout 5 0 j label label new j label j meter utils get res string duration non nls 1 panel add label border layout west duration new j text field panel add duration border layout center return panel jpanel createdurationpanel jpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring borderlayout jtextfield borderlayout create a panel containing the duration field and corresponding label return a gui panel containing the duration field private j panel create delay panel j panel panel new j panel new border layout 5 0 j label label new j label j meter utils get res string delay non nls 1 panel add label border layout west delay new j text field panel add delay border layout center return panel jpanel createdelaypanel jpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring borderlayout jtextfield borderlayout public string get label resource return threadgroup non nls 1 getlabelresource private j panel create on error panel j panel panel new j panel panel set border border factory create titled border j meter utils get res string sampler on error action non nls 1 button group group new button group continue box new j radio button j meter utils get res string sampler on error continue non nls 1 group add continue box panel add continue box stop thrd box new j radio button j meter utils get res string sampler on error stop thread non nls 1 group add stop thrd box panel add stop thrd box stop test box new j radio button j meter utils get res string sampler on error stop test non nls 1 group add stop test box panel add stop test box stop test now box new j radio button j meter utils get res string sampler on error stop test now non nls 1 group add stop test now box panel add stop test now box return panel jpanel createonerrorpanel jpanel jpanel setborder borderfactory createtitledborder jmeterutils getresstring sampler_on_error_action buttongroup buttongroup continuebox jradiobutton jmeterutils getresstring sampler_on_error_continue continuebox continuebox stopthrdbox jradiobutton jmeterutils getresstring sampler_on_error_stop_thread stopthrdbox stopthrdbox stoptestbox jradiobutton jmeterutils getresstring sampler_on_error_stop_test stoptestbox stoptestbox stoptestnowbox jradiobutton jmeterutils getresstring sampler_on_error_stop_test_now stoptestnowbox stoptestnowbox public void clear gui super clear gui init gui cleargui cleargui initgui initialise the gui field values private void init gui thread input set text 1 non nls 1 ramp input set text 1 non nls 1 continue box set selected true loop panel clear gui scheduler set selected false date today new date end set date today start set date today delay set text non nls 1 duration set text non nls 1 initgui threadinput settext rampinput settext continuebox setselected looppanel cleargui setselected setdate setdate settext settext private void init set layout new border layout 0 5 set border make border box box box create vertical box box add make title panel box add create on error panel add box border layout north j panel main panel new j panel new border layout thread properties vertical panel thread props panel new vertical panel thread props panel set border border factory create titled border border factory create etched border j meter utils get res string thread properties non nls 1 number of threads j panel thread panel new j panel new border layout 5 0 j label thread label new j label j meter utils get res string number of threads non nls 1 thread panel add thread label border layout west thread input new j text field 5 thread input set name thread name thread label set label for thread input thread panel add thread input border layout center thread props panel add thread panel new focus requester thread input ramp up j panel ramp panel new j panel new border layout 5 0 j label ramp label new j label j meter utils get res string ramp up non nls 1 ramp panel add ramp label border layout west ramp input new j text field 5 ramp input set name ramp name ramp label set label for ramp input ramp panel add ramp input border layout center thread props panel add ramp panel loop count thread props panel add create controller panel main panel add thread props panel border layout north add main panel border layout center scheduler new j check box j meter utils get res string scheduler non nls 1 scheduler add item listener this thread props panel add scheduler main panel new vertical panel main panel set border border factory create titled border border factory create etched border j meter utils get res string scheduler configuration non nls 1 main panel add create start time panel main panel add create end time panel main panel add create duration panel main panel add create delay panel main panel set visible false vertical panel intgration panel new vertical panel intgration panel add thread props panel intgration panel add main panel add intgration panel border layout center setlayout borderlayout setborder makeborder createverticalbox maketitlepanel createonerrorpanel borderlayout jpanel mainpanel jpanel borderlayout verticalpanel threadpropspanel verticalpanel threadpropspanel setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring thread_properties jpanel threadpanel jpanel borderlayout jlabel threadlabel jlabel jmeterutils getresstring number_of_threads threadpanel threadlabel borderlayout threadinput jtextfield threadinput setname thread_name threadlabel setlabelfor threadinput threadpanel threadinput borderlayout threadpropspanel threadpanel focusrequester threadinput jpanel ramppanel jpanel borderlayout jlabel ramplabel jlabel jmeterutils getresstring ramp_up ramppanel ramplabel borderlayout rampinput jtextfield rampinput setname ramp_name ramplabel setlabelfor rampinput ramppanel rampinput borderlayout threadpropspanel ramppanel threadpropspanel createcontrollerpanel mainpanel threadpropspanel borderlayout mainpanel borderlayout jcheckbox jmeterutils getresstring additemlistener threadpropspanel mainpanel verticalpanel mainpanel setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring scheduler_configuration mainpanel createstarttimepanel mainpanel createendtimepanel mainpanel createdurationpanel mainpanel createdelaypanel mainpanel setvisible verticalpanel intgrationpanel verticalpanel intgrationpanel threadpropspanel intgrationpanel mainpanel intgrationpanel borderlayout public void set node j meter tree node node get name panel set node node setnode jmetertreenode getnamepanel setnode public dimension get preferred size return get minimum size getpreferredsize getminimumsize public sample result sample entry e if wait 0 try thread sleep wait catch interrupted exception e1 ignore samples return null sampleresult interruptedexception public test sampler string name long wait set name name this wait wait testsampler setname public test sampler string name set name name testsampler setname public test sampler testsampler public string to string return get name tostring getname public long get samples return samples getsamples private final static string duration action processor duration non nls 1 public test action super actionprocessor testaction public sample result sample entry e j meter context context j meter context service get context int target get target int action get action if action pause pause get duration as string else if action stop action stop now if target thread log info stopping current thread context get thread stop not yet implemented else if target thread group else if target test if action stop now log info stopping all threads now context get engine stop test else log info stopping all threads context get engine ask threads to stop return null this means no sample is saved sampleresult jmetercontext jmetercontextservice getcontext gettarget getaction getdurationasstring stop_now getthread thread_group stop_now getengine stoptest getengine askthreadstostop private void pause string mili s int milis try milis integer parse int mili s catch number format exception e log warn could not create number from mili s milis 0 try thread sleep milis catch interrupted exception e mili_s parseint mili_s numberformatexception mili_s interruptedexception public void set target int target set property new integer property target target settarget setproperty integerproperty public int get target return get property as int target gettarget getpropertyasint public void set action int action set property new integer property action action setaction setproperty integerproperty public int get action return get property as int action getaction getpropertyasint public void set duration string duration set property new string property duration duration setduration setproperty stringproperty public string get duration as string return get property as string duration getdurationasstring getpropertyasstring no arg constructor public gaussian random timer gui init gaussianrandomtimergui handle an error param e the exception that was thrown param thrower the j component that threw the exception public static void error exception e j component thrower j option pane show message dialog thrower e error j option pane error message jcomponent jcomponent joptionpane showmessagedialog joptionpane error_message create the test element underlying this gui component see org apache jmeter gui j metergui component create test element public test element create test element random timer timer new gaussian random timer modify test element timer return timer jmeterguicomponent createtestelement testelement createtestelement randomtimer gaussianrandomtimer modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element timer this configure test element timer random timer timer set delay delay field get text random timer timer set range range field get text testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement randomtimer setdelay delayfield gettext randomtimer setrange rangefield gettext configure this gui component from the underlying test element see org apache jmeter gui j metergui component configure test element public void configure test element el super configure el delay field set text el get property as string random timer delay range field set text el get property as string random timer range testelement jmeterguicomponent testelement testelement delayfield settext getpropertyasstring randomtimer rangefield settext getpropertyasstring randomtimer public string get label resource return gaussian timer title non nls 1 getlabelresource gaussian_timer_title initialize this component private void init set layout new vertical layout 5 vertical layout both set border make border add make title panel j panel thread delay props panel new j panel thread delay props panel set layout new vertical layout 5 vertical layout left thread delay props panel set border border factory create titled border j meter utils get res string thread delay properties non nls 1 delay deviation box delay dev panel box create horizontal box delay dev panel add new j label j meter utils get res string gaussian timer range non nls 1 delay dev panel add box create horizontal strut 5 range field new j text field 6 range field set text default range range field set name range field delay dev panel add range field thread delay props panel add delay dev panel avg delay box avg delay panel box create horizontal box avg delay panel add new j label j meter utils get res string gaussian timer delay non nls 1 avg delay panel add box create horizontal strut 5 delay field new j text field 6 delay field set text default delay delay field set name delay field avg delay panel add delay field thread delay props panel add avg delay panel thread delay props panel set maximum size new dimension thread delay props panel get maximum size width thread delay props panel get preferred size height add thread delay props panel set the initial focus to the delay field new focus requester range field setlayout verticallayout verticallayout setborder makeborder maketitlepanel jpanel threaddelaypropspanel jpanel threaddelaypropspanel setlayout verticallayout verticallayout threaddelaypropspanel setborder borderfactory createtitledborder jmeterutils getresstring thread_delay_properties delaydevpanel createhorizontalbox delaydevpanel jlabel jmeterutils getresstring gaussian_timer_range delaydevpanel createhorizontalstrut rangefield jtextfield rangefield settext default_range rangefield setname range_field delaydevpanel rangefield threaddelaypropspanel delaydevpanel avgdelaypanel createhorizontalbox avgdelaypanel jlabel jmeterutils getresstring gaussian_timer_delay avgdelaypanel createhorizontalstrut delayfield jtextfield delayfield settext default_delay delayfield setname delay_field avgdelaypanel delayfield threaddelaypropspanel avgdelaypanel threaddelaypropspanel setmaximumsize threaddelaypropspanel getmaximumsize threaddelaypropspanel getpreferredsize threaddelaypropspanel focusrequester rangefield public void clear gui range field set text default range delay field set text default delay super clear gui cleargui rangefield settext default_range delayfield settext default_delay cleargui j meter utils get res string report output directory public html report writer gui super init jmeterutils getresstring report_output_directory htmlreportwritergui public string get label resource return report writer html getlabelresource report_writer_html public j popup menu create popup menu j popup menu pop new j popup menu report menu factory add file menu pop report menu factory add edit menu pop true return pop jpopupmenu createpopupmenu jpopupmenu jpopupmenu reportmenufactory addfilemenu reportmenufactory addeditmenu init creates the necessary gui stuff private void init called from ctor so must not be overridable set layout new border layout 10 10 set border make border set background color white j panel pane new j panel pane set layout new border layout 10 10 pane set background color white pane add this get name panel border layout north output directory set background color white pane add output directory border layout south add pane border layout north setlayout borderlayout setborder makeborder setbackground jpanel jpanel setlayout borderlayout setbackground getnamepanel borderlayout outputdirectory setbackground outputdirectory borderlayout borderlayout public test element create test element html report writer element new html report writer modify test element element return element testelement createtestelement htmlreportwriter htmlreportwriter modifytestelement public void modify test element test element element this configure test element element html report writer wr html report writer element wr set target directory output directory get filename modifytestelement testelement configuretestelement htmlreportwriter htmlreportwriter settargetdirectory outputdirectory getfilename public void configure test element element super configure element html report writer wr html report writer element output directory set filename wr get target directory testelement htmlreportwriter htmlreportwriter outputdirectory setfilename gettargetdirectory deprecated only for use in unit testing public monitor health panel log warn only for use in unit testing model null monitorhealthpanel public monitor health panel monitor accum model model this model model this model add listener this init monitorhealthpanel monitoraccummodel addlistener init is responsible for creating the necessary legends and information for the health panel private void init called from ctor so must not be overridable this set layout new border layout image icon legend j meter utils get image monitor legend gif i18n contains fixed english text j label label new j label legend label set preferred size new dimension 550 25 this add label border layout north this servers new j panel this servers set layout new box layout servers box layout y axis this servers set alignmentx component left alignment server scroll pane new j scroll pane this servers server scroll pane set preferred size new dimension 300 300 this add server scroll pane border layout center the equations string eqstring1 info h info a string eqstring2 info w info d string eqstring3 info load j label eqs new j label eqs set layout new border layout eqs set preferred size new dimension 500 60 eqs add new j label eqstring1 border layout north eqs add new j label eqstring2 border layout center eqs add new j label eqstring3 border layout south this add eqs border layout south setlayout borderlayout imageicon jmeterutils getimage jlabel jlabel setpreferredsize borderlayout jpanel setlayout boxlayout boxlayout y_axis setalignmentx left_alignment serverscrollpane jscrollpane serverscrollpane setpreferredsize serverscrollpane borderlayout info_h info_a info_w info_d info_load jlabel jlabel setlayout borderlayout setpreferredsize jlabel borderlayout jlabel borderlayout jlabel borderlayout borderlayout param model public void add sample monitor model model if server panel map contains key model geturl server panel pane null if server panel map get model geturl null pane server panel server panel map get model geturl else pane new server panel model server panel map put model geturl pane pane update gui model else server panel newpane new server panel model server panel map put model geturl newpane this servers add newpane newpane update gui model this servers updateui addsample monitormodel serverpanelmap containskey serverpanel serverpanelmap serverpanel serverpanelmap serverpanel serverpanelmap updategui serverpanel serverpanel serverpanelmap updategui clear will clear the hashmap remove all server panels from the servers pane and update the ui public void clear data this server panel map clear this servers remove all this servers updateui serverpanels cleardata serverpanelmap removeall public sync timer bean info super sync timer class create property group grouping new string group size property descriptor p property group size p set value not undefined boolean true p set value default new integer 0 synctimerbeaninfo synctimer createpropertygroup groupsize propertydescriptor groupsize setvalue not_undefined setvalue public assertion result get result sample result response assertion result result new assertion result get name try bsf manager mgr get manager if mgr null result set failure true result set error true result set failure message bsf manager not found return result mgr declare bean sample result response sample result class mgr declare bean assertion result result assertion result class process file or script mgr mgr terminate result set error false catch bsf exception e log warn problem in bsf script e result set error true result set failure message e to string return result assertionresult getresult sampleresult assertionresult assertionresult getname bsfmanager getmanager setfailure seterror setfailuremessage declarebean sampleresult sampleresult declarebean assertionresult assertionresult processfileorscript seterror bsfexception seterror setfailuremessage tostring static only private class finder classfinder filter tree set class parents boolean inner string contains string not contains super this parents parents this inner inner this contains contains this not contains not contains filtertreeset notcontains notcontains notcontains override the superclass so we only add classnames that meet the criteria param o classname must be a string return true if it is a new entry see java util tree set add java lang object public boolean add object o if contains o return false no need to check it again string s string o we only expect strings if contains null s index of contains 1 return false it does not contain a required string if not contains null s index of not contains 1 return false it contains a banned string if s index of 1 inner non nls 1 if is child of parents s context class loader return super add s return false treeset indexof notcontains indexof notcontains indexof ischildof contextclassloader convenience method for code find classes that extend class boolean code with the option to include inner classes in the search set to false return list containing discovered classes public static list find classes that extend string paths class super classes throws io exception return find classes that extend paths super classes false findclassesthatextend findclassesthatextend superclasses ioexception findclassesthatextend superclasses for each directory in the search path add all the jars found there private static string add jars in path string paths set full list new hash set for int i 0 i paths length i final string path paths i full list add path keep the unexpanded path todo allow directories to end with jar by removing this check if path ends with dot jar file dir new file path if dir exists dir is directory string jars dir list new filename filter public boolean accept file f string name return name ends with dot jar for int x 0 x jars length x full list add jars x return string full list to array new string 0 addjarsinpath fulllist hashset fulllist endswith dot_jar isdirectory filenamefilter endswith dot_jar fulllist fulllist toarray if dir exists dir is directory string jars dir list new filename filter public boolean accept file f string name return name ends with dot jar isdirectory filenamefilter endswith dot_jar find classes in the provided path s jar s that extend the class es param str paths or jars pathnames or jarfiles to search for classes param super classes required parent class es param inner classes should we include inner classes return list containing discovered classes public static list find classes that extend string str paths or jars final class super classes final boolean inner classes throws io exception return find classes that extend str paths or jars super classes inner classes null null strpathsorjars superclasses innerclasses findclassesthatextend strpathsorjars superclasses innerclasses ioexception findclassesthatextend strpathsorjars superclasses innerclasses find classes in the provided path s jar s that extend the class es param str paths or jars pathnames or jarfiles to search for classes param super classes required parent class es param inner classes should we include inner classes param contains classname should contain this string param not contains classname should not contain this string return list containing discovered classes public static list find classes that extend string str paths or jars final class super classes final boolean inner classes string contains string not contains throws io exception if log is debug enabled for int i 0 i super classes length i log debug superclass super classes i get name find all jars in the search path str paths or jars add jars in path str paths or jars for int k 0 k str paths or jars length k str paths or jars k fix path entry str paths or jars k if log is debug enabled log debug str paths or jars str paths or jars k now eliminate any classpath entries that do not match the search list list paths get classpath matches str paths or jars if log is debug enabled iterator t iter list paths iterator while t iter has next log debug list paths t iter next set list classes new filter tree set super classes inner classes contains not contains first get all the classes find classes in paths list paths list classes if log is debug enabled log debug list classes size list classes size iterator t iter list classes iterator while t iter has next log debug list classes t iter next now keep only the required classes set sub class list find all subclasses super classes list classes inner classes if log is debug enabled log debug sub class list size sub class list size iterator t iter sub class list iterator while t iter has next log debug sub class list t iter next return new array list list classes sub class list strpathsorjars superclasses innerclasses notcontains findclassesthatextend strpathsorjars superclasses innerclasses notcontains ioexception isdebugenabled superclasses superclasses getname strpathsorjars addjarsinpath strpathsorjars strpathsorjars strpathsorjars fixpathentry strpathsorjars isdebugenabled strpathsorjars strpathsorjars listpaths getclasspathmatches strpathsorjars isdebugenabled titer listpaths titer hasnext listpaths titer listclasses filtertreeset superclasses innerclasses notcontains findclassesinpaths listpaths listclasses isdebugenabled listclasses listclasses titer listclasses titer hasnext listclasses titer subclasslist findallsubclasses superclasses listclasses innerclasses isdebugenabled subclasslist subclasslist titer subclasslist titer hasnext subclasslist titer arraylist listclasses subclasslist private static list get classpath matches string str paths or jars final string java class path system get property java class path non nls 1 string tokenizer st paths new string tokenizer java class path system get property path separator non nls 1 if log is debug enabled log debug classpath java class path for int i 0 i str paths or jars length i log debug str paths or jars i str paths or jars i find all jar files or paths that end with str path or jar array list list paths new array list string str path null while st paths has more tokens str path fix path entry st paths next token if str paths or jars null log debug adding str path list paths add str path else boolean found false for int i 0 i str paths or jars length i if str path ends with str paths or jars i found true log debug adding str path found at i list paths add str path break no need to look further if found log debug did not find str path return list paths getclasspathmatches strpathsorjars javaclasspath getproperty stringtokenizer stpaths stringtokenizer javaclasspath getproperty isdebugenabled javaclasspath strpathsorjars strpathsorjars strpathsorjars strpathorjar arraylist listpaths arraylist strpath stpaths hasmoretokens strpath fixpathentry stpaths nexttoken strpathsorjars strpath listpaths strpath strpathsorjars strpath endswith strpathsorjars strpath listpaths strpath strpath listpaths fix a path replace by current directory trim any trailing spaces replace by replace by remove all trailing private static string fix path entry string path if path null return null if path equals non nls 1 return system get property user dir non nls 1 path path trim replace non nls 1 non nls 2 path j orphan utils substitute path non nls 1 non nls 2 while path ends with non nls 1 path path substring 0 path length 1 return path fixpathentry getproperty jorphanutils endswith param parent classes list of classes to check for param str class name name of class to be checked param inner classes should we allow inner classes param context class loader the classloader to use return private static boolean is child of class parent classes string str class name class loader context class loader might throw an exception assume this is ignorable try class c class for name str class name false context class loader if c is interface modifier is abstract c get modifiers for int i 0 i parent classes length i if parent classes i is assignable from c return true catch throwable ignored log debug ignored get localized message return false parentclasses strclassname innerclasses contextclassloader ischildof parentclasses strclassname classloader contextclassloader forname strclassname contextclassloader isinterface isabstract getmodifiers parentclasses parentclasses isassignablefrom getlocalizedmessage private static string fix class name string str class name str class name str class name replace non nls 1 non nls 2 str class name str class name replace non nls 1 non nls 2 remove class str class name str class name substring 0 str class name length dot class len return str class name fixclassname strclassname strclassname strclassname strclassname strclassname strclassname strclassname strclassname dot_class_len strclassname private static void find classes in one path string str path set list classes throws io exception file file new file str path if file is directory find classes in paths dir str path file list classes else if file exists zip file zip file null try zip file new zip file file enumeration entries zip file entries while entries has more elements string str entry entries next element to string if str entry ends with dot class list classes add fix class name str entry catch io exception e log warn can not open the jar str path e get localized message finally if zip file null try zip file close catch exception e findclassesinonepath strpath listclasses ioexception strpath isdirectory findclassesinpathsdir strpath listclasses zipfile zipfile zipfile zipfile zipfile hasmoreelements strentry nextelement tostring strentry endswith dot_class listclasses fixclassname strentry ioexception strpath getlocalizedmessage zipfile zipfile private static void find classes in paths list list paths set list classes throws io exception iterator iter paths list paths iterator while iter paths has next find classes in one path string iter paths next list classes findclassesinpaths listpaths listclasses ioexception iterpaths listpaths iterpaths hasnext findclassesinonepath iterpaths listclasses private static void find classes in paths dir string str path element file dir set list classes throws io exception string list dir list for int i 0 i list length i file file new file dir list i if file is directory recursive call find classes in paths dir str path element file list classes else if list i ends with dot class file exists file length 0 final string path file get path list classes add path substring str path element length 1 path last index of non nls 1 replace file separator char at 0 non nls 1 findclassesinpathsdir strpathelement listclasses ioexception isdirectory findclassesinpathsdir strpathelement listclasses endswith dot_class getpath listclasses strpathelement lastindexof charat public sample result sample entry e sample result res new sample result res set sample label get name res sample start string buffer sb new string buffer 100 string buffer rd new string buffer 20 for request data if is displayj meter variables rd append j meter variables n sb append j meter variables n format set sb j meter context service get context get variables entry set sb append n if is displayj meter properties rd append j meter properties n sb append j meter properties n format set sb j meter utils getj meter properties entry set sb append n if is display system properties rd append system properties n sb append system properties n format set sb system get properties entry set sb append n res set response data sb to string get bytes res set data type sample result text res set sampler data rd to string res set successful true res sample end return res sampleresult sampleresult sampleresult setsamplelabel getname samplestart stringbuffer stringbuffer stringbuffer stringbuffer isdisplayjmetervariables jmetervariables jmetervariables formatset jmetercontextservice getcontext getvariables entryset isdisplayjmeterproperties jmeterproperties jmeterproperties formatset jmeterutils getjmeterproperties entryset isdisplaysystemproperties systemproperties systemproperties formatset getproperties entryset setresponsedata tostring getbytes setdatatype sampleresult setsamplerdata tostring setsuccessful sampleend private void format set string buffer sb set s array list al new array list s collections sort al new comparator public int compare object o1 object o2 string m1 m2 m1 string map entry o1 get key m2 string map entry o2 get key return m1 compare to m2 iterator i al iterator while i has next map entry me map entry i next sb append me get key sb append sb append me get value sb append n formatset stringbuffer arraylist arraylist getkey getkey compareto hasnext getkey getvalue collections sort al new comparator public int compare object o1 object o2 string m1 m2 m1 string map entry o1 get key m2 string map entry o2 get key return m1 compare to m2 getkey getkey compareto public boolean is displayj meter variables return displayj meter variables isdisplayjmetervariables displayjmetervariables public void set displayj meter variables boolean displayj meter variables this displayj meter variables displayj meter variables setdisplayjmetervariables displayjmetervariables displayjmetervariables displayjmetervariables public boolean is displayj meter properties return displayj meter properties isdisplayjmeterproperties displayjmeterproperties public void set displayj meter properties boolean displayj meter propterties this displayj meter properties displayj meter propterties setdisplayjmeterproperties displayjmeterpropterties displayjmeterproperties displayjmeterpropterties public boolean is display system properties return display system properties isdisplaysystemproperties displaysystemproperties public void set display system properties boolean display system properties this display system properties display system properties setdisplaysystemproperties displaysystemproperties displaysystemproperties displaysystemproperties private url rewriting modifier mod null public testurl rewriting modifier string name super name urlrewritingmodifier testurlrewritingmodifier public void set up context j meter context service get context mod new url rewriting modifier mod set thread context context setup jmetercontextservice getcontext urlrewritingmodifier setthreadcontext public void test nonhttp sampler throws exception sampler sampler new null sampler response new sample result context set current sampler sampler context set previous result response mod process testnonhttpsampler nullsampler sampleresult setcurrentsampler setpreviousresult public void test grab session id throws exception string html location http server com index html session id jfdkjdkf 20jddkfdfjkdjfdf 22 response new sample result response set response data html get bytes mod set argument name session id http sampler base sampler create sampler sampler add argument session id adfasdfdsafasdfasd context set current sampler sampler context set previous result response mod process arguments args sampler get arguments assert equals jfdkjdkf jddkfdfjkdjfdf argument args get arguments get 0 get object value get value assert equals http server com index html session id jfdkjdkf jddkfdfjkdjfdf 22 sampler to string testgrabsessionid session_id sampleresult setresponsedata getbytes setargumentname session_id httpsamplerbase createsampler addargument session_id setcurrentsampler setpreviousresult getarguments assertequals getarguments getobjectvalue getvalue assertequals session_id tostring public void test grab session id2 throws exception string html a href http server com index html session id jfdkjdkfjddkfdfjkdjfdf response new sample result response set response data html get bytes mod set argument name session id http sampler base sampler create sampler context set current sampler sampler context set previous result response mod process arguments args sampler get arguments assert equals jfdkjdkfjddkfdfjkdjfdf argument args get arguments get 0 get object value get value testgrabsessionid2 session_id sampleresult setresponsedata getbytes setargumentname session_id httpsamplerbase createsampler setcurrentsampler setpreviousresult getarguments assertequals getarguments getobjectvalue getvalue private http sampler base create sampler http sampler base sampler new http null sampler sampler set domain server com sampler set path index html sampler set method http sampler base get sampler set protocol http return sampler httpsamplerbase createsampler httpsamplerbase httpnullsampler setdomain setpath setmethod httpsamplerbase setprotocol public void test grab session id3 throws exception string html href index html session id jfdkjdkfjddkfdfjkdjfdf response new sample result response set response data html get bytes mod set argument name session id http sampler base sampler create sampler context set current sampler sampler context set previous result response mod process arguments args sampler get arguments assert equals jfdkjdkfjddkfdfjkdjfdf argument args get arguments get 0 get object value get value testgrabsessionid3 session_id sampleresult setresponsedata getbytes setargumentname session_id httpsamplerbase createsampler setcurrentsampler setpreviousresult getarguments assertequals getarguments getobjectvalue getvalue public void test grab session id ended in tab throws exception string html href index html session id jfdkjdkfjddkfdfjkdjfdf t response new sample result response set response data html get bytes mod set argument name session id http sampler base sampler create sampler context set current sampler sampler context set previous result response mod process arguments args sampler get arguments assert equals jfdkjdkfjddkfdfjkdjfdf argument args get arguments get 0 get object value get value testgrabsessionidendedintab session_id sampleresult setresponsedata getbytes setargumentname session_id httpsamplerbase createsampler setcurrentsampler setpreviousresult getarguments assertequals getarguments getobjectvalue getvalue public void test grab session id4 throws exception string html href index html 24sid 24kq nq3aaadq zoeq axlkx8uqv5bjqvb pbt response new sample result response set response data html get bytes mod set argument name 24sid 24 mod set path extension true mod set path extension no equals true http sampler base sampler create sampler context set current sampler sampler context set previous result response mod process arguments args sampler get arguments assert equals index html 24sid 24kq nq3aaadq zoeq axlkx8uqv5bjqvb pbt sampler get path testgrabsessionid4 24kqnq3aaadqzoeqaxlkx8uqv5bjqvbpbt sampleresult setresponsedata getbytes setargumentname setpathextension setpathextensionnoequals httpsamplerbase createsampler setcurrentsampler setpreviousresult getarguments assertequals 24kqnq3aaadqzoeqaxlkx8uqv5bjqvbpbt getpath public void test grab session id5 throws exception string html location http server com index html session 33 jfdkjdkf 20jddkfdfjkdjfdf 22 response new sample result response set response data html get bytes mod set argument name session 33 http sampler base sampler create sampler sampler add argument session 33 adfasdfdsafasdfasd context set current sampler sampler context set previous result response mod process arguments args sampler get arguments assert equals jfdkjdkf jddkfdfjkdjfdf argument args get arguments get 0 get object value get value assert equals http server com index html session 5b33 5d jfdkjdkf jddkfdfjkdjfdf 22 sampler to string testgrabsessionid5 sampleresult setresponsedata getbytes setargumentname httpsamplerbase createsampler addargument setcurrentsampler setpreviousresult getarguments assertequals getarguments getobjectvalue getvalue assertequals tostring public void test grab session id from form throws exception string html new string input name sid value my id input name sid value my id input value my id name sid input value my id name sid input blah blah value my id yoda yoda name sid input type hidden name sid value my id input type hidden name sid tvalue my id for int i 0 i html length i response new sample result response set response data html i get bytes url rewriting modifier new mod new url rewriting modifier new mod set thread context context new mod set argument name sid new mod set path extension false http sampler base sampler create sampler context set current sampler sampler context set previous result response new mod process arguments args sampler get arguments assert equals for case i i my id argument args get arguments get 0 get object value get value testgrabsessionidfromform myid myid myid myid myid myid myid sampleresult setresponsedata getbytes urlrewritingmodifier newmod urlrewritingmodifier newmod setthreadcontext newmod setargumentname newmod setpathextension httpsamplerbase createsampler setcurrentsampler setpreviousresult newmod getarguments assertequals myid getarguments getobjectvalue getvalue public void test grab session idur linjson throws exception string html a href onclick frame src index param1 bla sessionid xyzxyzxyz response new sample result response set response data html get bytes mod set argument name sessionid http sampler base sampler create sampler sampler add argument sessionid xyzxyzxyz context set current sampler sampler context set previous result response mod process arguments args sampler get arguments assert equals xyzxyzxyz argument args get arguments get 0 get object value get value testgrabsessionidurlinjson sampleresult setresponsedata getbytes setargumentname httpsamplerbase createsampler addargument setcurrentsampler setpreviousresult getarguments assertequals getarguments getobjectvalue getvalue public void test cache throws exception string html new string input name sid value my id html html no entry check it is still present url rewriting modifier new mod new url rewriting modifier new mod set should cache true new mod set thread context context new mod set argument name sid new mod set path extension false for int i 0 i html length i response new sample result response set response data html i get bytes http sampler base sampler create sampler context set current sampler sampler context set previous result response new mod process arguments args sampler get arguments assert equals for case i i my id argument args get arguments get 0 get object value get value testcache myid urlrewritingmodifier newmod urlrewritingmodifier newmod setshouldcache newmod setthreadcontext newmod setargumentname newmod setpathextension sampleresult setresponsedata getbytes httpsamplerbase createsampler setcurrentsampler setpreviousresult newmod getarguments assertequals myid getarguments getobjectvalue getvalue public void test no cache throws exception string html new string input name sid value my id my id html html url rewriting modifier new mod new url rewriting modifier new mod set thread context context new mod set argument name sid new mod set path extension false new mod set should cache false for int i 0 i html length 2 i response new sample result response set response data html i 2 get bytes http sampler base sampler create sampler context set current sampler sampler context set previous result response new mod process arguments args sampler get arguments assert equals for case i i html i 2 1 argument args get arguments get 0 get object value get value testnocache myid myid urlrewritingmodifier newmod urlrewritingmodifier newmod setthreadcontext newmod setargumentname newmod setpathextension newmod setshouldcache sampleresult setresponsedata getbytes httpsamplerbase createsampler setcurrentsampler setpreviousresult newmod getarguments assertequals getarguments getobjectvalue getvalue public class test auth manager extends j meter test case public test auth manager string name super name testauthmanager jmetertestcase testauthmanager public void test http throws exception assert true auth manager is supported protocol new url http testhttp asserttrue authmanager issupportedprotocol public void test https throws exception assert true auth manager is supported protocol new url https testhttps asserttrue authmanager issupportedprotocol public void test file throws exception auth manager am new auth manager collection property ao am get auth objects assert equals 0 ao size am add file testfiles test auth txt assert equals 9 ao size authorization at at am get auth forurl new url http a b c assert equals login at get user assert equals password at get pass at am get auth forurl new url http a b c 80 same as above assert equals login at get user assert equals password at get pass at am get auth forurl new url http a b c 443 not same assert null at at am get auth forurl new url http a b c 1 assert equals login1 at get user assert equals password1 at get pass assert equals at get domain assert equals at get realm at am get auth forurl new url http d e f assert equals user at get user assert equals pass at get pass assert equals domain at get domain assert equals realm at get realm at am get auth forurl new url https j k l assert equals jkl at get user assert equals pass at get pass at am get auth forurl new url https j k l 443 assert equals jkl at get user assert equals pass at get pass at am get auth forurl new url https l m n assert equals lmn443 at get user assert equals pass at get pass at am get auth forurl new url https l m n 443 assert equals lmn443 at get user assert equals pass at get pass at am get auth forurl new url https l m n 8443 assert equals lmn8443 at get user assert equals pass at get pass testfile authmanager authmanager collectionproperty getauthobjects assertequals addfile testauth assertequals getauthforurl assertequals getuser assertequals getpass getauthforurl assertequals getuser assertequals getpass getauthforurl assertnull getauthforurl assertequals getuser assertequals getpass assertequals getdomain assertequals getrealm getauthforurl assertequals getuser assertequals getpass assertequals getdomain assertequals getrealm getauthforurl assertequals getuser assertequals getpass getauthforurl assertequals getuser assertequals getpass getauthforurl assertequals getuser assertequals getpass getauthforurl assertequals getuser assertequals getpass getauthforurl assertequals getuser assertequals getpass create a new loop control panel as a standalone component public foreach control panel this true loopcontrolpanel foreachcontrolpanel create a new loop control panel as either a standalone or an embedded component param display name indicates whether or not this component should display its name if true this is a standalone component if false this component is intended to be used as a subpanel for another component public foreach control panel boolean display name this display name display name init loopcontrolpanel displayname foreachcontrolpanel displayname displayname displayname a newly created component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui param element the test element to configure public void configure test element element super configure element input val set text foreach controller element get input val string return val set text foreach controller element get return val string use separator set selected foreach controller element get use separator testelement testelement inputval settext foreachcontroller getinputvalstring returnval settext foreachcontroller getreturnvalstring useseparator setselected foreachcontroller getuseseparator implements j metergui component create test element public test element create test element foreach controller lc new foreach controller modify test element lc return lc jmeterguicomponent createtestelement testelement createtestelement foreachcontroller foreachcontroller modifytestelement implements j metergui component modify test element test element public void modify test element test element lc configure test element lc if lc instanceof foreach controller if input val get text length 0 foreach controller lc set input val input val get text else foreach controller lc set input val non nls 1 if return val get text length 0 foreach controller lc set return val return val get text else foreach controller lc set return val non nls 1 foreach controller lc set use separator use separator is selected jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement foreachcontroller inputval gettext foreachcontroller setinputval inputval gettext foreachcontroller setinputval returnval gettext foreachcontroller setreturnval returnval gettext foreachcontroller setreturnval foreachcontroller setuseseparator useseparator isselected implements j metergui component clear gui public void clear gui super clear gui input val set text non nls 1 return val set text non nls 1 use separator set selected true jmeterguicomponent cleargui cleargui cleargui inputval settext returnval settext useseparator setselected public string get label resource return foreach controller title non nls 1 getlabelresource foreach_controller_title initialize the gui components and layout for this component private void init the loop controller panel can be displayed standalone or inside another panel for standalone we want to display the title name etc everything however if we want to display it within another panel we just display the loop count fields not the title and name standalone if display name set layout new border layout 0 5 set border make border add make title panel border layout north j panel main panel new j panel new border layout main panel add create loop count panel border layout north add main panel border layout center else embedded set layout new border layout add create loop count panel border layout north displayname setlayout borderlayout setborder makeborder maketitlepanel borderlayout jpanel mainpanel jpanel borderlayout mainpanel createloopcountpanel borderlayout mainpanel borderlayout setlayout borderlayout createloopcountpanel borderlayout create a gui panel containing the components related to the number of loops which should be executed return a gui panel containing the loop count components private j panel create loop count panel j panel loop panel new j panel new border layout 5 0 vertical panel loop panel new vertical panel loop label j label input val label new j label j meter utils get res string foreach input non nls 1 j label return val label new j label j meter utils get res string foreach output non nls 1 text field j panel input val sub panel new j panel new border layout 5 0 input val new j text field 5 non nls 1 input val set name inputval input val label set label for input val input val sub panel add input val label border layout west input val sub panel add input val border layout center text field j panel return val sub panel new j panel new border layout 5 0 return val new j text field 5 non nls 1 return val set name returnval return val label set label for return val return val sub panel add return val label border layout west return val sub panel add return val border layout center checkbox use separator new j check box j meter utils get res string foreach use separator true non nls 1 loop panel add input val sub panel loop panel add return val sub panel loop panel add use separator return loop panel jpanel createloopcountpanel jpanel looppanel jpanel borderlayout verticalpanel looppanel verticalpanel jlabel inputvallabel jlabel jmeterutils getresstring foreach_input jlabel returnvallabel jlabel jmeterutils getresstring foreach_output jpanel inputvalsubpanel jpanel borderlayout inputval jtextfield inputval setname inputvallabel setlabelfor inputval inputvalsubpanel inputvallabel borderlayout inputvalsubpanel inputval borderlayout jpanel returnvalsubpanel jpanel borderlayout returnval jtextfield returnval setname returnvallabel setlabelfor returnval returnvalsubpanel returnvallabel borderlayout returnvalsubpanel returnval borderlayout useseparator jcheckbox jmeterutils getresstring foreach_use_separator looppanel inputvalsubpanel looppanel returnvalsubpanel looppanel useseparator looppanel public static final string mailer model mailer result collector mailer model non nls 1 public mailer result collector super set property new test element property mailer model new mailer model mailer_model mailerresultcollector mailer_model mailerresultcollector setproperty testelementproperty mailer_model mailermodel public void clear super clear set property new test element property mailer model new mailer model setproperty testelementproperty mailer_model mailermodel see sample listener sample occurred sample event public void sample occurred sample event e super sample occurred e get mailer model add e get result samplelistener sampleoccurred sampleevent sampleoccurred sampleevent sampleoccurred getmailermodel getresult public mailer model get mailer model return mailer model get property mailer model get object value mailermodel getmailermodel mailermodel getproperty mailer_model getobjectvalue private int error count public statistical sample result may be called by x stream errorcount statisticalsampleresult xstream allow old save service to generate a suitable result when sample error counts have been saved deprecated needs to be replaced when multiple sample results are sorted out param stamp param elapsed public statistical sample result long stamp long elapsed super stamp elapsed oldsaveservice statisticalsampleresult public statistical sample result sample result res copy data that is shared between samples i e the key items set sample label res get sample label nothing else can be saved as the samples may come from any thread set successful true assume result is ok set sample count 0 because we add the sample count in later statisticalsampleresult sampleresult setsamplelabel getsamplelabel setsuccessful setsamplecount public void add sample result res add sample counter set sample count get sample count res get sample count set bytes get bytes res get bytes add error counter if res is successful error count this set successful false set start end times if get start time 0 bug 40954 ensure start time gets started this set start time res get start time else this set start time math min get start time res get start time this set end time math max get end time res get end time set latency get latency res get latency sampleresult setsamplecount getsamplecount getsamplecount setbytes getbytes getbytes issuccessful errorcount setsuccessful getstarttime setstarttime getstarttime setstarttime getstarttime getstarttime setendtime getendtime getendtime setlatency getlatency getlatency public long get time return get end time get start time this get idle time gettime getendtime getstarttime getidletime public long get time stamp return get end time gettimestamp getendtime public int get error count overrides sample result return error count geterrorcount sampleresult errorcount public void set error count int e for reading csv files error count e seterrorcount errorcount generates the key to be used for aggregating samples as follows br code sample label code code thread group code n b the key should agree with the fixed items that are saved in the sample param event sample event whose key is to be calculated return the key to use for aggregating samples public static string get key sample event event string buffer sb new string buffer 80 sb append event get result get sample label append append event get thread group return sb to string samplelabel threadgroup getkey sampleevent stringbuffer stringbuffer getresult getsamplelabel getthreadgroup tostring set the path where xml messages are stored for random selection public void set log file string path log file path setlogfile logfile get the path where xml messages are stored this is the directory where j meter will randomly select a file public string get log file return log file jmeter getlogfile logfile it s kinda obvious but we state it anyways set the xml file with a string path param classname parser class name public void set parser class name string classname parser class name classname setparserclassname parserclassname get the file location of the xml file return string file path public string get parser class name return parser class name getparserclassname parserclassname sample gets a new http sampler from the generator and calls it s sample method public sample result sample with parser init filter instantiate parser sample result res null try if parser null throw new j meter exception no parser available samp set domain this get domain samp set port this get port we call parse with 1 to get only one this also means if we change the implementation to use 2 it would use every other entry and so on not that it is really useful but a person could use it that way if they have a huge gigabyte log file and they only want to use a quarter of the entries int this count parser parse and configure 1 this if this count 0 was there an error return error result new error problem parsing the log file new http sample result if this count 0 if count 0 filter null log info stopping current thread j meter context service get context get thread stop if filter null filter reset cookie manager cm get cookie manager if cm null cm clear count 0 return error result new error no entries found new http sample result count this count res sample res set sample label to string catch exception e log warn sampling failure e return error result e new http sample result return res httpsampler sampleresult samplewithparser initfilter instantiateparser sampleresult jmeterexception setdomain getdomain setport getport thiscount parseandconfigure thiscount errorresult httpsampleresult thiscount jmetercontextservice getcontext getthread cookiemanager getcookiemanager errorresult httpsampleresult thiscount setsamplelabel tostring errorresult httpsampleresult sample entry e simply calls sample param e ignored return the new sample public sample result sample entry e return sample with parser sampleresult samplewithparser method will instantiate the log parser based on the class in the text field this was done to make it easier for people to plugin their own log parser and use different log parser public void instantiate parser if parser null try if this get parser class name null this get parser class name length 0 if this get log file null this get log file length 0 parser log parser class for name get parser class name new instance parser set source file this get log file parser set filter filter else log error no log file specified catch instantiation exception e log error e catch illegal access exception e log error e catch class not found exception e log error e instantiateparser getparserclassname getparserclassname getlogfile getlogfile logparser forname getparserclassname newinstance setsourcefile getlogfile setfilter instantiationexception illegalaccessexception classnotfoundexception return returns the filter class name public string get filter class name return filter class name filterclassname getfilterclassname filterclassname param filter class name the filter class name to set public void set filter class name string filter class name this filter class name filter class name filterclassname filterclassname setfilterclassname filterclassname filterclassname filterclassname return returns the domain public string get domain n b must be in this class for the test bean code to work return super get domain getdomain testbean getdomain param domain the domain to set public void set domain string domain n b must be in this class for the test bean code to work super set domain domain setdomain testbean setdomain return returns the image parsing public boolean is image parsing return super is image parser imageparsing isimageparsing isimageparser param image parsing the image parsing to set public void set image parsing boolean image parsing super set image parser image parsing imageparsing imageparsing setimageparsing imageparsing setimageparser imageparsing return returns the port public string get port string return super get property as string http sampler base port getportstring getpropertyasstring httpsamplerbase param port the port to set public void set port string string port super set property http sampler base port port setportstring setproperty httpsamplerbase public access log sampler super accesslogsampler protected void init filter if filter null filter class name null filter class name length 0 try filter filter class for name filter class name new instance catch exception e log warn couldn t instantiate filter filter class name e initfilter filterclassname filterclassname forname filterclassname newinstance filterclassname public object clone access log sampler s access log sampler super clone if started if filter class name null filter class name length 0 try if test cloneable class is assignable from class for name filter class name init filter s filter filter test cloneable filter clone if test cloneable class is assignable from class for name parser class name instantiate parser s parser log parser test cloneable parser clone if filter null s parser set filter s filter catch exception e log warn could not clone cloneable filter e return s accesslogsampler accesslogsampler filterclassname filterclassname testcloneable isassignablefrom forname filterclassname initfilter testcloneable testcloneable isassignablefrom forname parserclassname instantiateparser logparser testcloneable setfilter public void test ended if parser null parser close filter null started false super test ended testended testended see org apache jmeter testelement test listener test started public void test started started true super test started testlistener teststarted teststarted teststarted public void thread finished if parser instanceof thread listener thread listener parser thread finished if filter instanceof thread listener thread listener filter thread finished threadfinished threadlistener threadlistener threadfinished threadlistener threadlistener threadfinished protected void initialize table model table model new object table model new string arguments panel column resource names 0 arguments panel column resource names 1 encode or not include equals http argument class new functor new functor get name non nls 1 new functor get value non nls 1 new functor is always encoded non nls 1 new functor is use equals non nls 1 new functor new functor set name non nls 1 new functor set value non nls 1 new functor set always encoded non nls 1 new functor set use equals non nls 1 new class string class string class boolean class boolean class initializetablemodel tablemodel objecttablemodel argumentspanel column_resource_names_0 argumentspanel column_resource_names_1 encode_or_not include_equals httpargument getname getvalue isalwaysencoded isuseequals setname setvalue setalwaysencoded setuseequals public static boolean test functors http arguments panel instance new http arguments panel instance initialize table model return instance table model check functors null instance get class testfunctors httpargumentspanel httpargumentspanel initializetablemodel tablemodel checkfunctors getclass protected void size columns j table table int resize mode table get auto resize mode table set auto resize mode j table auto resize off fix size table get column include equals fix size table get column encode or not table set auto resize mode resize mode sizecolumns jtable resizemode getautoresizemode setautoresizemode jtable auto_resize_off fixsize getcolumn include_equals fixsize getcolumn encode_or_not setautoresizemode resizemode protected object make new argument http argument arg new http argument arg set always encoded false arg set use equals true return arg makenewargument httpargument httpargument setalwaysencoded setuseequals private void fix size table column column column size width to fit column set min width column get width column set max width int column get width 1 5 column set width column get max width column set resizable false fixsize tablecolumn sizewidthtofit setminwidth getwidth setmaxwidth getwidth setwidth getmaxwidth setresizable public http arguments panel super j meter utils get res string paramtable non nls 1 httpargumentspanel jmeterutils getresstring public test element create test element stop table editing iterator model data table model iterator arguments args new arguments while model data has next http argument arg http argument model data next args add argument arg this configure test element args return test element args clone testelement createtestelement stoptableediting modeldata tablemodel modeldata hasnext httpargument httpargument modeldata addargument configuretestelement testelement public void configure test element el super configure el if el instanceof arguments table model clear data http argument convert arguments tohttp arguments el property iterator iter arguments el get arguments iterator while iter has next http argument arg http argument iter next get object value table model add row arg check delete status testelement tablemodel cleardata httpargument convertargumentstohttp propertyiterator getarguments hasnext httpargument httpargument getobjectvalue tablemodel addrow checkdeletestatus protected boolean is meta data normal http argument arg return arg get meta data null arg get meta data equals arg get value null arg get value length 0 ismetadatanormal httpargument getmetadata getmetadata getvalue getvalue public static void main string args if args length 1 int objects 10000 if args 0 null objects integer parse int args 0 list objs new linked list object factory of object factory get instance long bfree runtime get runtime free memory long btotal runtime get runtime total memory long bmax runtime get runtime max memory system out println before we create objects system out println system out println free bfree system out println total btotal system out println max bmax for int idx 0 idx objects idx connector cnn of create connector workers wkrs of create workers for int idz 0 idz 26 idz worker wk0 of create worker wk0 set current query string manager status wk0 set current uri http localhost manager status wk0 set method get wk0 set protocol http wk0 set remote addr wk0 set request bytes received 132 wk0 set request bytes sent 18532 wk0 set stage k wk0 set virtual host wkrs get worker add wk0 cnn set workers wkrs request info rqinfo of create request info rqinfo set bytes received 0 rqinfo set bytes sent 434374 rqinfo set error count 10 rqinfo set max time 850 rqinfo set processing time 2634 rqinfo set request count 1002 cnn set request info rqinfo thread info thinfo of create thread info thinfo set current thread count 50 thinfo set current threads busy 12 thinfo set max spare threads 50 thinfo set max threads 150 thinfo set min spare threads 10 cnn set thread info thinfo jvm vm of create jvm memory mem of create memory mem set free 77280 mem set total 134210000 mem set max 134217728 vm set memory mem status st of create status st set jvm vm st get connector add cnn monitor stats mstats new monitor stats stats calculate status st stats calculate load st 0 stats calculate memory load st stats calculate thread load st localhost 8080 http system current time millis monitor model monmodel new monitor model mstats objs add monmodel long afree runtime get runtime free memory long atotal runtime get runtime total memory long amax runtime get runtime max memory long delta atotal afree btotal bfree system out println after we create objects system out println system out println free afree system out println total atotal system out println max amax system out println system out println delta delta 1024 kilobytes system out println delta delta 1024 1024 megabytes system out println number of objects objects system out println potential number of servers objects 1000 else system out println please provide the number of objects parseint linkedlist objectfactory objectfactory getinstance getruntime freememory getruntime totalmemory getruntime maxmemory createconnector createworkers createworker setcurrentquerystring setcurrenturi setmethod setprotocol setremoteaddr setrequestbytesreceived setrequestbytessent setstage setvirtualhost getworker setworkers requestinfo createrequestinfo setbytesreceived setbytessent seterrorcount setmaxtime setprocessingtime setrequestcount setrequestinfo threadinfo createthreadinfo setcurrentthreadcount setcurrentthreadsbusy setmaxsparethreads setmaxthreads setminsparethreads setthreadinfo createjvm creatememory setfree settotal setmax setmemory createstatus setjvm getconnector monitorstats monitorstats calculatestatus calculateload calculatememoryload calculatethreadload currenttimemillis monitormodel monitormodel getruntime freememory getruntime totalmemory getruntime maxmemory protected final tcp client tcp client the data implementation public tcp client decorator tcp client tcp client this tcp client tcp client tcpclient tcpclient tcpclientdecorator tcpclient tcpclient tcpclient tcpclient convert int to byte array param value int to be converted param len length of required byte array return byte array representation of input value throws illegal argument exception if not length 2 or 4 or outside range of a short int public static byte int to byte array int value int len if len 2 len 4 if len 2 value short min value value short max value throw new illegal argument exception value outside range for signed short int else byte b new byte len for int i 0 i len i int offset b length 1 i 8 b i byte value offset return b else throw new illegal argument exception length must be specified as either 2 or 4 illegalargumentexception inttobytearray min_value max_value illegalargumentexception illegalargumentexception convert byte array to int param b byte array to be converted return integer value of input byte array throws illegal argument exception if ba is null or not length 2 or 4 public static int byte array to int byte b if b null b length 2 b length 4 preserve sign on first byte int value b 0 b length 1 8 for int i 1 i b length i int offset b length 1 i 8 value b i 0xff offset return value else throw new illegal argument exception byte array is null or invalid length illegalargumentexception bytearraytoint illegalargumentexception constructor for the graph visualizer object public graph visualizer model new sampling stat calculator graph graph new graph model init graphvisualizer graphvisualizer samplingstatcalculator gets the image attribute of the graph visualizer object return the image value public image get image image result graph create image graph get width graph get height graph paint component result get graphics return result graphvisualizer getimage createimage getwidth getheight paintcomponent getgraphics public synchronized void update gui sample s we have received one more sample graph update gui s no samples field set text long to string s get count data field set text long to string s get data average field set text long to string s get average deviation field set text long to string s get deviation throughput field set text nf format 60 s get throughput minute non nls 1 median field set text long to string s get median updatey axis updategui updategui nosamplesfield settext tostring getcount datafield settext tostring getdata averagefield settext tostring getaverage deviationfield settext tostring getdeviation throughputfield settext getthroughput medianfield settext tostring getmedian updateyaxis public void add sample result res update gui model add sample res sampleresult updategui addsample public string get label resource return graph results title non nls 1 getlabelresource graph_results_title public void item state changed item event e if e get item data this graph enable data e get state change item event selected else if e get item average this graph enable average e get state change item event selected else if e get item deviation this graph enable deviation e get state change item event selected else if e get item throughput this graph enable throughput e get state change item event selected else if e get item median this graph enable median e get state change item event selected this graph repaint itemstatechanged itemevent getitem enabledata getstatechange itemevent getitem enableaverage getstatechange itemevent getitem enabledeviation getstatechange itemevent getitem enablethroughput getstatechange itemevent getitem enablemedian getstatechange itemevent public void clear data graph clear data model clear data field set text zero average field set text zero deviation field set text zero throughput field set text 0 minute non nls 1 median field set text zero no samples field set text zero updatey axis repaint cleardata cleardata datafield settext averagefield settext deviationfield settext throughputfield settext medianfield settext nosamplesfield settext updateyaxis public string to string return show the samples analysis as dot plots tostring update the max and min value of the y axis private void updatey axis maxy field set text long to string graph get graph max miny field set text zero updateyaxis maxyfield settext tostring getgraphmax minyfield settext initialize the gui private void init this set layout new border layout main panel border margin new empty border 10 10 5 10 this set border margin set up the graph with header footer y axis and graph display j panel graph panel new j panel new border layout graph panel add createy axis border layout west graph panel add create choose panel border layout north graph panel add create graph panel border layout center graph panel add create graph info panel border layout south add the main panel and the graph this add make title panel border layout north this add graph panel border layout center setlayout borderlayout emptyborder setborder jpanel graphpanel jpanel borderlayout graphpanel createyaxis borderlayout graphpanel createchoosepanel borderlayout graphpanel creategraphpanel borderlayout graphpanel creategraphinfopanel borderlayout maketitlepanel borderlayout graphpanel borderlayout creates the panel containing the graph s y axis labels return the y axis panel private j panel createy axis j panel graphy axis panel new j panel graphy axis panel set layout new border layout maxy field createy axis field 5 miny field createy axis field 3 graphy axis panel add createy axis panel graph results ms maxy field border layout north non nls 1 graphy axis panel add createy axis panel graph results ms miny field border layout south non nls 1 return graphy axis panel jpanel createyaxis jpanel graphyaxispanel jpanel graphyaxispanel setlayout borderlayout maxyfield createyaxisfield minyfield createyaxisfield graphyaxispanel createyaxispanel graph_results_ms maxyfield borderlayout graphyaxispanel createyaxispanel graph_results_ms minyfield borderlayout graphyaxispanel creates a text field to be used for the value of a y axis label these fields hold the minimum and maximum values for the graph the units are kept in a separate label outside of this field param length the number of characters which the field will use to calculate its preferred width this should be set to the maximum number of digits that are expected to be necessary to hold the label value see createy axis panel string j text field return a text field configured to be used in the y axis private j text field createy axis field int length j text field field new j text field length field set border border factory create empty border 0 10 0 0 field set editable false field set foreground color black field set background get background field set horizontal alignment j text field right return field createyaxispanel jtextfield jtextfield createyaxisfield jtextfield jtextfield setborder borderfactory createemptyborder seteditable setforeground setbackground getbackground sethorizontalalignment jtextfield creates a panel for an entire y axis label this includes the dynamic value as well as the unit label param label resource name the name of the label resource this is used to look up the label text using link j meter utils get res string string return a panel containing both the dynamic and static parts of a y axis label private j panel createy axis panel string label resource name j text field field j panel panel new j panel new flow layout j label label new j label j meter utils get res string label resource name panel add field panel add label return panel labelresourcename jmeterutils getresstring jpanel createyaxispanel labelresourcename jtextfield jpanel jpanel flowlayout jlabel jlabel jmeterutils getresstring labelresourcename creates a panel which allows the user to choose which graphs to display this panel consists of a check box for each type of graph current sample average deviation and throughput return a panel allowing the user to choose which graphs to display private j panel create choose panel j panel choose graphs panel new j panel choose graphs panel set layout new flow layout j label select graphs label new j label j meter utils get res string graph choose graphs non nls 1 data create choose check box graph results data color black non nls 1 average create choose check box graph results average color blue non nls 1 deviation create choose check box graph results deviation color red non nls 1 throughput create choose check box graph results throughput j meter color dark green non nls 1 median create choose check box graph results median j meter color purple non nls 1 choose graphs panel add select graphs label choose graphs panel add data choose graphs panel add average choose graphs panel add median choose graphs panel add deviation choose graphs panel add throughput return choose graphs panel jpanel createchoosepanel jpanel choosegraphspanel jpanel choosegraphspanel setlayout flowlayout jlabel selectgraphslabel jlabel jmeterutils getresstring graph_choose_graphs createchoosecheckbox graph_results_data createchoosecheckbox graph_results_average createchoosecheckbox graph_results_deviation createchoosecheckbox graph_results_throughput jmetercolor dark_green createchoosecheckbox graph_results_median jmetercolor choosegraphspanel selectgraphslabel choosegraphspanel choosegraphspanel choosegraphspanel choosegraphspanel choosegraphspanel choosegraphspanel creates a check box configured to be used to in the choose panel allowing the user to select whether or not a particular kind of graph data will be displayed param label resource name the name of the label resource this is used to look up the label text using link j meter utils get res string string param color the color used for the checkbox text by convention this is the same color that is used to draw the graph and for the corresponding info field return a checkbox allowing the user to select whether or not a kind of graph data will be displayed private j check box create choose check box string label resource name color color j check box check box new j check box j meter utils get res string label resource name check box set selected true check box add item listener this check box set foreground color return check box labelresourcename jmeterutils getresstring jcheckbox createchoosecheckbox labelresourcename jcheckbox checkbox jcheckbox jmeterutils getresstring labelresourcename checkbox setselected checkbox additemlistener checkbox setforeground checkbox creates a scroll pane containing the actual graph of the results return a scroll pane containing the graph private component create graph panel j scroll pane graph scroll panel make scroll pane graph j scroll pane vertical scrollbar never j scroll pane horizontal scrollbar as needed graph scroll panel set viewport border border factory create empty border 2 2 2 2 graph scroll panel set preferred size graph scroll panel get minimum size return graph scroll panel creategraphpanel jscrollpane graphscrollpanel makescrollpane jscrollpane vertical_scrollbar_never jscrollpane horizontal_scrollbar_as_needed graphscrollpanel setviewportborder borderfactory createemptyborder graphscrollpanel setpreferredsize graphscrollpanel getminimumsize graphscrollpanel creates a panel which numerically displays the current graph values return a panel showing the current graph values private box create graph info panel box graph info panel box create horizontal box no samples field create info field color black 6 data field create info field color black 5 average field create info field color blue 5 deviation field create info field color red 5 throughput field create info field j meter color dark green 15 median field create info field j meter color purple 5 graph info panel add create info column create info label graph results no samples no samples field non nls 1 no samples field create info label graph results deviation deviation field deviation field non nls 1 graph info panel add box create horizontal glue graph info panel add create info column create info label graph results latest sample data field data field non nls 1 create info label graph results throughput throughput field throughput field non nls 1 graph info panel add box create horizontal glue graph info panel add create info column create info label graph results average average field average field non nls 1 create info label graph results median median field median field non nls 1 graph info panel add box create horizontal glue return graph info panel creategraphinfopanel graphinfopanel createhorizontalbox nosamplesfield createinfofield datafield createinfofield averagefield createinfofield deviationfield createinfofield throughputfield createinfofield jmetercolor dark_green medianfield createinfofield jmetercolor graphinfopanel createinfocolumn createinfolabel graph_results_no_samples nosamplesfield nosamplesfield createinfolabel graph_results_deviation deviationfield deviationfield graphinfopanel createhorizontalglue graphinfopanel createinfocolumn createinfolabel graph_results_latest_sample datafield datafield createinfolabel graph_results_throughput throughputfield throughputfield graphinfopanel createhorizontalglue graphinfopanel createinfocolumn createinfolabel graph_results_average averagefield averagefield createinfolabel graph_results_median medianfield medianfield graphinfopanel createhorizontalglue graphinfopanel creates one of the fields used to display the graph s current values param color the color used to draw the value by convention this is the same color that is used to draw the graph for this value and in the choose panel param length the number of digits which the field should be able to display return a text field configured to display one of the current graph values private j text field create info field color color int length j text field field new j text field length field set border border factory create empty border 0 0 0 0 field set editable false field set foreground color field set background get background the text field should expand horizontally but have a fixed height field set maximum size new dimension field get maximum size width field get preferred size height return field jtextfield createinfofield jtextfield jtextfield setborder borderfactory createemptyborder seteditable setforeground setbackground getbackground setmaximumsize getmaximumsize getpreferredsize creates a label for one of the fields used to display the graph s current values neither the label created by this method or the code field code passed as a parameter is added to the gui here param label resource name the name of the label resource this is used to look up the label text using link j meter utils get res string string param field the field this label is being created for private j label create info label string label resource name j text field field j label label new j label j meter utils get res string label resource name label set foreground field get foreground label set label for field return label labelresourcename jmeterutils getresstring jlabel createinfolabel labelresourcename jtextfield jlabel jlabel jmeterutils getresstring labelresourcename setforeground getforeground setlabelfor creates a panel containing two pairs of labels and fields for displaying the current graph values this method exists to help with laying out the fields in columns if one or more components are null then these components will be represented by blank space param label1 the label for the first field this label will be placed in the upper left section of the panel if this parameter is null this section of the panel will be left blank param field1 the field corresponding to the first label this field will be placed in the upper right section of the panel if this parameter is null this section of the panel will be left blank param label2 the label for the second field this label will be placed in the lower left section of the panel if this parameter is null this section of the panel will be left blank param field2 the field corresponding to the second label this field will be placed in the lower right section of the panel if this parameter is null this section of the panel will be left blank private box create info column j label label1 j text field field1 j label label2 j text field field2 this column actually consists of a row with two sub columns the first column contains the labels and the second column contains the fields box row box create horizontal box box col box create vertical box col add label1 null label1 box create vertical glue col add label2 null label2 box create vertical glue row add col row add box create horizontal strut 5 col box create vertical box col add field1 null field1 box create vertical glue col add field2 null field2 box create vertical glue row add col row add box create horizontal strut 5 return row createinfocolumn jlabel jtextfield jlabel jtextfield createhorizontalbox createverticalbox createverticalglue createverticalglue createhorizontalstrut createverticalbox createverticalglue createverticalglue createhorizontalstrut private static file temporary file public testhttp samplers against http mirror server string arg0 super arg0 temporaryfile testhttpsamplersagainsthttpmirrorserver public static test suite test setup setup new test setup new test suite testhttp samplers against http mirror server class private http mirror server http server protected void set up throws exception http server testhttp mirror thread start http mirror mirror port create the test file content test file content new string some foo content 01234 56789 u007c u2aa1 u266a u0153 u20a1 u0115 u0364 u00c5 u2052 uc385 c3 85 get bytes utf 8 create a temporary file to make sure we always have a file to give to the post writer whereever we are or whatever the current path is temporary file file create temp file testhttp samplers against http mirror server tmp output stream output new file output stream temporary file output write test file content output flush output close protected void tear down throws exception shutdown mirror server http server stop server http server null delete temporay file temporary file delete return setup testsetup testsetup testsuite testhttpsamplersagainsthttpmirrorserver httpmirrorserver httpserver setup httpserver testhttpmirrorthread starthttpmirror mirror_port test_file_content getbytes postwriter temporaryfile createtempfile testhttpsamplersagainsthttpmirrorserver outputstream fileoutputstream temporaryfile test_file_content teardown httpserver stopserver httpserver temporaryfile private http mirror server http server protected void set up throws exception http server testhttp mirror thread start http mirror mirror port create the test file content test file content new string some foo content 01234 56789 u007c u2aa1 u266a u0153 u20a1 u0115 u0364 u00c5 u2052 uc385 c3 85 get bytes utf 8 create a temporary file to make sure we always have a file to give to the post writer whereever we are or whatever the current path is temporary file file create temp file testhttp samplers against http mirror server tmp output stream output new file output stream temporary file output write test file content output flush output close httpmirrorserver httpserver setup httpserver testhttpmirrorthread starthttpmirror mirror_port test_file_content getbytes postwriter temporaryfile createtempfile testhttpsamplersagainsthttpmirrorserver outputstream fileoutputstream temporaryfile test_file_content protected void tear down throws exception shutdown mirror server http server stop server http server null delete temporay file temporary file delete teardown httpserver stopserver httpserver temporaryfile public void testpostrequest urlencoded throws exception testpostrequest urlencoded http sampler iso 8859 1 testpostrequest_urlencoded testpostrequest_urlencoded http_sampler iso_8859_1 public void testpostrequest urlencoded2 throws exception testpostrequest urlencoded http sampler2 us ascii testpostrequest_urlencoded2 testpostrequest_urlencoded http_sampler2 us_ascii public void testpostrequest formmultipart throws exception testpostrequest formmultipart http sampler iso 8859 1 testpostrequest_formmultipart testpostrequest_formmultipart http_sampler iso_8859_1 public void testpostrequest formmultipart2 throws exception testpostrequest formmultipart http sampler2 us ascii testpostrequest_formmultipart2 testpostrequest_formmultipart http_sampler2 us_ascii public void testpostrequest fileupload throws exception testpostrequest fileupload http sampler iso 8859 1 testpostrequest_fileupload testpostrequest_fileupload http_sampler iso_8859_1 public void testpostrequest fileupload2 throws exception testpostrequest fileupload http sampler2 us ascii testpostrequest_fileupload2 testpostrequest_fileupload http_sampler2 us_ascii public void testpostrequest bodyfromparametervalues throws exception testpostrequest bodyfromparametervalues http sampler iso 8859 1 testpostrequest_bodyfromparametervalues testpostrequest_bodyfromparametervalues http_sampler iso_8859_1 public void testpostrequest bodyfromparametervalues2 throws exception testpostrequest bodyfromparametervalues http sampler2 us ascii testpostrequest_bodyfromparametervalues2 testpostrequest_bodyfromparametervalues http_sampler2 us_ascii public void test get request throws exception test get request http sampler testgetrequest testgetrequest http_sampler public void test get request2 throws exception test get request http sampler2 testgetrequest2 testgetrequest http_sampler2 public void testgetrequest parameters throws exception testgetrequest parameters http sampler testgetrequest_parameters testgetrequest_parameters http_sampler public void testgetrequest parameters2 throws exception testgetrequest parameters http sampler2 testgetrequest_parameters2 testgetrequest_parameters http_sampler2 private void testpostrequest urlencoded int sampler type string sampler default encoding throws exception string title field title string title value mytitle string description field description string description value mydescription test sending data with default encoding http sampler base sampler create http sampler sampler type string content encoding setup url sampler content encoding setup form data sampler false title field title value description field description value http sample result res execute sampler sampler check post request url encoded sampler res sampler default encoding content encoding title field title value description field description value false test sending data as iso 8859 1 sampler create http sampler sampler type content encoding iso 8859 1 setup url sampler content encoding setup form data sampler false title field title value description field description value res execute sampler sampler check post request url encoded sampler res sampler default encoding content encoding title field title value description field description value false test sending data as utf 8 sampler create http sampler sampler type content encoding utf 8 title value mytitle u0153 u20a1 u0115 u00c5 description value mydescription u0153 u20a1 u0115 u00c5 setup url sampler content encoding setup form data sampler false title field title value description field description value res execute sampler sampler check post request url encoded sampler res sampler default encoding content encoding title field title value description field description value false test sending data as utf 8 with values that will change when urlencoded sampler create http sampler sampler type content encoding utf 8 title value mytitle description value mydescription setup url sampler content encoding setup form data sampler false title field title value description field description value res execute sampler sampler check post request url encoded sampler res sampler default encoding content encoding title field title value description field description value false test sending data as utf 8 with values that have been urlencoded sampler create http sampler sampler type content encoding utf 8 title value mytitle 2f 3d description value mydescription 2f 5c setup url sampler content encoding setup form data sampler true title field title value description field description value res execute sampler sampler check post request url encoded sampler res sampler default encoding content encoding title field title value description field description value true test sending data as utf 8 with values similar to viewstate parameter that net uses sampler create http sampler sampler type content encoding utf 8 title value wep dwullte2 mzm2ota0ntypzbyc agmpz ra 8dz2dnz2dnz2d gn dar6 osh pwd jc description value mydescription setup url sampler content encoding setup form data sampler false title field title value description field description value res execute sampler sampler check post request url encoded sampler res sampler default encoding content encoding title field title value description field description value false test sending data as utf 8 with values similar to viewstate parameter that net uses with values urlencoded but the always encode set to false for the arguments this is how the http proxy server adds arguments to the sampler sampler create http sampler sampler type content encoding utf 8 title value 2 fwep dwullte2 mzm2ota0ntypzbyc agmpz 2 fra 2b8dz2dnz2dnz2d 2fgn dar6 osh pwd jc 3d description value mydescription setup url sampler content encoding setup form data sampler false title field title value description field description value http argument sampler get arguments get argument 0 set always encoded false http argument sampler get arguments get argument 1 set always encoded false res execute sampler sampler assert false http argument sampler get arguments get argument 0 is always encoded assert false http argument sampler get arguments get argument 1 is always encoded check post request url encoded sampler res sampler default encoding content encoding title field title value description field description value true test sending data as utf 8 where user defined variables are used to set the value for form data j meter utils set locale locale english test plan test plan new test plan j meter variables vars new j meter variables vars put title prefix a test u00c5 vars put description suffix the end j meter context service get context set variables vars j meter context service get context set sampling started true value replacer replacer new value replacer replacer set user defined variables test plan get user defined variables sampler create http sampler sampler type content encoding utf 8 title value title prefix mytitle u0153 u20a1 u0115 u00c5 description value mydescription u0153 u20a1 u0115 u00c5 description suffix setup url sampler content encoding setup form data sampler false title field title value description field description value replace the variables in the sampler replacer replace values sampler res execute sampler sampler string expected title value a test u00c5mytitle u0153 u20a1 u0115 u00c5 string expected description value mydescription u0153 u20a1 u0115 u00c5the end check post request url encoded sampler res sampler default encoding content encoding title field expected title value description field expected description value false testpostrequest_urlencoded samplertype samplerdefaultencoding titlefield titlevalue descriptionfield descriptionvalue httpsamplerbase createhttpsampler samplertype contentencoding setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue httpsampleresult executesampler checkpostrequesturlencoded samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue createhttpsampler samplertype contentencoding iso_8859_1 setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue executesampler checkpostrequesturlencoded samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue createhttpsampler samplertype contentencoding titlevalue descriptionvalue setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue executesampler checkpostrequesturlencoded samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue createhttpsampler samplertype contentencoding titlevalue descriptionvalue setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue executesampler checkpostrequesturlencoded samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue createhttpsampler samplertype contentencoding titlevalue descriptionvalue setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue executesampler checkpostrequesturlencoded samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue __viewstate createhttpsampler samplertype contentencoding titlevalue wepdwullte2mzm2ota0ntypzbycagmpz gndar6oshpwdjc descriptionvalue setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue executesampler checkpostrequesturlencoded samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue __viewstate createhttpsampler samplertype contentencoding titlevalue 2fwepdwullte2mzm2ota0ntypzbycagmpz 2fra 2fgndar6oshpwdjc descriptionvalue setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue httpargument getarguments getargument setalwaysencoded httpargument getarguments getargument setalwaysencoded executesampler assertfalse httpargument getarguments getargument isalwaysencoded assertfalse httpargument getarguments getargument isalwaysencoded checkpostrequesturlencoded samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue jmeterutils setlocale testplan testplan testplan jmetervariables jmetervariables title_prefix description_suffix the_end jmetercontextservice getcontext setvariables jmetercontextservice getcontext setsamplingstarted valuereplacer valuereplacer setuserdefinedvariables testplan getuserdefinedvariables createhttpsampler samplertype contentencoding titlevalue title_prefix descriptionvalue description_suffix setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue replacevalues executesampler expectedtitlevalue expecteddescriptionvalue u00c5the_end checkpostrequesturlencoded samplerdefaultencoding contentencoding titlefield expectedtitlevalue descriptionfield expecteddescriptionvalue private void testpostrequest formmultipart int sampler type string sampler default encoding throws exception string title field title string title value mytitle string description field description string description value mydescription test sending data with default encoding http sampler base sampler create http sampler sampler type string content encoding setup url sampler content encoding setup form data sampler false title field title value description field description value sampler set do multipart post true http sample result res execute sampler sampler check post request form multipart sampler res sampler default encoding content encoding title field title value description field description value test sending data as iso 8859 1 sampler create http sampler sampler type content encoding iso 8859 1 setup url sampler content encoding setup form data sampler false title field title value description field description value sampler set do multipart post true res execute sampler sampler check post request form multipart sampler res sampler default encoding content encoding title field title value description field description value test sending data as utf 8 sampler create http sampler sampler type content encoding utf 8 title value mytitle u0153 u20a1 u0115 u00c5 description value mydescription u0153 u20a1 u0115 u00c5 setup url sampler content encoding setup form data sampler false title field title value description field description value sampler set do multipart post true res execute sampler sampler check post request form multipart sampler res sampler default encoding content encoding title field title value description field description value test sending data as utf 8 with values that would have been urlencoded if it was not sent as multipart sampler create http sampler sampler type content encoding utf 8 title value mytitle description value mydescription setup url sampler content encoding setup form data sampler false title field title value description field description value sampler set do multipart post true res execute sampler sampler check post request form multipart sampler res sampler default encoding content encoding title field title value description field description value test sending data as utf 8 with values that have been urlencoded sampler create http sampler sampler type content encoding utf 8 title value mytitle 2f 3d description value mydescription 2f 5c setup url sampler content encoding setup form data sampler true title field title value description field description value sampler set do multipart post true res execute sampler sampler string expected title value mytitle string expected description value mydescription check post request form multipart sampler res sampler default encoding content encoding title field expected title value description field expected description value test sending data as utf 8 with values similar to viewstate parameter that net uses sampler create http sampler sampler type content encoding utf 8 title value wep dwullte2 mzm2ota0ntypzbyc agmpz ra 8dz2dnz2dnz2d gn dar6 osh pwd jc description value mydescription setup url sampler content encoding setup form data sampler false title field title value description field description value sampler set do multipart post true res execute sampler sampler check post request form multipart sampler res sampler default encoding content encoding title field title value description field description value test sending data as utf 8 where user defined variables are used to set the value for form data j meter utils set locale locale english test plan test plan new test plan j meter variables vars new j meter variables vars put title prefix a test u00c5 vars put description suffix the end j meter context service get context set variables vars j meter context service get context set sampling started true value replacer replacer new value replacer replacer set user defined variables test plan get user defined variables sampler create http sampler sampler type content encoding utf 8 title value title prefix mytitle u0153 u20a1 u0115 u00c5 description value mydescription u0153 u20a1 u0115 u00c5 description suffix setup url sampler content encoding setup form data sampler false title field title value description field description value sampler set do multipart post true replace the variables in the sampler replacer replace values sampler res execute sampler sampler expected title value a test u00c5mytitle u0153 u20a1 u0115 u00c5 expected description value mydescription u0153 u20a1 u0115 u00c5the end check post request form multipart sampler res sampler default encoding content encoding title field expected title value description field expected description value testpostrequest_formmultipart samplertype samplerdefaultencoding titlefield titlevalue descriptionfield descriptionvalue httpsamplerbase createhttpsampler samplertype contentencoding setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue setdomultipartpost httpsampleresult executesampler checkpostrequestformmultipart samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue createhttpsampler samplertype contentencoding iso_8859_1 setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue setdomultipartpost executesampler checkpostrequestformmultipart samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue createhttpsampler samplertype contentencoding titlevalue descriptionvalue setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue setdomultipartpost executesampler checkpostrequestformmultipart samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue createhttpsampler samplertype contentencoding titlevalue descriptionvalue setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue setdomultipartpost executesampler checkpostrequestformmultipart samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue createhttpsampler samplertype contentencoding titlevalue descriptionvalue setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue setdomultipartpost executesampler expectedtitlevalue expecteddescriptionvalue checkpostrequestformmultipart samplerdefaultencoding contentencoding titlefield expectedtitlevalue descriptionfield expecteddescriptionvalue __viewstate createhttpsampler samplertype contentencoding titlevalue wepdwullte2mzm2ota0ntypzbycagmpz gndar6oshpwdjc descriptionvalue setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue setdomultipartpost executesampler checkpostrequestformmultipart samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue jmeterutils setlocale testplan testplan testplan jmetervariables jmetervariables title_prefix description_suffix the_end jmetercontextservice getcontext setvariables jmetercontextservice getcontext setsamplingstarted valuereplacer valuereplacer setuserdefinedvariables testplan getuserdefinedvariables createhttpsampler samplertype contentencoding titlevalue title_prefix descriptionvalue description_suffix setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue setdomultipartpost replacevalues executesampler expectedtitlevalue expecteddescriptionvalue u00c5the_end checkpostrequestformmultipart samplerdefaultencoding contentencoding titlefield expectedtitlevalue descriptionfield expecteddescriptionvalue private void testpostrequest fileupload int sampler type string sampler default encoding throws exception string title field title string title value mytitle string description field description string description value mydescription string file field file1 string file mime type text plain test sending data with default encoding http sampler base sampler create http sampler sampler type string content encoding setup url sampler content encoding setup file upload data sampler false title field title value description field description value file field temporary file file mime type http sample result res execute sampler sampler check post request file upload sampler res sampler default encoding content encoding title field title value description field description value file field temporary file file mime type test file content test sending data as iso 8859 1 sampler create http sampler sampler type content encoding iso 8859 1 setup url sampler content encoding setup file upload data sampler false title field title value description field description value file field temporary file file mime type res execute sampler sampler check post request file upload sampler res sampler default encoding content encoding title field title value description field description value file field temporary file file mime type test file content test sending data as utf 8 sampler create http sampler sampler type content encoding utf 8 title value mytitle u0153 u20a1 u0115 u00c5 description value mydescription u0153 u20a1 u0115 u00c5 setup url sampler content encoding setup file upload data sampler false title field title value description field description value file field temporary file file mime type res execute sampler sampler check post request file upload sampler res sampler default encoding content encoding title field title value description field description value file field temporary file file mime type test file content testpostrequest_fileupload samplertype samplerdefaultencoding titlefield titlevalue descriptionfield descriptionvalue filefield filemimetype httpsamplerbase createhttpsampler samplertype contentencoding setupurl contentencoding setupfileuploaddata titlefield titlevalue descriptionfield descriptionvalue filefield temporaryfile filemimetype httpsampleresult executesampler checkpostrequestfileupload samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue filefield temporaryfile filemimetype test_file_content createhttpsampler samplertype contentencoding iso_8859_1 setupurl contentencoding setupfileuploaddata titlefield titlevalue descriptionfield descriptionvalue filefield temporaryfile filemimetype executesampler checkpostrequestfileupload samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue filefield temporaryfile filemimetype test_file_content createhttpsampler samplertype contentencoding titlevalue descriptionvalue setupurl contentencoding setupfileuploaddata titlefield titlevalue descriptionfield descriptionvalue filefield temporaryfile filemimetype executesampler checkpostrequestfileupload samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue filefield temporaryfile filemimetype test_file_content private void testpostrequest bodyfromparametervalues int sampler type string sampler default encoding throws exception final string title field ensure only values are used string title value mytitle final string description field ensure only values are used string description value mydescription test sending data with default encoding http sampler base sampler create http sampler sampler type string content encoding setup url sampler content encoding setup form data sampler false title field title value description field description value http argument sampler get arguments get argument 0 set always encoded false http argument sampler get arguments get argument 1 set always encoded false http sample result res execute sampler sampler string expected post body title value description value check post request body sampler res sampler default encoding content encoding expected post body test sending data as iso 8859 1 sampler create http sampler sampler type content encoding iso 8859 1 setup url sampler content encoding setup form data sampler false title field title value description field description value http argument sampler get arguments get argument 0 set always encoded false http argument sampler get arguments get argument 1 set always encoded false res execute sampler sampler expected post body title value description value check post request body sampler res sampler default encoding content encoding expected post body test sending data as utf 8 sampler create http sampler sampler type content encoding utf 8 title value mytitle u0153 u20a1 u0115 u00c5 description value mydescription u0153 u20a1 u0115 u00c5 setup url sampler content encoding setup form data sampler false title field title value description field description value http argument sampler get arguments get argument 0 set always encoded false http argument sampler get arguments get argument 1 set always encoded false res execute sampler sampler expected post body title value description value check post request body sampler res sampler default encoding content encoding expected post body test sending data as utf 8 with values that will change when urlencoded sampler create http sampler sampler type content encoding utf 8 title value mytitle description value mydescription setup url sampler content encoding setup form data sampler false title field title value description field description value http argument sampler get arguments get argument 0 set always encoded false http argument sampler get arguments get argument 1 set always encoded false res execute sampler sampler expected post body title value description value check post request body sampler res sampler default encoding content encoding expected post body test sending data as utf 8 with values that will change when urlencoded and where we tell the sampler to urlencode the parameter value sampler create http sampler sampler type content encoding utf 8 title value mytitle description value mydescription setup url sampler content encoding setup form data sampler true title field title value description field description value res execute sampler sampler expected post body url encoder encode title value description value content encoding check post request body sampler res sampler default encoding content encoding expected post body test sending data as utf 8 with values that have been urlencoded sampler create http sampler sampler type content encoding utf 8 title value mytitle 2f 3d description value mydescription 2f 5c setup url sampler content encoding setup form data sampler false title field title value description field description value http argument sampler get arguments get argument 0 set always encoded false http argument sampler get arguments get argument 1 set always encoded false res execute sampler sampler expected post body title value description value check post request body sampler res sampler default encoding content encoding expected post body test sending data as utf 8 with values that have been urlencoded and where we tell the sampler to urlencode the parameter values sampler create http sampler sampler type content encoding utf 8 title value mytitle 2f 3d description value mydescription 2f 5c setup url sampler content encoding setup form data sampler true title field title value description field description value res execute sampler sampler expected post body title value description value check post request body sampler res sampler default encoding content encoding expected post body test sending data as utf 8 with values similar to viewstate parameter that net uses sampler create http sampler sampler type content encoding utf 8 title value wep dwullte2 mzm2ota0ntypzbyc agmpz ra 8dz2dnz2dnz2d gn dar6 osh pwd jc description value mydescription setup url sampler content encoding setup form data sampler false title field title value description field description value http argument sampler get arguments get argument 0 set always encoded false http argument sampler get arguments get argument 1 set always encoded false res execute sampler sampler expected post body title value description value check post request body sampler res sampler default encoding content encoding expected post body test sending data as utf 8 with as part of the value where the value is set in sampler as not urluencoded but the isalwaysencoded flag of the argument is set to false this mimics the http sampler base add non encoded argument which the proxy server calls in some cases sampler create http sampler sampler type content encoding utf 8 title value mytitle description value mydescription setup url sampler content encoding setup form data sampler false title field title value description field description value http argument sampler get arguments get argument 0 set always encoded false http argument sampler get arguments get argument 1 set always encoded false res execute sampler sampler expected post body title value description value check post request body sampler res sampler default encoding content encoding expected post body test sending data as utf 8 where user defined variables are used to set the value for form data j meter utils set locale locale english test plan test plan new test plan j meter variables vars new j meter variables vars put title prefix a test u00c5 vars put description suffix the end j meter context service get context set variables vars j meter context service get context set sampling started true value replacer replacer new value replacer replacer set user defined variables test plan get user defined variables sampler create http sampler sampler type content encoding utf 8 title value title prefix mytitle u0153 u20a1 u0115 u00c5 description value mydescription u0153 u20a1 u0115 u00c5 description suffix setup url sampler content encoding setup form data sampler false title field title value description field description value http argument sampler get arguments get argument 0 set always encoded false http argument sampler get arguments get argument 1 set always encoded false replace the variables in the sampler replacer replace values sampler res execute sampler sampler string expected title value a test u00c5mytitle u0153 u20a1 u0115 u00c5 string expected description value mydescription u0153 u20a1 u0115 u00c5the end expected post body expected title value expected description value check post request body sampler res sampler default encoding content encoding expected post body testpostrequest_bodyfromparametervalues samplertype samplerdefaultencoding titlefield titlevalue descriptionfield descriptionvalue httpsamplerbase createhttpsampler samplertype contentencoding setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue httpargument getarguments getargument setalwaysencoded httpargument getarguments getargument setalwaysencoded httpsampleresult executesampler expectedpostbody titlevalue descriptionvalue checkpostrequestbody samplerdefaultencoding contentencoding expectedpostbody createhttpsampler samplertype contentencoding iso_8859_1 setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue httpargument getarguments getargument setalwaysencoded httpargument getarguments getargument setalwaysencoded executesampler expectedpostbody titlevalue descriptionvalue checkpostrequestbody samplerdefaultencoding contentencoding expectedpostbody createhttpsampler samplertype contentencoding titlevalue descriptionvalue setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue httpargument getarguments getargument setalwaysencoded httpargument getarguments getargument setalwaysencoded executesampler expectedpostbody titlevalue descriptionvalue checkpostrequestbody samplerdefaultencoding contentencoding expectedpostbody createhttpsampler samplertype contentencoding titlevalue descriptionvalue setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue httpargument getarguments getargument setalwaysencoded httpargument getarguments getargument setalwaysencoded executesampler expectedpostbody titlevalue descriptionvalue checkpostrequestbody samplerdefaultencoding contentencoding expectedpostbody createhttpsampler samplertype contentencoding titlevalue descriptionvalue setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue executesampler expectedpostbody urlencoder titlevalue descriptionvalue contentencoding checkpostrequestbody samplerdefaultencoding contentencoding expectedpostbody createhttpsampler samplertype contentencoding titlevalue descriptionvalue setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue httpargument getarguments getargument setalwaysencoded httpargument getarguments getargument setalwaysencoded executesampler expectedpostbody titlevalue descriptionvalue checkpostrequestbody samplerdefaultencoding contentencoding expectedpostbody createhttpsampler samplertype contentencoding titlevalue descriptionvalue setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue executesampler expectedpostbody titlevalue descriptionvalue checkpostrequestbody samplerdefaultencoding contentencoding expectedpostbody __viewstate createhttpsampler samplertype contentencoding titlevalue wepdwullte2mzm2ota0ntypzbycagmpz gndar6oshpwdjc descriptionvalue setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue httpargument getarguments getargument setalwaysencoded httpargument getarguments getargument setalwaysencoded executesampler expectedpostbody titlevalue descriptionvalue checkpostrequestbody samplerdefaultencoding contentencoding expectedpostbody httpsamplerbase addnonencodedargument createhttpsampler samplertype contentencoding titlevalue descriptionvalue setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue httpargument getarguments getargument setalwaysencoded httpargument getarguments getargument setalwaysencoded executesampler expectedpostbody titlevalue descriptionvalue checkpostrequestbody samplerdefaultencoding contentencoding expectedpostbody jmeterutils setlocale testplan testplan testplan jmetervariables jmetervariables title_prefix description_suffix the_end jmetercontextservice getcontext setvariables jmetercontextservice getcontext setsamplingstarted valuereplacer valuereplacer setuserdefinedvariables testplan getuserdefinedvariables createhttpsampler samplertype contentencoding titlevalue title_prefix descriptionvalue description_suffix setupurl contentencoding setupformdata titlefield titlevalue descriptionfield descriptionvalue httpargument getarguments getargument setalwaysencoded httpargument getarguments getargument setalwaysencoded replacevalues executesampler expectedtitlevalue expecteddescriptionvalue u00c5the_end expectedpostbody expectedtitlevalue expecteddescriptionvalue checkpostrequestbody samplerdefaultencoding contentencoding expectedpostbody private void test get request int sampler type throws exception test sending simple http get test sending data with default encoding http sampler base sampler create http sampler sampler type string content encoding setup url sampler content encoding sampler set method http sampler base get http sample result res execute sampler sampler check get request sampler res test sending data with iso 8859 1 encoding sampler create http sampler sampler type content encoding iso 8859 1 setup url sampler content encoding sampler set method http sampler base get res execute sampler sampler check get request sampler res test sending data with utf 8 encoding sampler create http sampler sampler type content encoding utf 8 setup url sampler content encoding sampler set method http sampler base get res execute sampler sampler check get request sampler res testgetrequest samplertype httpsamplerbase createhttpsampler samplertype contentencoding setupurl contentencoding setmethod httpsamplerbase httpsampleresult executesampler checkgetrequest createhttpsampler samplertype contentencoding iso_8859_1 setupurl contentencoding setmethod httpsamplerbase executesampler checkgetrequest createhttpsampler samplertype contentencoding setupurl contentencoding setmethod httpsamplerbase executesampler checkgetrequest private void testgetrequest parameters int sampler type throws exception string title field title string title value mytitle string description field description string description value mydescription test sending simple http get test sending data with default encoding http sampler base sampler create http sampler sampler type string content encoding setup url sampler content encoding sampler set method http sampler base get setup form data sampler false title field title value description field description value http sample result res execute sampler sampler sampler set running version true url executed url sampler get url sampler set running version false checkgetrequest parameters sampler res content encoding executed url title field title value description field description value false test sending data with iso 8859 1 encoding sampler create http sampler sampler type content encoding iso 8859 1 title value mytitle uc385 description value mydescription uc385 setup url sampler content encoding sampler set method http sampler base get setup form data sampler false title field title value description field description value res execute sampler sampler sampler set running version true executed url sampler get url sampler set running version false checkgetrequest parameters sampler res content encoding executed url title field title value description field description value false test sending data with utf 8 encoding sampler create http sampler sampler type content encoding utf 8 title value mytitle u0153 u20a1 u0115 u00c5 description value mydescription u0153 u20a1 u0115 u00c5 setup url sampler content encoding sampler set method http sampler base get setup form data sampler false title field title value description field description value res execute sampler sampler sampler set running version true executed url sampler get url sampler set running version false checkgetrequest parameters sampler res content encoding executed url title field title value description field description value false test sending data as utf 8 with values that changes when urlencoded sampler create http sampler sampler type content encoding utf 8 title value mytitle u0153 u20a1 u0115 yes u00c5 description value mydescription u0153 u20a1 u0115 u00c5 setup url sampler content encoding sampler set method http sampler base get setup form data sampler false title field title value description field description value res execute sampler sampler sampler set running version true executed url sampler get url sampler set running version false string expected title value mytitle u0153 2b u20a1 u0115 26yes u00c5 string expected description value mydescription u0153 u20a1 u0115 u00c5 checkgetrequest parameters sampler res content encoding executed url title field title value description field description value false test sending data as utf 8 with values that have been urlencoded sampler create http sampler sampler type content encoding utf 8 title value mytitle 2f 3d description value mydescription 2f 5c setup url sampler content encoding sampler set method http sampler base get setup form data sampler true title field title value description field description value res execute sampler sampler sampler set running version true executed url sampler get url sampler set running version false checkgetrequest parameters sampler res content encoding executed url title field title value description field description value true test sending data as utf 8 where user defined variables are used to set the value for form data j meter utils set locale locale english test plan test plan new test plan j meter variables vars new j meter variables vars put title prefix a test u00c5 vars put description suffix the end j meter context service get context set variables vars j meter context service get context set sampling started true value replacer replacer new value replacer replacer set user defined variables test plan get user defined variables sampler create http sampler sampler type content encoding utf 8 title value title prefix mytitle u0153 u20a1 u0115 u00c5 description value mydescription u0153 u20a1 u0115 u00c5 description suffix setup url sampler content encoding sampler set method http sampler base get setup form data sampler false title field title value description field description value replace the variables in the sampler replacer replace values sampler res execute sampler sampler expected title value a test u00c5mytitle u0153 u20a1 u0115 u00c5 expected description value mydescription u0153 u20a1 u0115 u00c5the end sampler set running version true executed url sampler get url sampler set running version false checkgetrequest parameters sampler res content encoding executed url title field expected title value description field expected description value false testgetrequest_parameters samplertype titlefield titlevalue descriptionfield descriptionvalue httpsamplerbase createhttpsampler samplertype contentencoding setupurl contentencoding setmethod httpsamplerbase setupformdata titlefield titlevalue descriptionfield descriptionvalue httpsampleresult executesampler setrunningversion executedurl geturl setrunningversion checkgetrequest_parameters contentencoding executedurl titlefield titlevalue descriptionfield descriptionvalue createhttpsampler samplertype contentencoding iso_8859_1 titlevalue descriptionvalue setupurl contentencoding setmethod httpsamplerbase setupformdata titlefield titlevalue descriptionfield descriptionvalue executesampler setrunningversion executedurl geturl setrunningversion checkgetrequest_parameters contentencoding executedurl titlefield titlevalue descriptionfield descriptionvalue createhttpsampler samplertype contentencoding titlevalue descriptionvalue setupurl contentencoding setmethod httpsamplerbase setupformdata titlefield titlevalue descriptionfield descriptionvalue executesampler setrunningversion executedurl geturl setrunningversion checkgetrequest_parameters contentencoding executedurl titlefield titlevalue descriptionfield descriptionvalue createhttpsampler samplertype contentencoding titlevalue descriptionvalue setupurl contentencoding setmethod httpsamplerbase setupformdata titlefield titlevalue descriptionfield descriptionvalue executesampler setrunningversion executedurl geturl setrunningversion expectedtitlevalue expecteddescriptionvalue checkgetrequest_parameters contentencoding executedurl titlefield titlevalue descriptionfield descriptionvalue createhttpsampler samplertype contentencoding titlevalue descriptionvalue setupurl contentencoding setmethod httpsamplerbase setupformdata titlefield titlevalue descriptionfield descriptionvalue executesampler setrunningversion executedurl geturl setrunningversion checkgetrequest_parameters contentencoding executedurl titlefield titlevalue descriptionfield descriptionvalue jmeterutils setlocale testplan testplan testplan jmetervariables jmetervariables title_prefix description_suffix the_end jmetercontextservice getcontext setvariables jmetercontextservice getcontext setsamplingstarted valuereplacer valuereplacer setuserdefinedvariables testplan getuserdefinedvariables createhttpsampler samplertype contentencoding titlevalue title_prefix descriptionvalue description_suffix setupurl contentencoding setmethod httpsamplerbase setupformdata titlefield titlevalue descriptionfield descriptionvalue replacevalues executesampler expectedtitlevalue expecteddescriptionvalue u00c5the_end setrunningversion executedurl geturl setrunningversion checkgetrequest_parameters contentencoding executedurl titlefield expectedtitlevalue descriptionfield expecteddescriptionvalue private http sample result execute sampler http sampler base sampler sampler set running version true sampler thread started http sample result res http sample result sampler sample sampler thread finished sampler set running version false return res httpsampleresult executesampler httpsamplerbase setrunningversion threadstarted httpsampleresult httpsampleresult threadfinished setrunningversion private void check post request url encoded http sampler base sampler http sample result res string sampler default encoding string content encoding string title field string title value string description field string description value boolean values already url encoded throws io exception if content encoding null content encoding length 0 content encoding sampler default encoding check url assert equals sampler get url res geturl string expected post body null if values already url encoded string expected title url encoder encode title value content encoding string expected description url encoder encode description value content encoding expected post body title field expected title description field expected description else expected post body title field title value description field description value check the request check post request body sampler res sampler default encoding content encoding expected post body checkpostrequesturlencoded httpsamplerbase httpsampleresult samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue valuesalreadyurlencoded ioexception contentencoding contentencoding contentencoding samplerdefaultencoding assertequals geturl expectedpostbody valuesalreadyurlencoded expectedtitle urlencoder titlevalue contentencoding expecteddescription urlencoder descriptionvalue contentencoding expectedpostbody titlefield expectedtitle descriptionfield expecteddescription expectedpostbody titlefield titlevalue descriptionfield descriptionvalue checkpostrequestbody samplerdefaultencoding contentencoding expectedpostbody private void check post request form multipart http sampler base sampler http sample result res string sampler default encoding string content encoding string title field string title value string description field string description value throws io exception if content encoding null content encoding length 0 content encoding sampler default encoding check url assert equals sampler get url res geturl string boundary string get boundary string from content type res get request headers assert not null boundary string byte expected post body create expected formdata output boundary string content encoding title field title value description field description value true true check request headers check header type length res get request headers multipart form data boundary boundary string expected post body length check post body from the result query string check arrays have same content expected post body res get query string get bytes content encoding find the data sent to the mirror server which the mirror server is sending back to us string data sent to mirror server new string res get response data content encoding int pos divider headers and body get position of body data sent to mirror server string headers sent null string body sent null if pos divider headers and body 0 headers sent data sent to mirror server substring 0 pos divider headers and body skip the blank line with crlf dividing headers and body body sent data sent to mirror server substring pos divider headers and body 2 else fail no header and body section found check response headers check header type length headers sent multipart form data boundary boundary string expected post body length check post body which was sent to the mirror server and sent back by the mirror server check arrays have same content expected post body body sent get bytes content encoding check method path and query sent check method path query headers sent sampler get method sampler get path null checkpostrequestformmultipart httpsamplerbase httpsampleresult samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue ioexception contentencoding contentencoding contentencoding samplerdefaultencoding assertequals geturl boundarystring getboundarystringfromcontenttype getrequestheaders assertnotnull boundarystring expectedpostbody createexpectedformdataoutput boundarystring contentencoding titlefield titlevalue descriptionfield descriptionvalue checkheadertypelength getrequestheaders boundarystring expectedpostbody checkarrayshavesamecontent expectedpostbody getquerystring getbytes contentencoding datasenttomirrorserver getresponsedata contentencoding posdividerheadersandbody getpositionofbody datasenttomirrorserver headerssent bodysent posdividerheadersandbody headerssent datasenttomirrorserver posdividerheadersandbody bodysent datasenttomirrorserver posdividerheadersandbody checkheadertypelength headerssent boundarystring expectedpostbody checkarrayshavesamecontent expectedpostbody bodysent getbytes contentencoding checkmethodpathquery headerssent getmethod getpath private void check post request file upload http sampler base sampler http sample result res string sampler default encoding string content encoding string title field string title value string description field string description value string file field file file value string file mime type byte file content throws io exception if content encoding null content encoding length 0 content encoding sampler default encoding check url assert equals sampler get url res geturl string boundary string get boundary string from content type res get request headers assert not null boundary string byte expected post body create expected form and upload output boundary string content encoding title field title value description field description value file field file value file mime type file content check request headers check header type length res get request headers multipart form data boundary boundary string expected post body length we cannot check post body from the result query string since that will not contain the actual file content but placeholder text for file content check arrays have same content expected post body res get query string get bytes content encoding find the data sent to the mirror server which the mirror server is sending back to us string headers sent get headers sent res get response data if headers sent null fail no header and body section found check response headers check header type length headers sent multipart form data boundary boundary string expected post body length byte body sent get body sent res get response data assert not null sent body should not be null body sent check post body which was sent to the mirror server and sent back by the mirror server check arrays have same content expected post body body sent check method path and query sent check method path query headers sent sampler get method sampler get path null checkpostrequestfileupload httpsamplerbase httpsampleresult samplerdefaultencoding contentencoding titlefield titlevalue descriptionfield descriptionvalue filefield filevalue filemimetype filecontent ioexception contentencoding contentencoding contentencoding samplerdefaultencoding assertequals geturl boundarystring getboundarystringfromcontenttype getrequestheaders assertnotnull boundarystring expectedpostbody createexpectedformanduploadoutput boundarystring contentencoding titlefield titlevalue descriptionfield descriptionvalue filefield filevalue filemimetype filecontent checkheadertypelength getrequestheaders boundarystring expectedpostbody checkarrayshavesamecontent expectedpostbody getquerystring getbytes contentencoding headerssent getheaderssent getresponsedata headerssent checkheadertypelength headerssent boundarystring expectedpostbody bodysent getbodysent getresponsedata assertnotnull bodysent checkarrayshavesamecontent expectedpostbody bodysent checkmethodpathquery headerssent getmethod getpath private void check post request body http sampler base sampler http sample result res string sampler default encoding string content encoding string expected post body throws io exception if content encoding null content encoding length 0 content encoding sampler default encoding check url assert equals sampler get url res geturl check request headers check header type length res get request headers http sampler base application x www form urlencoded expected post body get bytes content encoding length check post body from the result query string check arrays have same content expected post body get bytes content encoding res get query string get bytes content encoding find the data sent to the mirror server which the mirror server is sending back to us string data sent to mirror server new string res get response data content encoding int pos divider headers and body get position of body data sent to mirror server string headers sent null string body sent null if pos divider headers and body 0 headers sent data sent to mirror server substring 0 pos divider headers and body skip the blank line with crlf dividing headers and body body sent data sent to mirror server substring pos divider headers and body 2 else fail no header and body section found check response headers check header type length headers sent http sampler base application x www form urlencoded expected post body get bytes content encoding length check post body which was sent to the mirror server and sent back by the mirror server check arrays have same content expected post body get bytes content encoding body sent get bytes content encoding check method path and query sent check method path query headers sent sampler get method sampler get path null checkpostrequestbody httpsamplerbase httpsampleresult samplerdefaultencoding contentencoding expectedpostbody ioexception contentencoding contentencoding contentencoding samplerdefaultencoding assertequals geturl checkheadertypelength getrequestheaders httpsamplerbase application_x_www_form_urlencoded expectedpostbody getbytes contentencoding checkarrayshavesamecontent expectedpostbody getbytes contentencoding getquerystring getbytes contentencoding datasenttomirrorserver getresponsedata contentencoding posdividerheadersandbody getpositionofbody datasenttomirrorserver headerssent bodysent posdividerheadersandbody headerssent datasenttomirrorserver posdividerheadersandbody bodysent datasenttomirrorserver posdividerheadersandbody checkheadertypelength headerssent httpsamplerbase application_x_www_form_urlencoded expectedpostbody getbytes contentencoding checkarrayshavesamecontent expectedpostbody getbytes contentencoding bodysent getbytes contentencoding checkmethodpathquery headerssent getmethod getpath private void check get request http sampler base sampler http sample result res throws io exception check url assert equals sampler get url res geturl check method assert equals sampler get method res gethttp method check that the query string is empty assert equals 0 res get query string length find the data sent to the mirror server which the mirror server is sending back to us string data sent to mirror server new string res get response data encoder cache url argument encoding int pos divider headers and body get position of body data sent to mirror server string headers sent null string body sent null if pos divider headers and body 0 headers sent data sent to mirror server substring 0 pos divider headers and body skip the blank line with crlf dividing headers and body body sent data sent to mirror server substring pos divider headers and body 2 else fail no header and body section found no body should have been sent assert equals body sent length 0 check method path and query sent check method path query headers sent sampler get method sampler get path null checkgetrequest httpsamplerbase httpsampleresult ioexception assertequals geturl assertequals getmethod gethttpmethod assertequals getquerystring datasenttomirrorserver getresponsedata encodercache url_argument_encoding posdividerheadersandbody getpositionofbody datasenttomirrorserver headerssent bodysent posdividerheadersandbody headerssent datasenttomirrorserver posdividerheadersandbody bodysent datasenttomirrorserver posdividerheadersandbody assertequals bodysent checkmethodpathquery headerssent getmethod getpath private void checkgetrequest parameters http sampler base sampler http sample result res string content encoding url executed url string title field string title value string description field string description value boolean values already url encoded throws io exception if content encoding null content encoding length 0 content encoding encoder cache url argument encoding check url assert equals executed url res geturl check method assert equals sampler get method res gethttp method cannot check the query string of the result because the mirror server replies without including query string in url string expected query string null if values already url encoded string expected title url encoder encode title value content encoding string expected description url encoder encode description value content encoding expected query string title field expected title description field expected description else expected query string title field title value description field description value find the data sent to the mirror server which the mirror server is sending back to us string data sent to mirror server new string res get response data encoder cache url argument encoding int pos divider headers and body get position of body data sent to mirror server string headers sent null string body sent null if pos divider headers and body 0 headers sent data sent to mirror server substring 0 pos divider headers and body skip the blank line with crlf dividing headers and body body sent data sent to mirror server substring pos divider headers and body 2 else fail no header and body section found no body should have been sent assert equals body sent length 0 check method path and query sent check method path query headers sent sampler get method sampler get path expected query string checkgetrequest_parameters httpsamplerbase httpsampleresult contentencoding executedurl titlefield titlevalue descriptionfield descriptionvalue valuesalreadyurlencoded ioexception contentencoding contentencoding contentencoding encodercache url_argument_encoding assertequals executedurl assertequals getmethod gethttpmethod expectedquerystring valuesalreadyurlencoded expectedtitle urlencoder titlevalue contentencoding expecteddescription urlencoder descriptionvalue contentencoding expectedquerystring titlefield expectedtitle descriptionfield expecteddescription expectedquerystring titlefield titlevalue descriptionfield descriptionvalue datasenttomirrorserver getresponsedata encodercache url_argument_encoding posdividerheadersandbody getpositionofbody datasenttomirrorserver headerssent bodysent posdividerheadersandbody headerssent datasenttomirrorserver posdividerheadersandbody bodysent datasenttomirrorserver posdividerheadersandbody assertequals bodysent checkmethodpathquery headerssent getmethod getpath expectedquerystring private void check method path query string headers sent string expected method string expected path string expected query string throws io exception check the request uri sent to the mirror server and sent back by the mirror server int index first space headers sent index of int index second space headers sent index of headers sent length index first space index first space 1 index first space if index first space 0 index second space 0 index first space index second space fail could not find method and uri sent string method sent headers sent substring 0 index first space assert equals expected method method sent string uri sent headers sent substring index first space 1 index second space int index query start uri sent index of if expected query string null expected query string length 0 we should have a query string part if index query start 0 index query start uri sent length 1 fail could not find query string in uri else if index query start 0 we should not have a query string part fail query string present in uri else index query start uri sent length check path string path sent uri sent substring 0 index query start assert equals expected path path sent check query if expected query string null expected query string length 0 string query string sent uri sent substring index query start 1 is it only the parameter values which are encoded in the specified content encoding the rest of the query is encoded in utf 8 therefore we compare the whole query using utf 8 check arrays have same content expected query string get bytes encoder cache url argument encoding query string sent get bytes encoder cache url argument encoding checkmethodpathquery headerssent expectedmethod expectedpath expectedquerystring ioexception indexfirstspace headerssent indexof indexsecondspace headerssent indexof headerssent indexfirstspace indexfirstspace indexfirstspace indexfirstspace indexsecondspace indexfirstspace indexsecondspace methodsent headerssent indexfirstspace assertequals expectedmethod methodsent urisent headerssent indexfirstspace indexsecondspace indexquerystart urisent indexof expectedquerystring expectedquerystring indexquerystart indexquerystart urisent indexquerystart indexquerystart urisent pathsent urisent indexquerystart assertequals expectedpath pathsent expectedquerystring expectedquerystring querystringsent urisent indexquerystart checkarrayshavesamecontent expectedquerystring getbytes encodercache url_argument_encoding querystringsent getbytes encodercache url_argument_encoding private string get headers sent byte response data throws io exception find the data sent to the mirror server which the mirror server is sending back to us we assume the headers are in iso 8859 1 and the body can be in any content encoding string data sent to mirror server new string response data iso 8859 1 int pos divider headers and body get position of body data sent to mirror server string headers sent null if pos divider headers and body 0 headers sent data sent to mirror server substring 0 pos divider headers and body return headers sent getheaderssent responsedata ioexception iso_8859_1 datasenttomirrorserver responsedata iso_8859_1 posdividerheadersandbody getpositionofbody datasenttomirrorserver headerssent posdividerheadersandbody headerssent datasenttomirrorserver posdividerheadersandbody headerssent private byte get body sent byte response data throws io exception find the data sent to the mirror server which the mirror server is sending back to us we assume the headers are in iso 8859 1 and the body can be in any content encoding therefore we get the data sent in iso 8859 1 to be able to determine the end of the header part and then we just construct a byte array to hold the body part not taking encoding of the body into consideration because it can contain file data which is sent as raw byte data byte body sent null string headers sent get headers sent response data if headers sent null get the content length it tells us how much data to read todo maybe support chunked encoding then we cannot rely on content length string content length value get sent request header value headers sent http sampler base header content length int content length 1 if content length value null content length new integer content length value int value else fail did not receive any content length header body sent new byte content length system arraycopy response data response data length content length body sent 0 content length return body sent getbodysent responsedata ioexception iso_8859_1 iso_8859_1 bodysent headerssent getheaderssent responsedata headerssent contentlengthvalue getsentrequestheadervalue headerssent httpsamplerbase header_content_length contentlength contentlengthvalue contentlength contentlengthvalue intvalue bodysent contentlength responsedata responsedata contentlength bodysent contentlength bodysent private boolean is in request headers string request headers string header name string header value return check regular expression request headers header name header value isinrequestheaders requestheaders headername headervalue checkregularexpression requestheaders headername headervalue private void check header type length string request headers string content type int content len boolean typeok is in request headers request headers http sampler base header content type content type boolean lengok is in request headers request headers http sampler base header content length integer to string content len if typeok lengok fail expected type content type length content len in n request headers checkheadertypelength requestheaders contenttype contentlen isinrequestheaders requestheaders httpsamplerbase header_content_type contenttype isinrequestheaders requestheaders httpsamplerbase header_content_length tostring contentlen contenttype contentlen requestheaders private string get sent request header value string request headers string header name perl5 matcher local matcher j meter utils get matcher string expression header name d pattern pattern j meter utils get pattern expression perl5 compiler read only mask perl5 compiler case insensitive mask perl5 compiler singleline mask if local matcher matches request headers pattern the value is in the first group group 0 is the whole match return local matcher get match group 1 return null getsentrequestheadervalue requestheaders headername perl5matcher localmatcher jmeterutils getmatcher headername jmeterutils getpattern perl5compiler read_only_mask perl5compiler case_insensitive_mask perl5compiler singleline_mask localmatcher requestheaders localmatcher getmatch private boolean check regular expression string string to check string regular expression perl5 matcher local matcher j meter utils get matcher pattern pattern j meter utils get pattern regular expression perl5 compiler read only mask perl5 compiler case insensitive mask perl5 compiler singleline mask return local matcher contains string to check pattern checkregularexpression stringtocheck regularexpression perl5matcher localmatcher jmeterutils getmatcher jmeterutils getpattern regularexpression perl5compiler read_only_mask perl5compiler case_insensitive_mask perl5compiler singleline_mask localmatcher stringtocheck private int get position of body string string to check perl5 matcher local matcher j meter utils get matcher the headers and body are divided by a blank line string regular expression pattern pattern j meter utils get pattern regular expression perl5 compiler read only mask perl5 compiler case insensitive mask perl5 compiler multiline mask pattern matcher input input new pattern matcher input string to check while local matcher contains input pattern match result match local matcher get match return match begin offset 0 no divider was found return 1 getpositionofbody stringtocheck perl5matcher localmatcher jmeterutils getmatcher regularexpression jmeterutils getpattern regularexpression perl5compiler read_only_mask perl5compiler case_insensitive_mask perl5compiler multiline_mask patternmatcherinput patternmatcherinput stringtocheck localmatcher matchresult localmatcher getmatch beginoffset private string get boundary string from content type string request headers perl5 matcher local matcher j meter utils get matcher string regular expression http sampler base header content type multipart form data boundary pattern pattern j meter utils get pattern regular expression perl5 compiler read only mask perl5 compiler case insensitive mask perl5 compiler multiline mask if local matcher contains request headers pattern match result match local matcher get match return match group 1 else return null getboundarystringfromcontenttype requestheaders perl5matcher localmatcher jmeterutils getmatcher regularexpression httpsamplerbase header_content_type jmeterutils getpattern regularexpression perl5compiler read_only_mask perl5compiler case_insensitive_mask perl5compiler multiline_mask localmatcher requestheaders matchresult localmatcher getmatch private void setup url http sampler base sampler string content encoding string protocol http string domain localhost string domain localhost string path test somescript jsp sampler set protocol protocol sampler set method http sampler base post sampler set path path sampler set domain domain sampler set port mirror port sampler set content encoding content encoding setupurl httpsamplerbase contentencoding setprotocol setmethod httpsamplerbase setpath setdomain setport mirror_port setcontentencoding contentencoding setup the form data with specified values param http sampler private void setup form data http sampler base http sampler boolean is encoded string title field string title value string description field string description value if is encoded http sampler add encoded argument title field title value http sampler add encoded argument description field description value else http sampler add argument title field title value http sampler add argument description field description value httpsampler setupformdata httpsamplerbase httpsampler isencoded titlefield titlevalue descriptionfield descriptionvalue isencoded httpsampler addencodedargument titlefield titlevalue httpsampler addencodedargument descriptionfield descriptionvalue httpsampler addargument titlefield titlevalue httpsampler addargument descriptionfield descriptionvalue setup the form data with specified values and file to upload param http sampler private void setup file upload data http sampler base http sampler boolean is encoded string title field string title value string description field string description value string file field file file value string file mime type set the form data setup form data http sampler is encoded title field title value description field description value set the file upload data http sampler set file field file field http sampler set filename file value get absolute path http sampler set mimetype file mime type httpsampler setupfileuploaddata httpsamplerbase httpsampler isencoded titlefield titlevalue descriptionfield descriptionvalue filefield filevalue filemimetype setupformdata httpsampler isencoded titlefield titlevalue descriptionfield descriptionvalue httpsampler setfilefield filefield httpsampler setfilename filevalue getabsolutepath httpsampler setmimetype filemimetype check that the the two byte arrays have identical content param expected param actual throws unsupported encoding exception private void check arrays have same content byte expected byte actual throws unsupported encoding exception if expected null actual null if expected length actual length system out println system out println new string expected utf 8 system out println system out println new string actual utf 8 system out println fail arrays have different length expected is expected length actual is actual length else for int i 0 i expected length i if expected i actual i system out println system out println new string expected 0 i 1 system out println system out println new string actual 0 i 1 system out println useful to when debugging for int j 0 j expected length j system out print expected j system out println for int j 0 j actual length j system out print actual j system out println fail byte at position i is different expected is expected i actual is actual i else fail expected or actual byte arrays were null unsupportedencodingexception checkarrayshavesamecontent unsupportedencodingexception create the expected output multipart form data with only form data and no file multipart this method is copied from the post writer test class param last multipart true if this is the last multipart in the request private byte create expected formdata output string boundary string string content encoding string title field string title value string description field string description value boolean first multipart boolean last multipart throws io exception the encoding used for http headers and control information final byte dash dash new string get bytes iso 8859 1 final byte array output stream output new byte array output stream if first multipart output write dash dash output write boundary string get bytes iso 8859 1 output write crlf output write content disposition form data name get bytes iso 8859 1 output write title field get bytes iso 8859 1 output write get bytes iso 8859 1 output write crlf output write content type text plain get bytes iso 8859 1 if content encoding null output write charset get bytes iso 8859 1 output write content encoding get bytes iso 8859 1 output write crlf output write content transfer encoding 8bit get bytes iso 8859 1 output write crlf output write crlf if content encoding null output write title value get bytes content encoding else output write title value get bytes output write crlf output write dash dash output write boundary string get bytes iso 8859 1 output write crlf output write content disposition form data name get bytes iso 8859 1 output write description field get bytes iso 8859 1 output write get bytes iso 8859 1 output write crlf output write content type text plain get bytes iso 8859 1 if content encoding null output write charset get bytes iso 8859 1 output write content encoding get bytes iso 8859 1 output write crlf output write content transfer encoding 8bit get bytes iso 8859 1 output write crlf output write crlf if content encoding null output write description value get bytes content encoding else output write description value get bytes output write crlf output write dash dash output write boundary string get bytes iso 8859 1 if last multipart output write dash dash output write crlf output flush output close return output to byte array postwritertest lastmultipart createexpectedformdataoutput boundarystring contentencoding titlefield titlevalue descriptionfield descriptionvalue firstmultipart lastmultipart ioexception dash_dash getbytes iso_8859_1 bytearrayoutputstream bytearrayoutputstream firstmultipart dash_dash boundarystring getbytes iso_8859_1 getbytes iso_8859_1 titlefield getbytes iso_8859_1 getbytes iso_8859_1 getbytes iso_8859_1 contentencoding getbytes iso_8859_1 contentencoding getbytes iso_8859_1 getbytes iso_8859_1 contentencoding titlevalue getbytes contentencoding titlevalue getbytes dash_dash boundarystring getbytes iso_8859_1 getbytes iso_8859_1 descriptionfield getbytes iso_8859_1 getbytes iso_8859_1 getbytes iso_8859_1 contentencoding getbytes iso_8859_1 contentencoding getbytes iso_8859_1 getbytes iso_8859_1 contentencoding descriptionvalue getbytes contentencoding descriptionvalue getbytes dash_dash boundarystring getbytes iso_8859_1 lastmultipart dash_dash tobytearray create the expected file multipart param last multipart true if this is the last multipart in the request private byte create expected filepart output string boundary string string file field file file string mime type byte file content boolean first multipart boolean last multipart throws io exception final byte dash dash new string get bytes iso 8859 1 final byte array output stream output new byte array output stream if first multipart output write dash dash output write boundary string get bytes iso 8859 1 output write crlf replace all backslash with double backslash string filename file get name output write content disposition form data name get bytes iso 8859 1 output write file field get bytes iso 8859 1 output write filename filename get bytes iso 8859 1 output write crlf output write content type get bytes iso 8859 1 output write mime type get bytes iso 8859 1 output write crlf output write content transfer encoding binary get bytes iso 8859 1 output write crlf output write crlf output write file content output write crlf output write dash dash output write boundary string get bytes iso 8859 1 if last multipart output write dash dash output write crlf output flush output close return output to byte array lastmultipart createexpectedfilepartoutput boundarystring filefield mimetype filecontent firstmultipart lastmultipart ioexception dash_dash getbytes iso_8859_1 bytearrayoutputstream bytearrayoutputstream firstmultipart dash_dash boundarystring getbytes iso_8859_1 getname getbytes iso_8859_1 filefield getbytes iso_8859_1 getbytes iso_8859_1 getbytes iso_8859_1 mimetype getbytes iso_8859_1 getbytes iso_8859_1 filecontent dash_dash boundarystring getbytes iso_8859_1 lastmultipart dash_dash tobytearray create the expected output post body for form data and file multiparts with specified values when request is multipart private byte create expected form and upload output string boundary string string content encoding string title field string title value string description field string description value string file field file file value string file mime type byte file content throws io exception create the multiparts byte formdata multipart create expected formdata output boundary string content encoding title field title value description field description value true false byte file multipart create expected filepart output boundary string file field file value file mime type file content false true join the two multiparts byte array output stream output new byte array output stream output write formdata multipart output write file multipart output flush output close return output to byte array createexpectedformanduploadoutput boundarystring contentencoding titlefield titlevalue descriptionfield descriptionvalue filefield filevalue filemimetype filecontent ioexception formdatamultipart createexpectedformdataoutput boundarystring contentencoding titlefield titlevalue descriptionfield descriptionvalue filemultipart createexpectedfilepartoutput boundarystring filefield filevalue filemimetype filecontent bytearrayoutputstream bytearrayoutputstream formdatamultipart filemultipart tobytearray private http sampler base create http sampler int sampler type if sampler type http sampler2 return new http sampler2 else return new http sampler httpsamplerbase createhttpsampler samplertype samplertype http_sampler2 httpsampler2 httpsampler private cookie manager man null public test cookie manager string name super name cookiemanager testcookiemanager public void set up throws exception super set up jmctx j meter context service get context man new cookie manager man set thread context jmctx man test started this is needed in order to set up the cookie policy setup setup jmetercontextservice getcontext cookiemanager setthreadcontext teststarted public void test remove cookie throws exception man set thread context jmctx cookie c new cookie id me 127 0 0 1 false 0 man add c assert equals 1 man get cookie count this should be ignored as there is no value cookie d new cookie id 127 0 0 1 false 0 man add d assert equals 0 man get cookie count man add c man add c assert equals 1 man get cookie count cookie e new cookie id me2 127 0 0 1 false 0 man add e assert equals 1 man get cookie count testremovecookie setthreadcontext assertequals getcookiecount assertequals getcookiecount assertequals getcookiecount assertequals getcookiecount public void test send cookie throws exception man add new cookie id value jakarta apache org false 9999999999l http sampler base sampler new http null sampler sampler set domain jakarta apache org sampler set path index html sampler set method http sampler base get assert not null man get cookie header forurl sampler get url testsendcookie httpsamplerbase httpnullsampler setdomain setpath setmethod httpsamplerbase assertnotnull getcookieheaderforurl geturl public void test send cookie2 throws exception man add new cookie id value apache org false 9999999999l http sampler base sampler new http null sampler sampler set domain jakarta apache org sampler set path index html sampler set method http sampler base get assert not null man get cookie header forurl sampler get url testsendcookie2 httpsamplerbase httpnullsampler setdomain setpath setmethod httpsamplerbase assertnotnull getcookieheaderforurl geturl test that the cookie domain field is actually handled as browsers do i e host x matches domain x public void test domain handling throws exception url url new url http jakarta apache org man add cookie from header test 1 domain jakarta apache org url assert not null man get cookie header forurl url testdomainhandling addcookiefromheader assertnotnull getcookieheaderforurl public void test cross domain handling throws exception url url new url http jakarta apache org assert equals 0 man get cookie count starts empty man add cookie from header test 2 domain hc apache org url assert equals 0 man get cookie count should not be stored man add cookie from header test 1 domain jakarta apache org url assert equals 1 man get cookie count ok testcrossdomainhandling assertequals getcookiecount addcookiefromheader assertequals getcookiecount addcookiefromheader assertequals getcookiecount test that we won t be tricked by similar host names this was a past bug although it never got reported in the bug database public void test similar host names throws exception url url new url http ache org man add cookie from header test 1 url url new url http jakarta apache org assert null man get cookie header forurl url testsimilarhostnames addcookiefromheader assertnull getcookieheaderforurl test session cookie is returned public void test session cookie throws exception url url new url http a b c man add cookie from header test 1 url string s man get cookie header forurl url assert not null s assert equals test 1 s testsessioncookie addcookiefromheader getcookieheaderforurl assertnotnull assertequals bug 2063 public void test cookie with equals throws exception url url new url http a b c man add cookie from header nscp user login1 new sha xxxxx url string s man get cookie header forurl url assert not null s assert equals nscp user login1 new sha xxxxx s cookie c man get 0 assert equals nscp user login1 new c get name assert equals sha xxxxx c get value testcookiewithequals addcookiefromheader nscp_user_login1_new getcookieheaderforurl assertnotnull assertequals nscp_user_login1_new assertequals nscp_user_login1_new getname assertequals getvalue test old cookie is not returned public void test old cookie throws exception url url new url http a b c man add cookie from header test 1 expires mon 01 jan 1990 00 00 00 gmt url string s man get cookie header forurl url assert null s testoldcookie addcookiefromheader getcookieheaderforurl assertnull test new cookie is returned public void test new cookie throws exception url url new url http a b c man add cookie from header test 1 expires mon 01 jan 2990 00 00 00 gmt url assert equals 1 man get cookie count string s man get cookie header forurl url assert not null s assert equals test 1 s testnewcookie addcookiefromheader assertequals getcookiecount getcookieheaderforurl assertnotnull assertequals test multi cookie header handling public void test cookies1 throws exception url url new url http a b c d test cookies1 man add cookie from header test1 1 comment how now test2 2 version 1 url assert equals 2 man get cookie count string s man get cookie header forurl url assert not null s assert equals test1 1 test2 2 s testcookies1 testcookies1 addcookiefromheader assertequals getcookiecount getcookieheaderforurl assertnotnull assertequals public void test cookies2 throws exception url url new url https a b c d test cookies2 man add cookie from header test1 1 secure test2 2 secure url assert equals 2 man get cookie count string s man get cookie header forurl url assert not null s assert equals test1 1 test2 2 s testcookies2 testcookies2 addcookiefromheader assertequals getcookiecount getcookieheaderforurl assertnotnull assertequals test duplicate cookie handling public void test duplicate cookie throws exception url url new url http a b c man add cookie from header test 1 url string s man get cookie header forurl url assert not null s assert equals test 1 s man add cookie from header test 2 url s man get cookie header forurl url assert not null s assert equals test 2 s testduplicatecookie addcookiefromheader getcookieheaderforurl assertnotnull assertequals addcookiefromheader getcookieheaderforurl assertnotnull assertequals public void test duplicate cookie2 throws exception url url new url http a b c man add cookie from header test 1 url man add cookie from header test2 a url string s man get cookie header forurl url assert not null s assert equals test 1 test2 a s assumes some kind of list is used man add cookie from header test 2 url man add cookie from header test3 b url s man get cookie header forurl url assert not null s assert equals test2 a test 2 test3 b s assumes some kind of list is use if not using a list that retains the order then the asserts would need to change testduplicatecookie2 addcookiefromheader addcookiefromheader getcookieheaderforurl assertnotnull assertequals addcookiefromheader addcookiefromheader getcookieheaderforurl assertnotnull assertequals tests missing cookie path for a trivial url fetch from the domain note that this fails prior to a fix for bug 38256 public void test missing path0 throws exception url url new url http d e f goo html man add cookie from header test moo url string s man get cookie header forurl new url http d e f assert not null s assert equals test moo s testmissingpath0 addcookiefromheader getcookieheaderforurl assertnotnull assertequals tests missing cookie path for a non trivial url fetch from the domain note that this fails prior to a fix for bug 38256 public void test missing path1 throws exception url url new url http d e f moo html man add cookie from header test moo url string s man get cookie header forurl new url http d e f goo html assert not null s assert equals test moo s testmissingpath1 addcookiefromheader getcookieheaderforurl assertnotnull assertequals tests explicit root path with a trivial url fetch from the domain public void test root path0 throws exception url url new url http d e f goo html man add cookie from header test moo path url string s man get cookie header forurl new url http d e f assert not null s assert equals test moo s testrootpath0 addcookiefromheader getcookieheaderforurl assertnotnull assertequals tests explicit root path with a non trivial url fetch from the domain public void test root path1 throws exception url url new url http d e f moo html man add cookie from header test moo path url string s man get cookie header forurl new url http d e f goo html assert not null s assert equals test moo s testrootpath1 addcookiefromheader getcookieheaderforurl assertnotnull assertequals test cookie matching public void test cookie matching throws exception url url new url http a b c 8080 top dir fred jsp man add cookie from header id abcd path top dir url string s man get cookie header forurl url assert not null s assert equals id abcd s url new url http a b c 8080 other jsp s man get cookie header forurl url assert null s url new url http a b c 8080 top dir suub another jsp s man get cookie header forurl url assert not null s url new url http a b c 8080 top dir s man get cookie header forurl url assert not null s url new url http a b d s man get cookie header forurl url assert null s testcookiematching topdir addcookiefromheader topdir getcookieheaderforurl assertnotnull assertequals getcookieheaderforurl assertnull topdir getcookieheaderforurl assertnotnull topdir getcookieheaderforurl assertnotnull getcookieheaderforurl assertnull public void test cookie ordering1 throws exception url url new url http order now sub1 moo html man add cookie from header test1 moo1 path url man add cookie from header test2 moo2 path sub1 url man add cookie from header test2 moo3 path url assert equals 3 man get cookie count string s man get cookie header forurl url assert not null s assert equals test2 moo2 test1 moo1 test2 moo3 s testcookieordering1 addcookiefromheader addcookiefromheader addcookiefromheader assertequals getcookiecount getcookieheaderforurl assertnotnull assertequals public void test cookie ordering2 throws exception url url new url http order now sub1 moo html man add cookie from header test1 moo1 url man add cookie from header test2 moo2 path sub1 url man add cookie from header test2 moo3 path url assert equals 3 man get cookie count assert equals sub1 man get 0 get path defaults to caller url assert equals sub1 man get 1 get path assert equals man get 2 get path string s man get cookie header forurl url assert not null s org apache commons httpclient cookie c man get cookies for url url assert equals sub1 c 0 get path assert false c 0 is path attribute specified assert equals sub1 c 1 get path assert true c 1 is path attribute specified assert equals c 2 get path assert equals test1 moo1 test2 moo2 test2 moo3 s testcookieordering2 addcookiefromheader addcookiefromheader addcookiefromheader assertequals getcookiecount assertequals getpath assertequals getpath assertequals getpath getcookieheaderforurl assertnotnull getcookiesforurl assertequals getpath assertfalse ispathattributespecified assertequals getpath asserttrue ispathattributespecified assertequals getpath assertequals public void test cookie policy2109 throws exception man set cookie policy cookie policy rfc 2109 man test started ensure policy is picked up url url new url http order now sub1 moo html man add cookie from header test1 moo1 url man add cookie from header test2 moo2 path sub1 url man add cookie from header test2 moo3 path url assert equals 3 man get cookie count assert equals man get 0 get path assert equals sub1 man get 1 get path assert equals man get 2 get path string s man get cookie header forurl url assert not null s org apache commons httpclient cookie c man get cookies for url url assert equals sub1 c 0 get path assert false c 0 is path attribute specified assert equals sub1 c 1 get path assert true c 1 is path attribute specified assert equals c 2 get path assert true c 2 is path attribute specified assert equals version 0 test1 moo1 test2 moo2 path sub1 test2 moo3 path s testcookiepolicy2109 setcookiepolicy cookiepolicy rfc_2109 teststarted addcookiefromheader addcookiefromheader addcookiefromheader assertequals getcookiecount assertequals getpath assertequals getpath assertequals getpath getcookieheaderforurl assertnotnull getcookiesforurl assertequals getpath assertfalse ispathattributespecified assertequals getpath asserttrue ispathattributespecified assertequals getpath asserttrue ispathattributespecified assertequals public void test cookie policy netscape throws exception man set cookie policy cookie policy netscape man test started ensure policy is picked up url url new url http www order now sub1 moo html man add cookie from header test1 moo1 url man add cookie from header test2 moo2 path sub1 url man add cookie from header test2 moo3 path url assert equals 3 man get cookie count assert equals sub1 man get 0 get path assert equals sub1 man get 1 get path assert equals man get 2 get path string s man get cookie header forurl url assert not null s org apache commons httpclient cookie c man get cookies for url url assert equals sub1 c 0 get path assert false c 0 is path attribute specified assert equals sub1 c 1 get path assert true c 1 is path attribute specified assert equals c 2 get path assert true c 2 is path attribute specified assert equals test1 moo1 test2 moo2 test2 moo3 s testcookiepolicynetscape setcookiepolicy cookiepolicy teststarted addcookiefromheader addcookiefromheader addcookiefromheader assertequals getcookiecount assertequals getpath assertequals getpath assertequals getpath getcookieheaderforurl assertnotnull getcookiesforurl assertequals getpath assertfalse ispathattributespecified assertequals getpath asserttrue ispathattributespecified assertequals getpath asserttrue ispathattributespecified assertequals public void test cookie policy ignore throws exception man set cookie policy cookie policy ignore cookies man test started ensure policy is picked up url url new url http order now sub1 moo html man add cookie from header test1 moo1 url man add cookie from header test2 moo2 path sub1 url man add cookie from header test2 moo3 path url assert equals 0 man get cookie count cookies are ignored cookie cc cc new cookie test1 moo1 null sub1 false 0 false false man add cc cc new cookie test2 moo2 null sub1 false 0 true false man add cc cc new cookie test3 moo3 null false 0 false false man add cc assert equals 3 man get cookie count assert equals sub1 man get 0 get path assert equals sub1 man get 1 get path assert equals man get 2 get path string s man get cookie header forurl url assert null s org apache commons httpclient cookie c man get cookies for url url assert equals 0 c length cookies again ignored testcookiepolicyignore setcookiepolicy cookiepolicy ignore_cookies teststarted addcookiefromheader addcookiefromheader addcookiefromheader assertequals getcookiecount assertequals getcookiecount assertequals getpath assertequals getpath assertequals getpath getcookieheaderforurl assertnull getcookiesforurl assertequals public void test load throws exception assert equals 0 man get cookie count man add file testfiles cookies txt assert equals 3 man get cookie count int num 0 assert equals name man get num get name assert equals value man get num get value assert equals path man get num get path assert equals domain man get num get domain assert true man get num get secure assert equals num man get num get expires num assert equals name2 man get num get name assert equals value2 man get num get value assert equals man get num get path assert equals man get num get domain assert false man get num get secure assert equals 0 man get num get expires num assert equals a man get num get name assert equals b man get num get value assert equals d man get num get path assert equals c man get num get domain assert true man get num get secure assert equals 0 man get num get expires show that maxlong now saved as 0 testload assertequals getcookiecount addfile assertequals getcookiecount assertequals getname assertequals getvalue assertequals getpath assertequals getdomain asserttrue getsecure assertequals getexpires assertequals getname assertequals getvalue assertequals getpath assertequals getdomain assertfalse getsecure assertequals getexpires assertequals getname assertequals getvalue assertequals getpath assertequals getdomain asserttrue getsecure assertequals getexpires public class bsf post processor bean info extends bsf bean info support public bsf post processor bean info super bsf post processor class bsfpostprocessorbeaninfo bsfbeaninfosupport bsfpostprocessorbeaninfo bsfpostprocessor public final class test menu factory extends j meter test case public test menu factory super testmenufactory jmetertestcase testmenufactory public test menu factory string name super name testmenufactory private static void check string s int i throws exception assert false the number of s should not be 0 0 i assertfalse public void test menu throws exception check menumap menu factory menumap size check assertions menu factory assertions size check config elements menu factory configelements size check controllers menu factory controllers size check listeners menu factory listeners size check non test elements menu factory nontestelements size check post processors menu factory postprocessors size check pre processors menu factory preprocessors size check samplers menu factory samplers size check timers menu factory timers size check elementstoskip menu factory elementstoskip size testmenu menufactory menumap_size menufactory assertions_size configelements menufactory configelements_size menufactory controllers_size menufactory listeners_size nontestelements menufactory nontestelements_size postprocessors menufactory postprocessors_size preprocessors menufactory preprocessors_size menufactory samplers_size menufactory timers_size menufactory elementstoskip_size constructor for the exit command object public report exit command exitcommand reportexitcommand gets the action names attribute of the exit command object return the action names value public set get action names return commands actionnames exitcommand actionnames getactionnames description of the method param e description of parameter public void do action action event e report action router get instance do action now new action event e get source e getid report check dirty check dirty if report gui package get instance is dirty int chosen option j option pane show confirm dialog report gui package get instance get main frame j meter utils get res string cancel exit to save j meter utils get res string save j option pane yes no cancel option j option pane question message if chosen option j option pane no option system exit 0 else if chosen option j option pane yes option report action router get instance do action now new action event e get source e getid report save save all as if report gui package get instance is dirty system exit 0 else system exit 0 doaction actionevent reportactionrouter getinstance doactionnow actionevent getsource reportcheckdirty check_dirty reportguipackage getinstance isdirty chosenoption joptionpane showconfirmdialog reportguipackage getinstance getmainframe jmeterutils getresstring cancel_exit_to_save jmeterutils getresstring joptionpane yes_no_cancel_option joptionpane question_message chosenoption joptionpane no_option chosenoption joptionpane yes_option reportactionrouter getinstance doactionnow actionevent getsource reportsave save_all_as reportguipackage getinstance isdirty the cache of tcp connections private static final thread local tp new thread local protected object initial value return new hash map threadlocal threadlocal initialvalue hashmap private transient tcp client protocol handler public tcp sampler log debug created this non nls 1 tcpclient protocolhandler tcpsampler private string get error map cp map tp get return string cp get errkey geterror private socket get socket map cp map tp get socket con null if is re use connection con socket cp get tcpkey if con null log debug this reusing connection con non nls 1 return con not in cache so create new one and cache it try close socket bug 44910 close previous socket if any con new socket get server get port con set so timeout get timeout con set tcp no delay get no delay log debug this timeout get timeout no delay get no delay non nls 1 log debug created new connection con non nls 1 cp put tcpkey con catch unknown host exception e log warn unknown host for get label e non nls 1 cp put errkey e to string catch io exception e log warn could not create socket for get label e non nls 1 cp put errkey e to string return con getsocket isreuseconnection closesocket getserver getport setsotimeout gettimeout settcpnodelay getnodelay gettimeout nodelay getnodelay unknownhostexception getlabel tostring ioexception getlabel tostring public string get username return get property as string config test element username getusername getpropertyasstring configtestelement public string get password return get property as string config test element password getpassword getpropertyasstring configtestelement public void set server string new server this set property server new server setserver newserver setproperty newserver public string get server return get property as string server getserver getpropertyasstring public void set re use connection string reuse this set property re use connection reuse setreuseconnection setproperty re_use_connection public boolean is re use connection return get property as boolean re use connection isreuseconnection getpropertyasboolean re_use_connection public void set port string new filename this set property port new filename setport newfilename setproperty newfilename public int get port return get property as int port getport getpropertyasint public void set filename string new filename this set property filename new filename setfilename newfilename setproperty newfilename public string get filename return get property as string filename getfilename getpropertyasstring public void set request data string new request data this set property request new request data setrequestdata newrequestdata setproperty newrequestdata public string get request data return get property as string request getrequestdata getpropertyasstring public void set timeout string new timeout this set property timeout new timeout settimeout newtimeout setproperty newtimeout public int get timeout return get property as int timeout gettimeout getpropertyasint public void set no delay string new no delay this set property nodelay new no delay setnodelay newnodelay setproperty newnodelay public boolean get no delay return get property as boolean nodelay getnodelay getpropertyasboolean public void set classname string classname this set property classname classname non nls 1 setclassname setproperty public string get classname string clazz get property as string classname if clazz null clazz length 0 clazz j meter utils get prop default tcp handler tcp client impl non nls 1 non nls 2 return clazz getclassname getpropertyasstring jmeterutils getpropdefault tcpclientimpl returns a formatted string label describing this sampler example output tcp tcp nowhere com pub readme txt return a formatted string label describing this sampler public string get label return tcp this get server this get port non nls 1 non nls 2 getlabel getserver getport private class get class string class name class c null try c class for name class name false thread current thread get context class loader catch class not found exception e try c class for name proto prefix class name false thread current thread get context class loader catch class not found exception e1 log error could not find protocol class class name non nls 1 return c getclass classname forname classname currentthread getcontextclassloader classnotfoundexception forname protoprefix classname currentthread getcontextclassloader classnotfoundexception classname private tcp client get protocol tcp client tcp client null class java class get class get classname if java class null return null try tcp client tcp client java class new instance if log is debug enabled log debug this created get classname integer to hex string tcp client hash code non nls 1 catch exception e log error this exception creating get classname e non nls 1 return tcp client tcpclient getprotocol tcpclient tcpclient javaclass getclass getclassname javaclass tcpclient tcpclient javaclass newinstance isdebugenabled getclassname tohexstring tcpclient hashcode getclassname tcpclient public sample result sample entry e entry tends to be ignored log debug get label get filename get username get password sample result res new sample result boolean is successful false res set sample label get name use the test element name for the label res set sampler data host get server port get port non nls 1 non nls 2 res sample start try socket sock get socket if sock null res set response code 500 non nls 1 res set response message get error else if protocol handler null res set response code 500 non nls 1 res set response message protocol handler not found else input stream is sock get input stream output stream os sock get output stream string req get request data todo handle filenames res set sampler data req protocol handler write os req string in protocol handler read is res set response data in get bytes res set data type sample result text res set response codeok res set response message ok non nls 1 is successful true reset the status code if the message contains one if status prefix length 0 int i in index of status prefix int j in index of status suffix i status prefix length if i 1 j i string rc in substring i status prefix length j res set response code rc is successful check response code rc if have status props res set response message status props get property rc status code not found in properties non nls 1 else res set response message no status property file else res set response code 999 non nls 1 res set response message status value not found is successful false catch io exception ex log debug ex res set response code 500 non nls 1 res set response message ex to string close socket finally calculate response time res sample end set if we were successful or not res set successful is successful if is re use connection close socket return res sampleresult getlabel getfilename getusername getpassword sampleresult sampleresult issuccessful setsamplelabel getname setsamplerdata getserver getport samplestart getsocket setresponsecode setresponsemessage geterror protocolhandler setresponsecode setresponsemessage inputstream getinputstream outputstream getoutputstream getrequestdata setsamplerdata protocolhandler protocolhandler setresponsedata getbytes setdatatype sampleresult setresponsecodeok setresponsemessage issuccessful status_prefix indexof status_prefix indexof status_suffix status_prefix status_prefix setresponsecode issuccessful checkresponsecode havestatusprops setresponsemessage statusprops getproperty setresponsemessage setresponsecode setresponsemessage issuccessful ioexception setresponsecode setresponsemessage tostring closesocket sampleend setsuccessful issuccessful isreuseconnection closesocket param rc response code return whether this represents success or not private boolean check response code string rc if rc compare to 400 0 rc compare to 499 0 non nls 1 non nls 2 return false if rc compare to 500 0 rc compare to 599 0 non nls 1 non nls 2 return false return true checkresponsecode compareto compareto compareto compareto public void thread started log debug thread started non nls 1 protocol handler get protocol log debug using protocol handler non nls 1 protocol handler null none protocol handler get class get name non nls 1 if protocol handler null protocol handler setup test threadstarted protocolhandler getprotocol protocolhandler protocolhandler getclass getname protocolhandler protocolhandler setuptest private void close socket map cp map tp get socket con socket cp remove tcpkey if con null log debug this closing connection con non nls 1 try con close catch io exception e log warn error closing socket e non nls 1 closesocket ioexception public void thread finished log debug thread finished non nls 1 close socket if protocol handler null protocol handler teardown test threadfinished closesocket protocolhandler protocolhandler teardowntest private static volatile int request number 0 running number public http request hdr this sampler http sampler factory new instance requestnumber httprequesthdr httpsamplerfactory newinstance param sampler the http sampler public http request hdr http sampler base sampler this sampler sampler httprequesthdr httpsamplerbase parses a http header from a stream param in the stream to parse return array of bytes from client public byte parse input stream in throws io exception boolean in headers true int read length 0 int data length 0 boolean first line true byte array output stream client request new byte array output stream byte array output stream line new byte array output stream int x while in headers read length data length x in read 1 line write x client request write x if first line char utils is ascii char x includes n throw new illegal argument exception only ascii supported in headers perhaps ssl was used if in headers byte x byte n non nls 1 if line size 3 in headers false first line false cannot be first line either if first line parse first line line to string first line false else parse other header lines looking for content length final int content len parse line line to string if content len 0 data length content len save the last valid content length one if log is debug enabled log debug client request line line to string line reset else if in headers read length keep the raw post data raw post data line to byte array if log is debug enabled log debug raw post data in default jre encoding new string raw post data log debug request client request to string return client request to byte array inputstream ioexception inheaders readlength datalength firstline bytearrayoutputstream clientrequest bytearrayoutputstream bytearrayoutputstream bytearrayoutputstream inheaders readlength datalength clientrequest firstline charutils isascii illegalargumentexception inheaders inheaders firstline firstline parsefirstline tostring firstline contentlen parseline tostring contentlen datalength contentlen isdebugenabled tostring inheaders readlength rawpostdata tobytearray isdebugenabled rawpostdata rawpostdata clientrequest tostring clientrequest tobytearray private void parse first line string first line if log is debug enabled log debug browser request first line if char utils is ascii alphanumeric first line char at 0 throw new illegal argument exception unrecognised header line probably used https string tokenizer tz new string tokenizer first line method get token tz to upper case java util locale english url get token tz if url to lower case java util locale english starts with http constants protocol https throw new illegal argument exception cannot handle https urls url version get token tz if log is debug enabled log debug parser input first line log debug parsed method method log debug parsed url url log debug parsed version version if connect equals ignore case method throw new illegal argument exception cannot handle connect probably used https parsefirstline firstline isdebugenabled firstline charutils isasciialphanumeric firstline charat illegalargumentexception stringtokenizer stringtokenizer firstline gettoken touppercase gettoken tolowercase startswith httpconstants protocol_https illegalargumentexception gettoken isdebugenabled firstline equalsignorecase illegalargumentexception private int parse line string next line int colon next line index of if colon 0 return 0 nothing to do string name next line substring 0 colon trim string value next line substring colon 1 trim headers put name to lower case java util locale english new header name value if name equals ignore case content length return integer parse int value return 0 parseline nextline nextline indexof nextline nextline tolowercase equalsignorecase content_length parseint private header manager create header manager header manager manager new header manager iterator keys headers key set iterator while keys has next string key string keys next if key equals proxy connection key equals content length manager add header headers get key manager set name j meter utils get res string header manager title non nls 1 manager set property test element test class header manager class get name manager set property test element gui class header panel class get name return manager headermanager createheadermanager headermanager headermanager keyset hasnext proxy_connection content_length setname jmeterutils getresstring header_manager_title setproperty testelement test_class headermanager getname setproperty testelement gui_class headerpanel getname public header manager get header manager if header manager null header manager create header manager return header manager headermanager getheadermanager headermanager headermanager createheadermanager headermanager public http sampler base get sampler map page encodings map form encodings throws malformedurl exception io exception damn a whole new gui just to instantiate a test element isn t there a beter way http test sample gui temp gui null create the corresponding gui for the sampler class if sampler instanceof http sampler2 temp gui new http test sample gui2 else temp gui new http test sample gui sampler set property test element gui class temp gui get class get name populate the sampler populate sampler page encodings form encodings temp gui configure sampler temp gui modify test element sampler defaults sampler set follow redirects false sampler set use keep alive true if log is debug enabled log debug get sampler sampler path sampler get path return sampler httpsamplerbase getsampler pageencodings formencodings malformedurlexception ioexception httptestsamplegui tempgui httpsampler2 tempgui httptestsamplegui2 tempgui httptestsamplegui setproperty testelement gui_class tempgui getclass getname populatesampler pageencodings formencodings tempgui tempgui modifytestelement setfollowredirects setusekeepalive isdebugenabled getsampler getpath return the sampler throws malformedurl exception throws io exception throws protocol exception deprecated use the get sampler hash map page encodings hash map form encodings instead since that properly handles the encodings of the page public http sampler base get sampler throws malformedurl exception io exception protocol exception return get sampler null null malformedurlexception ioexception protocolexception getsampler hashmap pageencodings hashmap formencodings httpsamplerbase getsampler malformedurlexception ioexception protocolexception getsampler private string get content type header content type header header headers get content type if content type header null return content type header get value return null getcontenttype contenttypeheader content_type contenttypeheader contenttypeheader getvalue private boolean is multipart string content type if content type null content type starts with http constants multipart form data return true return false ismultipart contenttype contenttype contenttype startswith httpconstants multipart_form_data private multipart url config get multipart config string content type if is multipart content type get the boundary string for the multiparts from the content type string boundary string content type substring content type to lower case java util locale english index of boundary boundary length return new multipart url config boundary string return null multiparturlconfig getmultipartconfig contenttype ismultipart contenttype boundarystring contenttype contenttype tolowercase indexof multiparturlconfig boundarystring private void populate sampler map page encodings map form encodings throws malformedurl exception unsupported encoding exception sampler set domain server name if log is debug enabled log debug proxy setting server sampler get domain sampler set method method log debug proxy setting method sampler get method sampler set port server port if log is debug enabled log debug proxy setting port sampler get port if url index of 1 string protocol url substring 0 url index of if log is debug enabled log debug proxy setting protocol to protocol sampler set protocol protocol else if sampler get port http constants default https port sampler set protocol https if log is debug enabled log debug proxy setting protocol to https else if log is debug enabled log debug proxy setting default protocol to http sampler set protocol http url page url null if sampler is protocol default port page url new url sampler get protocol sampler get domain get path else page url new url sampler get protocol sampler get domain sampler get port get path string url without query get url without query page url check if the request itself tells us what the encoding is string content encoding null string request content encoding conversion utils get encoding from content type get content type if request content encoding null content encoding request content encoding else check if we know the encoding of the page if page encodings null synchronized page encodings content encoding string page encodings get url without query check if we know the encoding of the form if form encodings null synchronized form encodings string form encoding string form encodings get url without query form encoding has priority over page encoding if form encoding null content encoding form encoding get the post data using the content encoding of the request string post data null if log is debug enabled if content encoding null log debug using encoding content encoding for request body else log debug no encoding found using jre default encoding for request body if content encoding null post data new string raw post data content encoding else use default encoding post data new string raw post data if content encoding null sampler set path get path content encoding else although the spec says utf 8 should be used for encoding url parameters most browser use iso 8859 1 for default if encoding is not known we use null for content encoding then the url parameters will be added with the value in the url and the encode flag set to false sampler set path get path null if log is debug enabled log debug proxy setting path sampler get path if number requests request number sampler set name request number sampler get path else sampler set name sampler get path set the content encoding if content encoding null sampler set content encoding content encoding if it was a http get request then all parameters in the url has been handled by the sampler set path above so we just need to do parse the rest of the request if it is not a get request if http constants get equals method check if it was a multipart http post request final string content type get content type multipart url config url config get multipart config content type if url config null url config parse arguments post data tell the sampler to do a multipart post sampler set do multipart post true remove the header for content type and content length since those values will most likely be incorrect when the sampler performs the multipart request because the boundary string will change get header manager remove header named content type get header manager remove header named content length set the form data sampler set arguments url config get arguments set the file uploads sampler sethttp files url config gethttp file args as array else if post data trim starts with not sure if this is needed anymore i assume these requests do not have http constants application x www form urlencoded as content type and they would therefore be catched by the last else if of these if else if tests sampler add non encoded argument post data used when post data is pure xml ex an xml rpc call else if content type null content type starts with http constants application x www form urlencoded it is the most common post request with parameter name and values we also assume this if no content type is present to be most backwards compatible but maybe we should only parse arguments if the content type is as expected sampler parse arguments post data trim content encoding standard name value post data else if post data length 0 if is binary content content type try file temp dir new file binary directory file out file create temp file method binary file suffix temp dir file utils write byte array to file out raw post data http file arg files new http file arg out get path content type sampler sethttp files files catch io exception e log warn could not create binary file e else just put the whole postbody as the value of a parameter sampler add non encoded argument post data used when post data is pure xml ex an xml rpc call if log is debug enabled log debug sampler path sampler get path populatesampler pageencodings formencodings malformedurlexception unsupportedencodingexception setdomain servername isdebugenabled getdomain setmethod getmethod setport serverport isdebugenabled getport indexof indexof isdebugenabled setprotocol getport httpconstants default_https_port setprotocol isdebugenabled isdebugenabled setprotocol pageurl isprotocoldefaultport pageurl getprotocol getdomain getpath pageurl getprotocol getdomain getport getpath urlwithoutquery geturlwithoutquery pageurl contentencoding requestcontentencoding conversionutils getencodingfromcontenttype getcontenttype requestcontentencoding contentencoding requestcontentencoding pageencodings pageencodings contentencoding pageencodings urlwithoutquery formencodings formencodings formencoding formencodings urlwithoutquery formencoding contentencoding formencoding postdata isdebugenabled contentencoding contentencoding contentencoding postdata rawpostdata contentencoding postdata rawpostdata contentencoding setpath getpath contentencoding contentencoding setpath getpath isdebugenabled getpath numberrequests requestnumber setname requestnumber getpath setname getpath contentencoding setcontentencoding contentencoding setpath httpconstants contenttype getcontenttype multiparturlconfig urlconfig getmultipartconfig contenttype urlconfig urlconfig parsearguments postdata setdomultipartpost getheadermanager removeheadernamed content_type getheadermanager removeheadernamed content_length setarguments urlconfig getarguments sethttpfiles urlconfig gethttpfileargs asarray postdata startswith httpconstants application_x_www_form_urlencoded addnonencodedargument postdata postdata contenttype contenttype startswith httpconstants application_x_www_form_urlencoded parsearguments postdata contentencoding postdata postdata isbinarycontent contenttype tempdir binarydirectory createtempfile binaryfilesuffix tempdir fileutils writebytearraytofile rawpostdata httpfilearg httpfilearg getpath contenttype sethttpfiles ioexception addnonencodedargument postdata postdata isdebugenabled getpath private boolean is binary content string content type if content type null return false return binary content types contains content type isbinarycontent contenttype contenttype binarycontenttypes contenttype find the server name from an url return server s internet name private string server name chop to server name x thing string str url int i str index of non nls 1 if i 0 str str substring i 2 chop to server name xx i str index of non nls 1 if 0 i str str substring 0 i chop to server name i str index of non nls 1 if 0 i str str substring 0 i return str servername indexof indexof indexof find the port from http server ect port some file xxx return server s port or unspecified if not found private int server port string str url chop to server name x thing int i str index of if i 0 str str substring i 2 chop to server name xx i str index of if 0 i str str substring 0 i chop xx i str index of if 0 i return integer parse int str substring i 1 trim return http sampler base unspecified port serverport indexof indexof indexof parseint httpsamplerbase unspecified_port find the some file xxxx from http server ect port some file xxx return the path private string get path string str url int i str index of if i 0 str str substring i 2 i str index of if i 0 return return str substring i getpath indexof indexof returns the url string extracted from the first line of the client request return the url public string get url return url geturl returns the next token in a string param tk string that is partially tokenized return the remainder private string get token string tokenizer tk if tk has more tokens return tk next token return non nls 1 gettoken stringtokenizer hasmoretokens nexttoken private string get url without query url url string full url url to string string url without query full url string query url get query if query null get rid of the query and the url without query url without query substring 0 url without query length query length 1 return url without query geturlwithoutquery _url fullurl _url tostring urlwithoutquery fullurl _url getquery urlwithoutquery urlwithoutquery urlwithoutquery urlwithoutquery private transient weak reference listener public abstract listener element weakreference abstractlistenerelement protected final visualizer get visualizer if listener null e g in non gui mode return null return visualizer listener get getvisualizer public void set listener visualizer vis listener new weak reference vis setlistener weakreference public object clone abstract listener element clone abstract listener element super clone clone listener this listener return clone abstractlistenerelement abstractlistenerelement public class order preserving log parser extends sharedtc log parser public order preserving log parser super orderpreservinglogparser sharedtclogparser orderpreservinglogparser public order preserving log parser string source super source orderpreservinglogparser parse a set number of lines from the access log keep in mind the number of lines parsed will depend the filter and number of lines in the log the method returns the actual lines parsed param count return lines parsed public synchronized int parse and configure int count test element el return this parse el count parseandconfigure testelement constructor for the table visualizer object public table visualizer super model new object table model columns sample class the object used for each row new functor new functor get count non nls 1 new functor get start time formatted non nls 1 new object format new functor get thread name non nls 1 new functor get label non nls 1 new functor get data non nls 1 new sample success functor is success non nls 1 new functor get bytes non nls 1 new functor null null null null null null null new class long class string class string class string class long class image icon class integer class init tablevisualizer tablevisualizer objecttablemodel getcount getstarttimeformatted getthreadname getlabel getdata samplesuccessfunctor issuccess getbytes imageicon public static boolean test functors table visualizer instance new table visualizer return instance model check functors null instance get class testfunctors tablevisualizer tablevisualizer checkfunctors getclass public string get label resource return view results in table non nls 1 getlabelresource view_results_in_table protected synchronized void update text fields no samples field set text long to string calc get count data field set text long to string current data average field set text long to string long calc get mean deviation field set text long to string long calc get standard deviation updatetextfields nosamplesfield settext tostring getcount datafield settext tostring currentdata averagefield settext tostring getmean deviationfield settext tostring getstandarddeviation public void add sample result res current data res get time synchronized calc calc add value current data int count calc get count sample news new sample res get sample label res get time 0 0 0 0 0 0 res is successful count res get end time res get bytes res get thread name model add row news update text fields sampleresult currentdata gettime addvalue currentdata getcount getsamplelabel gettime issuccessful getendtime getbytes getthreadname addrow updatetextfields public synchronized void clear data model clear data current data 0 calc clear no samples field set text 0 non nls 1 data field set text 0 non nls 1 average field set text 0 non nls 1 deviation field set text 0 non nls 1 repaint cleardata cleardata currentdata nosamplesfield settext datafield settext averagefield settext deviationfield settext public string to string return show the samples in a table tostring private void init this set layout new border layout main panel j panel main panel new j panel border margin new empty border 10 10 5 10 main panel set border margin main panel set layout new vertical layout 5 vertical layout both name main panel add make title panel set up the table itself table new j table model table get table header set default renderer new header as property renderer table get table header set reordering allowed false renderer utils apply renderers table renderers table scroll panel new j scroll pane table table scroll panel set viewport border border factory create empty border 2 2 2 2 set up footer of table which displays numerics of the graphs j panel data panel new j panel j label data label new j label j meter utils get res string graph results latest sample non nls 1 data label set foreground color black data field new j text field 5 data field set border border factory create empty border 0 0 0 0 data field set editable false data field set foreground color black data field set background get background data panel add data label data panel add data field j panel average panel new j panel j label average label new j label j meter utils get res string graph results average non nls 1 average label set foreground color blue average field new j text field 5 average field set border border factory create empty border 0 0 0 0 average field set editable false average field set foreground color blue average field set background get background average panel add average label average panel add average field j panel deviation panel new j panel j label deviation label new j label j meter utils get res string graph results deviation non nls 1 deviation label set foreground color red deviation field new j text field 5 deviation field set border border factory create empty border 0 0 0 0 deviation field set editable false deviation field set foreground color red deviation field set background get background deviation panel add deviation label deviation panel add deviation field j panel no samples panel new j panel j label no samples label new j label j meter utils get res string graph results no samples non nls 1 no samples field new j text field 10 no samples field set border border factory create empty border 0 0 0 0 no samples field set editable false no samples field set foreground color black no samples field set background get background no samples panel add no samples label no samples panel add no samples field j panel table info panel new j panel table info panel set layout new flow layout table info panel set border border factory create empty border 0 0 0 0 table info panel add no samples panel table info panel add data panel table info panel add average panel table info panel add deviation panel set up the table with footer j panel table panel new j panel table panel set layout new border layout table panel add table scroll panel border layout center table panel add table info panel border layout south add the main panel and the graph this add main panel border layout north this add table panel border layout center setlayout borderlayout jpanel mainpanel jpanel emptyborder mainpanel setborder mainpanel setlayout verticallayout verticallayout mainpanel maketitlepanel jtable gettableheader setdefaultrenderer headeraspropertyrenderer gettableheader setreorderingallowed rendererutils applyrenderers tablescrollpanel jscrollpane tablescrollpanel setviewportborder borderfactory createemptyborder jpanel datapanel jpanel jlabel datalabel jlabel jmeterutils getresstring graph_results_latest_sample datalabel setforeground datafield jtextfield datafield setborder borderfactory createemptyborder datafield seteditable datafield setforeground datafield setbackground getbackground datapanel datalabel datapanel datafield jpanel averagepanel jpanel jlabel averagelabel jlabel jmeterutils getresstring graph_results_average averagelabel setforeground averagefield jtextfield averagefield setborder borderfactory createemptyborder averagefield seteditable averagefield setforeground averagefield setbackground getbackground averagepanel averagelabel averagepanel averagefield jpanel deviationpanel jpanel jlabel deviationlabel jlabel jmeterutils getresstring graph_results_deviation deviationlabel setforeground deviationfield jtextfield deviationfield setborder borderfactory createemptyborder deviationfield seteditable deviationfield setforeground deviationfield setbackground getbackground deviationpanel deviationlabel deviationpanel deviationfield jpanel nosamplespanel jpanel jlabel nosampleslabel jlabel jmeterutils getresstring graph_results_no_samples nosamplesfield jtextfield nosamplesfield setborder borderfactory createemptyborder nosamplesfield seteditable nosamplesfield setforeground nosamplesfield setbackground getbackground nosamplespanel nosampleslabel nosamplespanel nosamplesfield jpanel tableinfopanel jpanel tableinfopanel setlayout flowlayout tableinfopanel setborder borderfactory createemptyborder tableinfopanel nosamplespanel tableinfopanel datapanel tableinfopanel averagepanel tableinfopanel deviationpanel jpanel tablepanel jpanel tablepanel setlayout borderlayout tablepanel tablescrollpanel borderlayout tablepanel tableinfopanel borderlayout mainpanel borderlayout tablepanel borderlayout public static class sample success functor extends functor public sample success functor string method name super method name samplesuccessfunctor samplesuccessfunctor methodname methodname public object invoke object p invokee boolean success boolean super invoke p invokee if success null if success boolean value return image success else return image failure else return null p_invokee p_invokee booleanvalue imagesuccess imagefailure static final string copyright copyright c 1998 2009 the apache software foundation private j meter version not instantiable super jmeterversion static final string getversion return version protected bsf bean info support class bean class super bean class property descriptor p p property script language non nls 1 p set value not undefined boolean true p set value default non nls 1 create property group scripting language non nls 1 new string script language non nls 1 p property parameters non nls 1 p set value not undefined boolean true p set value default non nls 1 create property group parameter group non nls 1 new string parameters non nls 1 p property filename non nls 1 p set value not undefined boolean true p set value default non nls 1 create property group filename group non nls 1 new string filename non nls 1 p property script non nls 1 p set value not undefined boolean true p set value default non nls 1 p set property editor class text area editor class create property group scripting non nls 1 new string script non nls 1 bsfbeaninfosupport beanclass beanclass propertydescriptor scriptlanguage setvalue not_undefined setvalue createpropertygroup scriptinglanguage scriptlanguage setvalue not_undefined setvalue createpropertygroup parametergroup setvalue not_undefined setvalue createpropertygroup filenamegroup setvalue not_undefined setvalue setpropertyeditorclass textareaeditor createpropertygroup private j button add delete edit load save public button panel init jbutton buttonpanel public void add button listener int button action listener listener switch button case add button add add action listener listener break case edit button edit add action listener listener break case delete button delete add action listener listener break case load button load add action listener listener break case save button save add action listener listener break addbuttonlistener actionlistener add_button addactionlistener edit_button addactionlistener delete_button addactionlistener load_button addactionlistener save_button addactionlistener private void init add new j button j meter utils get res string add non nls 1 add set action command add edit new j button j meter utils get res string edit non nls 1 edit set action command edit delete new j button j meter utils get res string delete non nls 1 delete set action command delete load new j button j meter utils get res string load non nls 1 load set action command load save new j button j meter utils get res string save non nls 1 save set action command save dimension d delete get preferred size add set preferred size d edit set preferred size d close set preferred size d load set preferred size d save set preferred size d grid bag layout g new grid bag layout this set layout g grid bag constraints c new grid bag constraints c fill grid bag constraints none c gridwidth 1 c gridheight 1 c gridx 1 c gridy 1 g set constraints add c this add add c gridx 2 c gridy 1 g set constraints edit c this add edit c gridx 3 c gridy 1 g set constraints delete c this add delete c gridx 1 c gridy 2 g set constraints close c panel add close c gridx 2 c gridy 2 g set constraints load c this add load c gridx 3 c gridy 2 g set constraints save c this add save jbutton jmeterutils getresstring setactioncommand jbutton jmeterutils getresstring setactioncommand jbutton jmeterutils getresstring setactioncommand jbutton jmeterutils getresstring setactioncommand jbutton jmeterutils getresstring setactioncommand getpreferredsize setpreferredsize setpreferredsize setpreferredsize setpreferredsize setpreferredsize gridbaglayout gridbaglayout setlayout gridbagconstraints gridbagconstraints gridbagconstraints setconstraints setconstraints setconstraints setconstraints setconstraints setconstraints private transient boolean saved value public boolean property string name boolean v super name value v savedvalue booleanproperty public boolean property super booleanproperty public void set object value object v if v instanceof boolean value boolean v boolean value else value boolean value of v to string boolean value setobjectvalue booleanvalue valueof tostring booleanvalue see j meter property get string value public string get string value return boolean to string value jmeterproperty getstringvalue getstringvalue tostring see j meter property get object value public object get object value return boolean value of value jmeterproperty getobjectvalue getobjectvalue valueof public object clone boolean property prop boolean property super clone prop value value return prop booleanproperty booleanproperty see j meter property get boolean value public boolean get boolean value return value jmeterproperty getbooleanvalue getbooleanvalue see org apache jmeter testelement property j meter property set running version boolean public void set running version boolean running version saved value value super set running version running version jmeterproperty setrunningversion setrunningversion runningversion savedvalue setrunningversion runningversion see org apache jmeter testelement property j meter property recover running version org apache jmeter testelement test element public void recover running version test element owner value saved value jmeterproperty recoverrunningversion testelement recoverrunningversion testelement savedvalue private j check box style public random control gui init jcheckbox randomcontrolgui public test element create test element random controller ic new random controller modify test element ic return ic testelement createtestelement randomcontroller randomcontroller modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element ic configure test element ic if style is selected random controller ic set style interleave control ignore sub controllers else random controller ic set style interleave control use sub controllers testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement isselected randomcontroller setstyle interleavecontrol ignore_sub_controllers randomcontroller setstyle interleavecontrol use_sub_controllers implements j metergui component clear gui public void clear gui super clear gui style set selected false jmeterguicomponent cleargui cleargui cleargui setselected public void configure test element el super configure el if random controller el get style interleave control ignore sub controllers style set selected true else style set selected false testelement randomcontroller getstyle interleavecontrol ignore_sub_controllers setselected setselected public string get label resource return random control title non nls 1 getlabelresource random_control_title private void init set layout new vertical layout 5 vertical layout both vertical layout top set border make border add make title panel style new j check box j meter utils get res string ignore subcontrollers non nls 1 add style setlayout verticallayout verticallayout verticallayout setborder makeborder maketitlepanel jcheckbox jmeterutils getresstring ignore_subcontrollers see org apache jmeter gui action command do action action event public void do action action event e report tree node nodes report gui package get instance get tree listener get selected nodes if e get action command equals enable log debug enabling currently selected gui objects enable components nodes true else if e get action command equals disable log debug disabling currently selected gui objects enable components nodes false doaction actionevent doaction actionevent reporttreenode reportguipackage getinstance gettreelistener getselectednodes getactioncommand enablecomponents getactioncommand enablecomponents private void enable components report tree node nodes boolean enable report gui package pack report gui package get instance for int i 0 i nodes length i nodes i set enabled enable pack get gui nodes i get test element set enabled enable enablecomponents reporttreenode reportguipackage reportguipackage getinstance setenabled getgui gettestelement setenabled see org apache jmeter gui action command get action names public set get action names return commands getactionnames getactionnames public binarytcp client impl super set eol byte eom int if use eol byte log info using eom byte eol byte binarytcpclientimpl seteolbyte eomint useeolbyte eombyte eolbyte convert hex string to binary byte array param hex encoded binary hex encoded binary string return byte array containing binary representation of input hex encoded string throws illegal argument exception if string is not an even number of hex digits public static final byte hex string to byte array string hex encoded binary if hex encoded binary length 2 0 char sc hex encoded binary to char array byte ba new byte sc length 2 for int i 0 i ba length i int nibble0 character digit sc i 2 16 int nibble1 character digit sc i 2 1 16 if nibble0 1 nibble1 1 throw new illegal argument exception hex encoded binary string contains an invalid hex digit in sc i 2 sc i 2 1 ba i byte nibble0 4 nibble1 return ba else throw new illegal argument exception hex encoded binary string contains an uneven no of digits hexencodedbinary illegalargumentexception hexstringtobytearray hexencodedbinary hexencodedbinary hexencodedbinary tochararray illegalargumentexception illegalargumentexception input hex string is converted to binary and written to the output stream param os output stream param hex encoded binary hex encoded binary public void write output stream os string hex encoded binary try os write hex string to byte array hex encoded binary os flush catch io exception e log warn write error e log debug wrote hex encoded binary return hexencodedbinary outputstream hexencodedbinary hexstringtobytearray hexencodedbinary ioexception hexencodedbinary java io input stream public void write output stream os input stream is throw new unsupported operation exception method not supported for length prefixed data inputstream outputstream inputstream unsupportedoperationexception reads data until the defined eom byte is reached if there is no eom byte defined then reads until the end of the stream is reached response data is converted to hex encoded binary return hex encoded binary string public string read input stream is byte buffer new byte 4096 byte array output stream w new byte array output stream int x 0 try while x is read buffer 1 w write buffer 0 x if use eol byte buffer x 1 eol byte break catch socket timeout exception e drop out to handle buffer catch interruptedio exception e drop out to handle buffer catch io exception e log warn read error e return io utils close quietly w for completeness final string hex string j orphan utils ba to hex string w to byte array log debug read w size n hex string return hex string inputstream bytearrayoutputstream bytearrayoutputstream useeolbyte eolbyte sockettimeoutexception interruptedioexception ioexception ioutils closequietly hexstring jorphanutils batohexstring tobytearray hexstring hexstring protected string pkgs new string 0 public class filter super classfilter public void set packges string pk this pkgs pk setpackges public void add package string pkg string newpkg new string pkgs length 1 system arraycopy pkgs 0 newpkg 0 pkgs length newpkg pkgs length pkg pkgs newpkg addpackage public boolean include string text boolean inc false for int idx 0 idx pkgs length idx if text starts with pkgs idx inc true break return inc startswith public object filter array list items iterator itr items iterator array list newlist new array list while itr has next object item itr next if include string item newlist add item if newlist size 0 return newlist to array else return new object 0 filterarray arraylist arraylist hasnext toarray public int size return pkgs length private string concat string s1 string s2 return new string buffer s1 append append s2 to string non nls 1 stringbuffer _ tostring do the job extract value from x html response using x path query return value as variable defined by refname returns default value if not found public void process j meter context context get thread context j meter variables vars context get variables string ref name get ref name vars put ref name get default value vars put concat ref name match nr 0 in case parse fails non nls 1 vars remove concat ref name 1 in case parse fails non nls 1 final sample result previous result context get previous result try document d parse response previous result get values forx path d getx path query vars ref name catch io exception e should not happen final string error message error on getx path query log error error message e throw new j meter error error message e catch parser configuration exception e should not happen final string errror message error on getx path query log error errror message e throw new j meter error errror message e catch sax exception e can happen for bad input document log warn error on getx path query e get localized message catch transformer exception e can happen for incorrect x path expression log warn error on getx path query e get localized message catch tidy exception e assertion result ass new assertion result tidy exception non nls 1 ass set failure true ass set failure message e get message previous result add assertion result ass previous result set successful false xpath jmetercontext getthreadcontext jmetervariables getvariables refname getrefname refname getdefaultvalue refname match_nr refname sampleresult previousresult getpreviousresult parseresponse previousresult getvaluesforxpath getxpathquery refname ioexception errormessage getxpathquery errormessage jmetererror errormessage parserconfigurationexception errrormessage getxpathquery errrormessage jmetererror errrormessage saxexception getxpathquery getlocalizedmessage transformerexception xpath getxpathquery getlocalizedmessage tidyexception assertionresult assertionresult tidyexception setfailure setfailuremessage getmessage previousresult addassertionresult previousresult setsuccessful public object clone x path extractor cloned x path extractor super clone return cloned xpathextractor xpathextractor object properties public void setx path query string val set property xpath query val setxpathquery setproperty xpath_query public string getx path query return get property as string xpath query getxpathquery getpropertyasstring xpath_query public void set ref name string ref name set property refname ref name setrefname refname setproperty refname public string get ref name return get property as string refname getrefname getpropertyasstring public void set default value string val set property default val setdefaultvalue setproperty public string get default value return get property as string default getdefaultvalue getpropertyasstring public void set tolerant boolean val set property new boolean property tolerant val settolerant setproperty booleanproperty public boolean is tolerant return get property as boolean tolerant istolerant getpropertyasboolean public void set name space boolean val set property new boolean property namespace val setnamespace setproperty booleanproperty public boolean use name space return get property as boolean namespace usenamespace getpropertyasboolean public void set report errors boolean val set property report errors val false setreporterrors setproperty report_errors public boolean report errors return get property as boolean report errors false reporterrors getpropertyasboolean report_errors public void set show warnings boolean val set property show warnings val false setshowwarnings setproperty show_warnings public boolean show warnings return get property as boolean show warnings false showwarnings getpropertyasboolean show_warnings public void set quiet boolean val set property quiet val true setquiet setproperty public boolean is quiet return get property as boolean quiet true isquiet getpropertyasboolean internal business converts x html response to dom object tree this version cares of charset of response param result return private document parse response sample result result throws unsupported encoding exception io exception parser configuration exception sax exception tidy exception todo validate content type for reasonable types todo is it really necessary to recode the data note response data encoding is server specific therefore we do byte unicode byte conversion to ensure utf 8 encoding as required by x path util string unicode data result get response data as string convert unicode string utf 8 bytes byte utf8data unicode data get bytes utf 8 non nls 1 byte array input stream in new byte array input stream utf8data boolean isxml j orphan utils isxml utf8data this method assumes utf 8 input data return x path util make document in false false use name space is tolerant is quiet show warnings report errors isxml parseresponse sampleresult unsupportedencodingexception ioexception parserconfigurationexception saxexception tidyexception contenttype responsedata xpathutil unicodedata getresponsedataasstring unicodedata getbytes bytearrayinputstream bytearrayinputstream jorphanutils xpathutil makedocument usenamespace istolerant isquiet showwarnings reporterrors extract value from document d by x path query param d param query throws transformer exception private void get values forx path document d string query j meter variables vars string ref name throws transformer exception string val null x object x object x pathapi eval d query final int object type x object get type if object type x object class nodeset node list matches x object nodelist int length matches get length vars put concat ref name match nr string value of length for int i 0 i length i node match matches item i if match instanceof element elements have empty node value but we are usually interested in their content final node first child match get first child if first child null val first child get node value else val match get node value todo is this correct else val match get node value if val null if i 0 treat 1st match specially vars put ref name val vars put concat ref name string value of i 1 val vars remove concat ref name string value of length 1 else if object type x object class null object type x object class unknown object type x object class unresolvedvariable log warn unexpected object type x object get type string returned for getx path query else val x object to string vars put concat ref name match nr 1 vars put ref name val vars put concat ref name 1 val vars remove concat ref name 2 xpath transformerexception getvaluesforxpath jmetervariables refname transformerexception xobject xobject xpathapi objecttype xobject gettype objecttype xobject class_nodeset nodelist xobject getlength refname match_nr valueof nodevalue firstchild getfirstchild firstchild firstchild getnodevalue getnodevalue getnodevalue refname refname valueof refname valueof objecttype xobject class_null objecttype xobject class_unknown objecttype xobject class_unresolvedvariable xobject gettypestring getxpathquery xobject tostring refname match_nr refname refname refname protected map variables public void set master function compound variable variable master function variable setmasterfunction compoundvariable masterfunction protected compound variable get master function return master function compoundvariable getmasterfunction masterfunction public map get variables return variables getvariables public void set variables map map variables map setvariables public slow socket final int cps string host int port inet address local address int local port int timeout throws io exception super if cps 0 throw new illegal argument exception speed cps 0 cps cps this sequence is borrowed from org apache commons httpclient protocol reflection socket factory create socket socket address localaddr new inet socket address local address local port socket address remoteaddr new inet socket address host port bind localaddr connect remoteaddr timeout slowsocket inetaddress localaddress localport ioexception illegalargumentexception reflectionsocketfactory createsocket socketaddress inetsocketaddress localaddress localport socketaddress inetsocketaddress param cps characters per second param host hostname param port port param local addr local address param local port local port throws io exception throws illegal argument exception if cps 0 public slow socket int cps string host int port inet address local addr int local port throws io exception super host port local addr local port if cps 0 throw new illegal argument exception speed cps 0 cps cps localaddr localport ioexception illegalargumentexception slowsocket inetaddress localaddr localport ioexception localaddr localport illegalargumentexception param cps characters per second param host hostname param port port throws unknown host exception throws io exception throws illegal argument exception if cps 0 public slow socket int cps string host int port throws unknown host exception io exception super host port if cps 0 throw new illegal argument exception speed cps 0 cps cps unknownhostexception ioexception illegalargumentexception slowsocket unknownhostexception ioexception illegalargumentexception override so we can intercept the stream public output stream get output stream throws io exception return new slow output stream super get output stream cps outputstream getoutputstream ioexception slowoutputstream getoutputstream override so we can intercept the stream public input stream get input stream throws io exception return new slow input stream super get input stream cps inputstream getinputstream ioexception slowinputstream getinputstream protected constructor to prevent instantiation except from within subclasses protected html parser htmlparser public static final html parser get parser return get parser j meter utils get prop default parser classname default parser htmlparser getparser getparser jmeterutils getpropdefault parser_classname default_parser public static final synchronized html parser get parser string html parser class name is there a cached parser html parser pars html parser parsers get html parser class name if pars null log debug fetched html parser class name return pars try object clazz class for name html parser class name new instance if clazz instanceof html parser pars html parser clazz else throw new html parse error new class cast exception html parser class name catch instantiation exception e throw new html parse error e catch illegal access exception e throw new html parse error e catch class not found exception e throw new html parse error e log info created html parser class name if pars is reusable parsers put html parser class name pars cache the parser return pars htmlparser getparser htmlparserclassname htmlparser htmlparser htmlparserclassname htmlparserclassname forname htmlparserclassname newinstance htmlparser htmlparser htmlparseerror classcastexception htmlparserclassname instantiationexception htmlparseerror illegalaccessexception htmlparseerror classnotfoundexception htmlparseerror htmlparserclassname isreusable htmlparserclassname get the ur ls for all the resources that a browser would automatically download following the download of the html content that is images stylesheets javascript files applets etc p ur ls should not appear twice in the returned iterator p malformed ur ls can be reported to the caller by having the iterator return the corresponding rl string overall problems parsing the html should be reported by throwing an html parse exception param html html code param base url base url from which the html code was obtained return an iterator for the resource ur ls public iterator get embedded resourceur ls byte html url base url throws html parse exception the set is used to ignore duplicated binary files using a linked hash set to avoid unnecessary overhead in iterating the elements in the set later on as a side effect this will keep them roughly in order which should be a better model of browser behaviour collection col new linked hash set return get embedded resourceur ls html base url new url collection col an additional note on using hash sets to store ur ls i just discovered that obtaining the hash code of a java net url implies a domain name resolution process this means significant delays can occur even more so if the domain name is not resolvable whether this can be a problem in practical situations i can t tell but thought i d keep a note just in case btw note that using a vector and removing duplicates via scan would not help since url equals requires name resolution too the above problem has now been addressed with the url string and url collection classes urls urls urls htmlparseexception baseurl urls getembeddedresourceurls baseurl htmlparseexception linkedhashset linkedhashset getembeddedresourceurls baseurl urlcollection hashsets urls hashcode urlstring urlcollection get the ur ls for all the resources that a browser would automatically download following the download of the html content that is images stylesheets javascript files applets etc p all ur ls should be added to the collection p malformed ur ls can be reported to the caller by having the iterator return the corresponding rl string overall problems parsing the html should be reported by throwing an html parse exception n b the iterator returns ur ls but the collection will contain objects of class url string param html html code param base url base url from which the html code was obtained param coll url collection return an iterator for the resource ur ls public abstract iterator get embedded resourceur ls byte html url base url url collection coll urls urls urls htmlparseexception urls urlstring baseurl urlcollection urls getembeddedresourceurls baseurl urlcollection get the ur ls for all the resources that a browser would automatically download following the download of the html content that is images stylesheets javascript files applets etc n b the iterator returns ur ls but the collection will contain objects of class url string param html html code param base url base url from which the html code was obtained param coll collection will contain url string objects not ur ls return an iterator for the resource ur ls public iterator get embedded resourceur ls byte html url base url collection coll throws html parse exception return get embedded resourceur ls html base url new url collection coll urls urls urlstring baseurl urlstring urls urls getembeddedresourceurls baseurl htmlparseexception getembeddedresourceurls baseurl urlcollection parsers should over ride this method if the parser class is re usable in which case the class will be cached for the next get parser call return true if the parser is reusable protected boolean is reusable return false getparser isreusable returns the converter version used to check for possible incompatibilities public static string get version return revision 674365 non nls 1 getversion see com thoughtworks xstream converters converter can convert java lang class public boolean can convert class arg0 return arg0 equals long property class canconvert canconvert longproperty public void marshal object obj hierarchical stream writer writer marshalling context arg2 long property prop long property obj writer add attribute att name conversion help encode prop get name writer set value prop get string value hierarchicalstreamwriter marshallingcontext longproperty longproperty addattribute att_name conversionhelp getname setvalue getstringvalue public object unmarshal hierarchical stream reader reader unmarshalling context arg1 long property prop new long property conversion help decode reader get attribute att name long parse long reader get value return prop hierarchicalstreamreader unmarshallingcontext longproperty longproperty conversionhelp getattribute att_name parselong getvalue public class testcvs data set extends j meter test case public testcvs data set super testcvsdataset jmetertestcase testcvsdataset public testcvs data set string arg0 super arg0 testcvsdataset public void tear down throws io exception file server get file server close files teardown ioexception fileserver getfileserver closefiles public void testopen throws exception j meter context jmcx j meter context service get context jmcx set variables new j meter variables j meter variables thread vars jmcx get variables thread vars put b value csv data set csv new csv data set csv set filename no such filename csv set variable names a b c csv set delimiter csv iteration start null assert null thread vars get a assert equals value thread vars get b assert null thread vars get c csv new csv data set csv set filename testfiles testempty csv csv set variable names a b c csv set delimiter csv iteration start null assert equals thread vars get a assert equals b1 thread vars get b assert equals c1 thread vars get c csv iteration start null assert equals a2 thread vars get a assert equals thread vars get b assert equals c2 thread vars get c csv iteration start null assert equals a3 thread vars get a assert equals b3 thread vars get b assert equals thread vars get c csv iteration start null assert equals a4 thread vars get a assert equals b4 thread vars get b assert equals c4 thread vars get c csv iteration start null restart file assert equals thread vars get a assert equals b1 thread vars get b assert equals c1 thread vars get c jmetercontext jmetercontextservice getcontext setvariables jmetervariables jmetervariables threadvars getvariables threadvars csvdataset csvdataset setfilename setvariablenames setdelimiter iterationstart assertnull threadvars assertequals threadvars assertnull threadvars csvdataset setfilename setvariablenames setdelimiter iterationstart assertequals threadvars assertequals threadvars assertequals threadvars iterationstart assertequals threadvars assertequals threadvars assertequals threadvars iterationstart assertequals threadvars assertequals threadvars assertequals threadvars iterationstart assertequals threadvars assertequals threadvars assertequals threadvars iterationstart assertequals threadvars assertequals threadvars assertequals threadvars private csv data set initcsv csv data set csv new csv data set csv set filename testfiles test csv csv set variable names a b c csv set delimiter return csv csvdataset csvdataset csvdataset setfilename setvariablenames setdelimiter public void test share mode j meter context jmcx j meter context service get context jmcx set variables new j meter variables j meter variables thread vars jmcx get variables thread vars put b value csv data set bean info cbi new csv data set bean info needs to be initialised csv data set csv0 initcsv csv data set csv1 initcsv assert null csv1 get share mode csv1 set share mode abc assert equals abc csv1 get share mode csv1 iteration start null assert equals a1 thread vars get a csv1 iteration start null assert equals a2 thread vars get a csv data set csv2 initcsv csv2 set share mode abc assert equals abc csv2 get share mode csv2 iteration start null assert equals a3 thread vars get a csv0 iteration start null assert equals a1 thread vars get a csv1 iteration start null assert equals a4 thread vars get a testsharemode jmetercontext jmetercontextservice getcontext setvariables jmetervariables jmetervariables threadvars getvariables threadvars csvdatasetbeaninfo csvdatasetbeaninfo csvdataset csvdataset assertnull getsharemode setsharemode assertequals getsharemode iterationstart assertequals threadvars iterationstart assertequals threadvars csvdataset setsharemode assertequals getsharemode iterationstart assertequals threadvars iterationstart assertequals threadvars iterationstart assertequals threadvars public class ajp sampler gui extends http test sample gui public ajp sampler gui super ajpsamplergui httptestsamplegui ajpsamplergui public test element create test element ajp sampler sampler new ajp sampler modify test element sampler return sampler testelement createtestelement ajpsampler ajpsampler modifytestelement use this instead of get label resource otherwise get doc anchor below does not work public string get static label return j meter utils get res string ajp sampler title non nls 1 getlabelresource getdocanchor getstaticlabel jmeterutils getresstring ajp_sampler_title public string get doc anchor reuse documentation return super get static label replace non nls 1 non nls 2 getdocanchor getstaticlabel _ create a pauser with the appropriate speed settings param cps cps to emulate public cps pauser int cps if cps 0 throw new illegal argument exception speed cps 0 cps cps cpspauser illegalargumentexception pause for an appropriate time according to the number of bytes being transferred param bytes number of bytes being transferred public void pause int bytes long sleepms bytes ms per sec cps int sleepns bytes ms per sec cps ns per ms try thread sleep sleepms sleepns catch interrupted exception ignored ms_per_sec ms_per_sec ns_per_ms interruptedexception public class bean shell timer bean info extends bean shell bean info support public bean shell timer bean info super bean shell timer class beanshelltimerbeaninfo beanshellbeaninfosupport beanshelltimerbeaninfo beanshelltimer private boolean for thread true public tree cloner this true forthread treecloner public tree cloner boolean for thread new tree new listed hash tree this for thread for thread treecloner forthread newtree listedhashtree forthread forthread public void add node object node hash tree sub tree if for thread node instanceof no thread clone node instanceof test element node test element node clone new tree add objects node else new tree add objects node objects add last node addnode hashtree subtree forthread nothreadclone testelement testelement newtree newtree addlast public void subtract node objects remove last subtractnode removelast public listed hash tree get cloned tree return new tree listedhashtree getclonedtree newtree public void process path processpath private j check box should cache public string get label resource return http url rewriting modifier title non nls 1 jcheckbox shouldcache getlabelresource http_url_rewriting_modifier_title public url rewriting modifier gui init urlrewritingmodifiergui private void init set layout new border layout 0 5 set border make border add make title panel border layout north vertical panel main panel new vertical panel argument name new j labeled text field j meter utils get res string session argument name 10 non nls 1 main panel add argument name path ext new j check box j meter utils get res string path extension choice non nls 1 main panel add path ext path ext no equals new j check box j meter utils get res string path extension dont use equals non nls 1 main panel add path ext no equals path ext no questionmark new j check box j meter utils get res string path extension dont use questionmark non nls 1 main panel add path ext no questionmark should cache new j check box j meter utils get res string cache session id non nls 1 should cache set selected true main panel add should cache add main panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout verticalpanel mainpanel verticalpanel argumentname jlabeledtextfield jmeterutils getresstring session_argument_name mainpanel argumentname pathext jcheckbox jmeterutils getresstring path_extension_choice mainpanel pathext pathextnoequals jcheckbox jmeterutils getresstring path_extension_dont_use_equals mainpanel pathextnoequals pathextnoquestionmark jcheckbox jmeterutils getresstring path_extension_dont_use_questionmark mainpanel pathextnoquestionmark shouldcache jcheckbox jmeterutils getresstring cache_session_id shouldcache setselected mainpanel shouldcache mainpanel borderlayout public test element create test element url rewriting modifier modifier new url rewriting modifier modify test element modifier return modifier testelement createtestelement urlrewritingmodifier urlrewritingmodifier modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element modifier this configure test element modifier url rewriting modifier rewriting modifier url rewriting modifier modifier rewriting modifier set argument name argument name get text rewriting modifier set path extension path ext is selected rewriting modifier set path extension no equals path ext no equals is selected rewriting modifier set path extension no questionmark path ext no questionmark is selected rewriting modifier set should cache should cache is selected testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement urlrewritingmodifier rewritingmodifier urlrewritingmodifier rewritingmodifier setargumentname argumentname gettext rewritingmodifier setpathextension pathext isselected rewritingmodifier setpathextensionnoequals pathextnoequals isselected rewritingmodifier setpathextensionnoquestionmark pathextnoquestionmark isselected rewritingmodifier setshouldcache shouldcache isselected implements j metergui component clear gui public void clear gui super clear gui argument name set text non nls 1 path ext set selected false path ext no equals set selected false path ext no questionmark set selected false should cache set selected false jmeterguicomponent cleargui cleargui cleargui argumentname settext pathext setselected pathextnoequals setselected pathextnoquestionmark setselected shouldcache setselected public void configure test element el url rewriting modifier rewriting modifier url rewriting modifier el argument name set text rewriting modifier get argument name path ext set selected rewriting modifier is path extension path ext no equals set selected rewriting modifier is path extension no equals path ext no questionmark set selected rewriting modifier is path extension no questionmark should cache set selected rewriting modifier should cache super configure el testelement urlrewritingmodifier rewritingmodifier urlrewritingmodifier argumentname settext rewritingmodifier getargumentname pathext setselected rewritingmodifier ispathextension pathextnoequals setselected rewritingmodifier ispathextensionnoequals pathextnoquestionmark setselected rewritingmodifier ispathextensionnoquestionmark shouldcache setselected rewritingmodifier shouldcache public static final string init file beanshell assertion init non nls 1 protected string get init file property return init file init_file getinitfileproperty init_file public string get script return get property as string script getscript getpropertyasstring public string get filename return get property as string filename getfilename getpropertyasstring public string get parameters return get property as string parameters getparameters getpropertyasstring public boolean is reset interpreter return get property as boolean reset interpreter isresetinterpreter getpropertyasboolean reset_interpreter public assertion result get result sample result response assertion result result new assertion result get name final bean shell interpreter bsh interpreter get bean shell interpreter if bsh interpreter null result set failure true result set error true result set failure message bean shell interpreter not found return result try string request get script string file name get filename bsh interpreter set file name get filename non nls 1 set params as a single line bsh interpreter set parameters get parameters non nls 1 bsh interpreter set bsh args non nls 1 j orphan utils split get parameters non nls 1 add sampler data for consistency with bean shell sampler bsh interpreter set sample result response non nls 1 bsh interpreter set response response non nls 1 bsh interpreter set response data response get response data non nls 1 bsh interpreter set response code response get response code non nls 1 bsh interpreter set response message response get response message non nls 1 bsh interpreter set response headers response get response headers non nls 1 bsh interpreter set request headers response get request headers non nls 1 bsh interpreter set sample label response get sample label non nls 1 bsh interpreter set sampler data response get sampler data non nls 1 bsh interpreter set successful response is successful non nls 1 the following are used to set the result details on return from the script bsh interpreter set failure message non nls 1 non nls 2 bsh interpreter set failure false non nls 1 add variables for access to context and variables j meter context jmctx j meter context service get context j meter variables vars jmctx get variables bsh interpreter set ctx jmctx non nls 1 bsh interpreter set vars vars non nls 1 object bsh out if file name length 0 bsh out bsh interpreter eval request else bsh out bsh interpreter source file name result set failure message bsh interpreter get failure message to string non nls 1 result set failure boolean value of bsh interpreter get failure non nls 1 to string boolean value result set error false to avoid class loading problems when the bsh jar is missing we don t try to catch this error separately catch bsh eval error ex log debug ex result set error true result set failure message ex to string but we do trap this error to make tests work better catch no class def found error ex log error bean shell jar missing ex to string result set error true result set failure message bean shell jar missing ex to string response set stop thread true no point continuing catch exception ex mainly for bsh eval error result set error true result set failure message ex to string log warn ex to string return result assertionresult getresult sampleresult assertionresult assertionresult getname beanshellinterpreter bshinterpreter getbeanshellinterpreter bshinterpreter setfailure seterror setfailuremessage beanshell getscript filename getfilename bshinterpreter filename getfilename bshinterpreter getparameters bshinterpreter jorphanutils getparameters samplerdata beanshell bshinterpreter sampleresult bshinterpreter bshinterpreter responsedata getresponsedata bshinterpreter responsecode getresponsecode bshinterpreter responsemessage getresponsemessage bshinterpreter responseheaders getresponseheaders bshinterpreter requestheaders getrequestheaders bshinterpreter samplelabel getsamplelabel bshinterpreter samplerdata getsamplerdata bshinterpreter issuccessful bshinterpreter failuremessage bshinterpreter jmetercontext jmetercontextservice getcontext jmetervariables getvariables bshinterpreter bshinterpreter bshout filename bshout bshinterpreter bshout bshinterpreter filename setfailuremessage bshinterpreter failuremessage tostring setfailure valueof bshinterpreter tostring booleanvalue seterror evalerror seterror setfailuremessage tostring noclassdeffounderror beanshell tostring seterror setfailuremessage beanshell tostring setstopthread evalerror seterror setfailuremessage tostring tostring public access log sampler bean info super access log sampler class log debug entered access log sampler bean info try create property group defaults non nls 1 new string domain port string image parsing non nls 1 non nls 2 non nls 3 create property group plugins non nls 1 new string parser class name filter class name non nls 1 non nls 2 non nls 3 create property group accesslogfile non nls 1 new string log file non nls 1 property descriptor p p property parser class name p set value not undefined boolean true p set value default access log sampler default class p set value not other boolean true p set value not expression boolean true final list log parser classes class finder find classes that extend j meter utils get search paths new class log parser class if log is debug enabled log debug found parsers log parser classes p set value tags log parser classes to array new string 0 p property filter class name non nls 1 p set value not undefined boolean false p set value default non nls 1 p set value not expression boolean true p set value tags class finder find classes that extend j meter utils get search paths new class filter class false to array new string 0 p property log file non nls 1 p set value not undefined boolean true p set value default p set property editor class file editor class p property domain non nls 1 p set value not undefined boolean true p set value default p property port string non nls 1 p set value not undefined boolean true p set value default non nls 1 p property image parsing non nls 1 p set value not undefined boolean true p set value default boolean false p set value not other boolean true catch io exception e log warn couldn t find classes and set up properties e throw new runtime exception could not find classes with class finder log debug got to end of access log samper bean info init accesslogsamplerbeaninfo accesslogsampler createpropertygroup portstring imageparsing createpropertygroup parserclassname filterclassname createpropertygroup logfile propertydescriptor parserclassname setvalue not_undefined setvalue accesslogsampler default_class setvalue not_other setvalue not_expression logparserclasses classfinder findclassesthatextend jmeterutils getsearchpaths logparser isdebugenabled logparserclasses setvalue logparserclasses toarray filterclassname setvalue not_undefined setvalue setvalue not_expression setvalue classfinder findclassesthatextend jmeterutils getsearchpaths toarray logfile setvalue not_undefined setvalue setpropertyeditorclass fileeditor setvalue not_undefined setvalue portstring setvalue not_undefined setvalue imageparsing setvalue not_undefined setvalue setvalue not_other ioexception runtimeexception default constructor for code sleep test code the java sampler uses the default constructor to instantiate an instance of the client class public sleep test get logger debug who ami t construct sleeptest sleeptest getlogger whoami tconstruct do any initialization required by this client in this case initialization consists of getting the values of the sleep time and sleep mask parameters it is generally recommended to do any initialization such as getting parameter values in the setup test method rather than the run test method in order to add as little overhead as possible to the test param context the context to run with this provides access to initialization parameters public void setup test java sampler context context get logger debug who ami tsetup test list parameters context sleep time context get long parameter sleep time default sleep time sleep mask context get long parameter sleep mask default sleep mask sleeptime sleepmask setuptest runtest setuptest javasamplercontext getlogger whoami tsetuptest listparameters sleeptime getlongparameter sleeptime default_sleep_time sleepmask getlongparameter sleepmask default_sleep_mask perform a single sample in this case this method will simply sleep for some amount of time perform a single sample for each iteration this method returns a code sample result code object code sample result code has many fields which can be used at a minimum the test should use code sample result sample start code and code sample result sample end code to set the time that the test required to execute it is also a good idea to set the sample label and the successful flag see org apache jmeter samplers sample result sample start see org apache jmeter samplers sample result sample end see org apache jmeter samplers sample result set successful boolean see org apache jmeter samplers sample result set sample label string param context the context to run with this provides access to initialization parameters return a sample result giving the results of this sample public sample result run test java sampler context context sample result results new sample result try record sample start time results sample start generate a random value using the current time long start system current time millis long sleep get sleep time start get sleep mask results set sample label sleep test time sleep execute the sample in this case sleep for the specified time thread sleep sleep results set successful true catch interrupted exception e get logger warn sleep test interrupted results set successful true catch exception e get logger error sleep test error during sample e results set successful false finally results sample end if get logger is debug enabled get logger debug who ami trun test t time t results get time list parameters context return results sampleresult sampleresult sampleresult samplestart sampleresult sampleend samplelabel sampleresult samplestart sampleresult sampleend sampleresult setsuccessful sampleresult setsamplelabel sampleresult sampleresult runtest javasamplercontext sampleresult sampleresult samplestart currenttimemillis getsleeptime getsleepmask setsamplelabel setsuccessful interruptedexception getlogger sleeptest setsuccessful getlogger sleeptest setsuccessful sampleend getlogger isdebugenabled getlogger whoami truntest ttime gettime listparameters do any clean up required by this test in this case no clean up is necessary but some messages are logged for debugging purposes param context the context to run with this provides access to initialization parameters public void teardown test java sampler context context get logger debug who ami tteardown test list parameters context teardowntest javasamplercontext getlogger whoami tteardowntest listparameters provide a list of parameters which this test supports any parameter names and associated values returned by this method will appear in the gui by default so the user doesn t have to remember the exact names the user can add other parameters which are not listed here if this method returns null then no parameters will be listed if the value for some parameter is null then that parameter will be listed in the gui with an empty value return a specification of the parameters used by this test which should be listed in the gui or null if no parameters should be listed public arguments get default parameters arguments params new arguments params add argument sleep time string value of default sleep time params add argument sleep mask 0x long to hex string default sleep mask to upper case java util locale english return params getdefaultparameters addargument sleeptime valueof default_sleep_time addargument sleepmask tohexstring default_sleep_mask touppercase dump a list of the parameters in this context to the debug log param context the context which contains the initialization parameters private void list parameters java sampler context context if get logger is debug enabled iterator args it context get parameter names iterator while args it has next string name string args it next get logger debug name context get parameter name listparameters javasamplercontext getlogger isdebugenabled argsit getparameternamesiterator argsit hasnext argsit getlogger getparameter generate a string identifier of this test for debugging purposes return a string identifier for this test instance private string who ami string buffer sb new string buffer sb append thread current thread to string sb append sb append integer to hex string hash code return sb to string whoami stringbuffer stringbuffer currentthread tostring tohexstring hashcode tostring get the value of the sleep time field return the base number of milliseconds to sleep during each sample private long get sleep time return sleep time sleeptime getsleeptime sleeptime get the value of the sleep mask field return a mask to be applied to the current time in order to add a random component to the sleep time private long get sleep mask return sleep mask sleepmask getsleepmask sleepmask see org apache jmeter protocol http util accesslog log filter exc pattern java lang string protected boolean has exc pattern string text return false logfilter excpattern hasexcpattern protected string get ip address string log line pattern inc ip j meter utils get pattern cache get pattern d 1 3 d 1 3 d 1 3 d 1 3 perl5 compiler read only mask perl5 compiler singleline mask perl5 matcher matcher j meter utils get matcher matcher contains log line inc ip return matcher get match group 0 getipaddress logline incip jmeterutils getpatterncache getpattern perl5compiler read_only_mask perl5compiler singleline_mask perl5matcher jmeterutils getmatcher logline incip getmatch see org apache jmeter protocol http util accesslog filter reset public void reset cookie managers clear cookiemanagers public object clone if cookie managers null cookie managers collections synchronized map new hash map if managers in use null managers in use collections synchronized set new hash set session filter f new session filter f cookie managers cookie managers f managers in use managers in use return f cookiemanagers cookiemanagers synchronizedmap hashmap managersinuse managersinuse synchronizedset hashset sessionfilter sessionfilter cookiemanagers cookiemanagers managersinuse managersinuse public session filter sessionfilter see org apache jmeter protocol http util accesslog filter exclude files java lang string public void exclude files string filenames excludefiles excludefiles see org apache jmeter protocol http util accesslog filter exclude pattern java lang string public void exclude pattern string regexp excludepattern excludepattern see org apache jmeter protocol http util accesslog filter filter java lang string public string filter string text return text see org apache jmeter protocol http util accesslog filter include files java lang string public void include files string filenames includefiles includefiles see org apache jmeter protocol http util accesslog filter include pattern java lang string public void include pattern string regexp includepattern includepattern public boolean is filtered string path test element sampler string ip addr get ip address path cookie manager cm get cookie manager ip addr http sampler sampler set cookie manager cm return false isfiltered testelement ipaddr getipaddress cookiemanager getcookiemanager ipaddr httpsampler setcookiemanager protected cookie manager get cookie manager string ip addr cookie manager cm null first have to release the cookie we were using so other threads stuck in wait can move on synchronized managers in use if last used null managers in use remove last used managers in use notify let notified threads move on and get lock on managers in use if last used null thread yield here is the core routine to find appropriate cookie manager and check it s not being used if used wait until whoever s using it gives it up synchronized managers in use cm cookie manager cookie managers get ip addr if cm null cm new cookie manager cookie managers put ip addr cm while managers in use contains cm try managers in use wait catch interrupted exception e log info session filter wait interrupted managers in use add cm last used cm return cm cookiemanager getcookiemanager ipaddr cookiemanager managersinuse lastused managersinuse lastused managersinuse managersinuse lastused managersinuse cookiemanager cookiemanagers ipaddr cookiemanager cookiemanagers ipaddr managersinuse managersinuse interruptedexception sessionfilter managersinuse lastused java lang string public void set replace extension string oldextension string newextension setreplaceextension public void thread finished synchronized managers in use managers in use remove last used managers in use notify threadfinished managersinuse managersinuse lastused managersinuse see org apache jmeter testelement thread listener thread started public void thread started todo auto generated method stub threadlistener threadstarted threadstarted create a new name panel with the default name public name panel set name get static label init namepanel namepanel setname getstaticlabel initialize the gui components and layout private void init set layout new border layout 5 0 name label new j label j meter utils get res string name non nls 1 name label set name name name label set label for name field name field get document add document listener new document listener public void insert update document event e update name name field get text public void remove update document event e update name name field get text public void changed update document event e not for text fields add name label border layout west add name field border layout center setlayout borderlayout namelabel jlabel jmeterutils getresstring namelabel setname namelabel setlabelfor namefield namefield getdocument adddocumentlistener documentlistener insertupdate documentevent updatename namefield gettext removeupdate documentevent updatename namefield gettext changedupdate documentevent namelabel borderlayout namefield borderlayout name field get document add document listener new document listener public void insert update document event e update name name field get text namefield getdocument adddocumentlistener documentlistener insertupdate documentevent updatename namefield gettext public void remove update document event e update name name field get text removeupdate documentevent updatename namefield gettext public void changed update document event e not for text fields changedupdate documentevent public void clear gui set name get static label cleargui setname getstaticlabel get the currently displayed name return the current name public string get name if name field null return name field get text return non nls 1 getname namefield namefield gettext set the name displayed in this component param name the name to display public void set name string name super set name name name field set text name setname setname namefield settext get the tree node which this component provides the name for return the tree node corresponding to this component protected tree node get node return node treenode getnode set the tree node which this component provides the name for param node the tree node corresponding to this component public void set node tree node node this node node setnode treenode implements j metergui component configure test element public void configure test element test element set name test element get name jmeterguicomponent testelement testelement testelement setname testelement getname implements j metergui component create popup menu public j popup menu create popup menu return null jmeterguicomponent createpopupmenu jpopupmenu createpopupmenu implements j metergui component get static label public string get static label return j meter utils get res string get label resource jmeterguicomponent getstaticlabel getstaticlabel jmeterutils getresstring getlabelresource see org apache jmeter gui j metergui component get label resource public string get label resource return root non nls 1 jmeterguicomponent getlabelresource getlabelresource implements j metergui component get menu categories public collection get menu categories return null jmeterguicomponent getmenucategories getmenucategories implements j metergui component create test element public test element create test element work bench wb new work bench modify test element wb return wb jmeterguicomponent createtestelement testelement createtestelement workbench workbench modifytestelement implements j metergui component modify test element test element public void modify test element test element wb wb set name get name wb set property new string property test element gui class this get class get name wb set property new string property test element test class work bench class get name jmeterguicomponent modifytestelement testelement modifytestelement testelement setname getname setproperty stringproperty testelement gui_class getclass getname setproperty stringproperty testelement test_class workbench getname called when the name changes the tree node which this component names will be notified of the change param new value the new name private void update name string new value if get node null named tree node get node name changed newvalue updatename newvalue getnode namedtreenode getnode namechanged see org apache jmeter gui j metergui component get doc anchor public string get doc anchor return null jmeterguicomponent getdocanchor getdocanchor creates a new url collection from an existing collection public url collection collection c coll c urlcollection urlcollection adds the url to the collection first wrapping it in the url string class param u url to add return boolean condition returned by the add method of the underlying collection public boolean add url u return coll add new url string u urlstring urlstring method of the underlying collection private boolean add string s return coll add new url string s urlstring convenience method for adding ur ls to the collection if the url parameter is null or empty nothing is done param url string may be null or empty param base url return boolean condition returned by the add method of the underlying collection public boolean addurl string url url base url if url null url length 0 return false url replace url string escape utils unescape xml url boolean b false try b this add conversion utils make relativeurl base url url catch malformedurl exception mfue todo log a warning message b this add url add the string if cannot create the url return b urls baseurl baseurl stringescapeutils unescapexml conversionutils makerelativeurl baseurl malformedurlexception public iterator iterator return new url iterator coll iterator urliterator private final iterator iter url iterator iterator i iter i urliterator public boolean has next return iter has next hasnext hasnext unwraps the url string class to return the url public object next return url string iter next geturl urlstring urlstring public void remove throw new unsupported operation exception unsupportedoperationexception public class test once only controller extends j meter test case public test once only controller string name super name testonceonlycontroller jmetertestcase testonceonlycontroller public void test processing throws exception generic controller controller new generic controller generic controller sub 1 new once only controller sub 1 add test element new test sampler one sub 1 add test element new test sampler two controller add test element sub 1 controller add test element new test sampler three loop controller sub 2 new loop controller sub 2 set loops 3 generic controller sub 3 new generic controller sub 2 add test element new test sampler four sub 3 add test element new test sampler five sub 3 add test element new test sampler six sub 2 add test element sub 3 sub 2 add test element new test sampler seven controller add test element sub 2 string interleave order new string one two string order new string three four five six seven four five six seven four five six seven int counter 15 controller set running version true sub 1 set running version true sub 2 set running version true sub 3 set running version true controller initialize for int i 0 i 4 i assert equals 15 counter counter 0 if i 0 counter 2 test element sampler null while sampler controller next null if i 0 counter 2 assert equals interleave order counter sampler get name else assert equals order counter sampler get name counter testprocessing genericcontroller genericcontroller genericcontroller sub_1 onceonlycontroller sub_1 addtestelement testsampler sub_1 addtestelement testsampler addtestelement sub_1 addtestelement testsampler loopcontroller sub_2 loopcontroller sub_2 setloops genericcontroller sub_3 genericcontroller sub_2 addtestelement testsampler sub_3 addtestelement testsampler sub_3 addtestelement testsampler sub_2 addtestelement sub_3 sub_2 addtestelement testsampler addtestelement sub_2 interleaveorder setrunningversion sub_1 setrunningversion sub_2 setrunningversion sub_3 setrunningversion assertequals testelement assertequals interleaveorder getname assertequals getname public void test processing2 throws exception generic controller controller new generic controller generic controller sub 1 new once only controller sub 1 add test element new test sampler one sub 1 add test element new test sampler two controller add test element sub 1 controller add test element new test sampler three loop controller sub 2 new loop controller sub 2 set loops 3 once only controller sub 3 new once only controller sub 2 add test element new test sampler four sub 3 add test element new test sampler five sub 3 add test element new test sampler six sub 2 add test element sub 3 sub 2 add iteration listener sub 3 sub 2 add test element new test sampler seven controller add test element sub 2 string interleave order new string one two string order new string three four five six seven four seven four seven int counter 11 controller set running version true sub 1 set running version true sub 2 set running version true sub 3 set running version true controller initialize for int i 0 i 4 i assert equals 11 counter counter 0 if i 0 counter 2 test element sampler null while sampler controller next null if i 0 counter 2 assert equals interleave order counter sampler get name else assert equals order counter sampler get name counter testprocessing2 genericcontroller genericcontroller genericcontroller sub_1 onceonlycontroller sub_1 addtestelement testsampler sub_1 addtestelement testsampler addtestelement sub_1 addtestelement testsampler loopcontroller sub_2 loopcontroller sub_2 setloops onceonlycontroller sub_3 onceonlycontroller sub_2 addtestelement testsampler sub_3 addtestelement testsampler sub_3 addtestelement testsampler sub_2 addtestelement sub_3 sub_2 additerationlistener sub_3 sub_2 addtestelement testsampler addtestelement sub_2 interleaveorder setrunningversion sub_1 setrunningversion sub_2 setrunningversion sub_3 setrunningversion assertequals testelement assertequals interleaveorder getname assertequals getname public void test in outer loop throws exception set up the test plan loop controller controller new loop controller final int outer loop count 4 controller set loops outer loop count only once samples once only controller sub 1 new once only controller sub 1 add test element new test sampler one sub 1 add test element new test sampler two controller add test element sub 1 controller add iteration listener sub 1 outer sample controller add test element new test sampler three inner loop loop controller sub 2 new loop controller final int inner loop count 3 sub 2 set loops inner loop count generic controller sub 3 new generic controller sub 2 add test element new test sampler four sub 3 add test element new test sampler five sub 3 add test element new test sampler six sub 2 add test element sub 3 sample in inner loop sub 2 add test element new test sampler seven controller add test element sub 2 compute the expected sample names string only once order new string one two string order new string three four five six seven four five six seven four five six seven outer only once three four five six seven inner loop count outer loop count int expected no samples 2 1 3 1 inner loop count outer loop count string expected samples new string expected no samples the only once samples for int i 0 i only once order length i expected samples i only once order i the outer sample and the inner loop samples final int once only samples only once order length for int i 0 i order length outer loop count i expected samples once only samples i order i order length execute the test pan controller set running version true sub 1 set running version true sub 2 set running version true sub 3 set running version true controller initialize int counter 0 test element sampler null while sampler controller next null assert equals expected samples counter sampler get property as string test element name counter assert equals expected no samples counter testinouterloop loopcontroller loopcontroller outerloopcount setloops outerloopcount onlyonce onceonlycontroller sub_1 onceonlycontroller sub_1 addtestelement testsampler sub_1 addtestelement testsampler addtestelement sub_1 additerationlistener sub_1 addtestelement testsampler loopcontroller sub_2 loopcontroller innerloopcount sub_2 setloops innerloopcount genericcontroller sub_3 genericcontroller sub_2 addtestelement testsampler sub_3 addtestelement testsampler sub_3 addtestelement testsampler sub_2 addtestelement sub_3 sub_2 addtestelement testsampler addtestelement sub_2 onlyonceorder innerloopcount outerloopcount expectednosamples innerloopcount outerloopcount expectedsamples expectednosamples onlyonceorder expectedsamples onlyonceorder onceonlysamples onlyonceorder outerloopcount expectedsamples onceonlysamples setrunningversion sub_1 setrunningversion sub_2 setrunningversion sub_3 setrunningversion testelement assertequals expectedsamples getpropertyasstring testelement assertequals expectednosamples public void test inside inner loop throws exception test plan with only once controller inside inner loop set up the test plan loop controller controller new loop controller final int outer loop count 4 controller set loops outer loop count only once samples once only controller sub 1 new once only controller sub 1 add test element new test sampler one sub 1 add test element new test sampler two controller add test element sub 1 controller add iteration listener sub 1 outer sample controller add test element new test sampler three inner loop loop controller sub 2 new loop controller final int inner loop count 3 sub 2 set loops inner loop count sample in inner loop sub 2 add test element new test sampler four only once inside inner loop once only controller sub 3 new once only controller sub 3 add test element new test sampler five sub 3 add test element new test sampler six sub 2 add test element sub 3 sub 2 add iteration listener sub 3 sample in inner loop sub 2 add test element new test sampler seven controller add test element sub 2 compute the expected sample names string only once order new string one two string order new string three four five six seven four seven four seven outer only once three only once five and six four seven inner loop count outer loop count int expected no samples 2 1 2 1 1 inner loop count outer loop count string expected samples new string expected no samples the only once samples for int i 0 i only once order length i expected samples i only once order i the outer sample and the inner loop samples final int once only samples only once order length for int i 0 i order length outer loop count i expected samples once only samples i order i order length execute the test pan controller set running version true sub 1 set running version true sub 2 set running version true sub 3 set running version true controller initialize int counter 0 test element sampler null while sampler controller next null assert equals expected samples counter sampler get property as string test element name counter assert equals expected no samples counter testinsideinnerloop onlyoncecontroller loopcontroller loopcontroller outerloopcount setloops outerloopcount onlyonce onceonlycontroller sub_1 onceonlycontroller sub_1 addtestelement testsampler sub_1 addtestelement testsampler addtestelement sub_1 additerationlistener sub_1 addtestelement testsampler loopcontroller sub_2 loopcontroller innerloopcount sub_2 setloops innerloopcount sub_2 addtestelement testsampler onlyonce onceonlycontroller sub_3 onceonlycontroller sub_3 addtestelement testsampler sub_3 addtestelement testsampler sub_2 addtestelement sub_3 sub_2 additerationlistener sub_3 sub_2 addtestelement testsampler addtestelement sub_2 onlyonceorder innerloopcount outerloopcount expectednosamples innerloopcount outerloopcount expectedsamples expectednosamples onlyonceorder expectedsamples onlyonceorder onceonlysamples onlyonceorder outerloopcount expectedsamples onceonlysamples setrunningversion sub_1 setrunningversion sub_2 setrunningversion sub_3 setrunningversion testelement assertequals expectedsamples getpropertyasstring testelement assertequals expectednosamples test skipped for now as behaviour is not yet properly defined public void notest inside interleave throws exception test to show current problem with interleave controller i am not sure if the expected order of the samples below are correct because i am not sure if it is properly defined how the interleave controller and only once controller should function test plan with only once controller inside inner loop set up the test plan loop controller controller new loop controller final int outer loop count 4 controller set loops outer loop count only once samples once only controller sub 1 new once only controller sub 1 set name outer only once sub 1 add test element new test sampler one sub 1 add test element new test sampler two controller add test element sub 1 controller add iteration listener sub 1 outer sample controller add test element new test sampler three inner loop loop controller sub 2 new loop controller final int inner loop count 5 sub 2 set loops inner loop count sub 2 add test element new test sampler four only once inside inner loop once only controller sub 3 new once only controller sub 3 set name in loop only once sub 3 add test element new test sampler five sub 3 add test element new test sampler six sub 2 add test element sub 3 sub 2 add iteration listener sub 3 interleave controller in inner loop interleave control sub 4 new interleave control sub 4 set style interleave control use sub controllers only once inside interleave controller once only controller sub 5 new once only controller sub 5 add test element new test sampler seven sub 5 add test element new test sampler eight sub 5 set name inside interleave controller only once sub 4 add test element sub 5 sub 4 add iteration listener sub 5 samples inside interleave controller sub 4 add test element new test sampler nine sub 4 add test element new test sampler ten sub 2 add test element sub 4 sample in inner loop sub 2 add test element new test sampler eleven controller add test element sub 2 compute the expected sample names string only once order new string one two string order new string three four five six seven eight eleven four nine eleven four ten eleven four nine eleven four ten eleven outer only once three only once five and six eight in interleave only once four interleave eleven inner loop count outer loop count int expected no samples 2 1 2 1 1 1 1 inner loop count outer loop count string expected samples new string expected no samples the only once samples for int i 0 i only once order length i expected samples i only once order i the outer sample and the inner loop samples final int once only samples only once order length for int i 0 i order length outer loop count i expected samples once only samples i order i order length execute the test pan controller set running version true sub 1 set running version true sub 2 set running version true sub 3 set running version true sub 4 set running version true sub 5 set running version true controller initialize int counter 0 test element sampler null while sampler controller next null system out println ex expected samples counter ac sampler get property as string test element name assert equals expected samples counter sampler get property as string test element name counter assert equals expected no samples counter notestinsideinterleave interleavecontroller interleavecontroller onlyoncecontroller onlyoncecontroller loopcontroller loopcontroller outerloopcount setloops outerloopcount onlyonce onceonlycontroller sub_1 onceonlycontroller sub_1 setname onlyonce sub_1 addtestelement testsampler sub_1 addtestelement testsampler addtestelement sub_1 additerationlistener sub_1 addtestelement testsampler loopcontroller sub_2 loopcontroller innerloopcount sub_2 setloops innerloopcount sub_2 addtestelement testsampler onlyonce onceonlycontroller sub_3 onceonlycontroller sub_3 setname onlyonce sub_3 addtestelement testsampler sub_3 addtestelement testsampler sub_2 addtestelement sub_3 sub_2 additerationlistener sub_3 interleavecontroller interleavecontrol sub_4 interleavecontrol sub_4 setstyle interleavecontrol use_sub_controllers onlyonce interleavecontroller onceonlycontroller sub_5 onceonlycontroller sub_5 addtestelement testsampler sub_5 addtestelement testsampler sub_5 setname interleavecontroller onlyonce sub_4 addtestelement sub_5 sub_4 additerationlistener sub_5 interleavecontroller sub_4 addtestelement testsampler sub_4 addtestelement testsampler sub_2 addtestelement sub_4 sub_2 addtestelement testsampler addtestelement sub_2 onlyonceorder innerloopcount outerloopcount expectednosamples innerloopcount outerloopcount expectedsamples expectednosamples onlyonceorder expectedsamples onlyonceorder onceonlysamples onlyonceorder outerloopcount expectedsamples onceonlysamples setrunningversion sub_1 setrunningversion sub_2 setrunningversion sub_3 setrunningversion sub_4 setrunningversion sub_5 setrunningversion testelement expectedsamples getpropertyasstring testelement assertequals expectedsamples getpropertyasstring testelement assertequals expectednosamples public abstract class abstract pre processor gui extends abstractj meter gui component public j popup menu create popup menu return menu factory get default extractor menu abstractpreprocessorgui abstractjmeterguicomponent jpopupmenu createpopupmenu menufactory getdefaultextractormenu public collection get menu categories return arrays as list new string menu factory pre processors getmenucategories aslist menufactory pre_processors extends j meter test case because it needs access to j meter properties public class test sample save configuration extends j meter test case public test sample save configuration string name super name jmetertest jmeter testsamplesaveconfiguration jmetertestcase testsamplesaveconfiguration public void test clone throws exception sample save configuration a new sample save configuration a set url false a set assertions true a set default delimiter a set default time stamp format a set data type true assert false a save url assert not null a get delimiter assert true a save assertions assert true a save data type original and clone should be equal sample save configuration clonea sample save configuration a clone assert not same a clonea assert equals a clonea assert true a equals clonea assert true clonea equals a assert equals a hash code clonea hash code change the original a set url true assert false a equals clonea assert false clonea equals a assert false a hash code clonea hash code change the original back again a set url false assert equals a clonea assert true a equals clonea assert true clonea equals a assert equals a hash code clonea hash code testclone samplesaveconfiguration samplesaveconfiguration seturl setassertions setdefaultdelimiter setdefaulttimestampformat setdatatype assertfalse saveurl assertnotnull getdelimiter asserttrue saveassertions asserttrue savedatatype samplesaveconfiguration samplesaveconfiguration assertnotsame assertequals asserttrue asserttrue assertequals hashcode hashcode seturl assertfalse assertfalse assertfalse hashcode hashcode seturl assertequals asserttrue asserttrue assertequals hashcode hashcode public void test equals and hash code throws exception sample save configuration a new sample save configuration a set url false a set assertions true a set default delimiter a set default time stamp format a set data type true sample save configuration b new sample save configuration b set url false b set assertions true b set default delimiter b set default time stamp format b set data type true a and b should be equal assert equals a b assert true a equals b assert true b equals a assert equals a hash code b hash code assert equals a save url b save url assert equals a save assertions b save assertions assert equals a get delimiter b get delimiter assert equals a save data type b save data type a set assertions false a and b should not be equal assert false a equals b assert false b equals a assert false a hash code b hash code assert false a save assertions b save assertions testequalsandhashcode samplesaveconfiguration samplesaveconfiguration seturl setassertions setdefaultdelimiter setdefaulttimestampformat setdatatype samplesaveconfiguration samplesaveconfiguration seturl setassertions setdefaultdelimiter setdefaulttimestampformat setdatatype assertequals asserttrue asserttrue assertequals hashcode hashcode assertequals saveurl saveurl assertequals saveassertions saveassertions assertequals getdelimiter getdelimiter assertequals savedatatype savedatatype setassertions assertfalse assertfalse assertfalse hashcode hashcode assertfalse saveassertions saveassertions public void test false throws exception sample save configuration a new sample save configuration false sample save configuration b new sample save configuration false assert true hash codes should be equal a hash code b hash code assert true objects should be equal a equals b assert true objects should be equal b equals a testfalse samplesaveconfiguration samplesaveconfiguration samplesaveconfiguration samplesaveconfiguration asserttrue hashcode hashcode asserttrue asserttrue public void test true throws exception sample save configuration a new sample save configuration true sample save configuration b new sample save configuration true assert true hash codes should be equal a hash code b hash code assert true objects should be equal a equals b assert true objects should be equal b equals a testtrue samplesaveconfiguration samplesaveconfiguration samplesaveconfiguration samplesaveconfiguration asserttrue hashcode hashcode asserttrue asserttrue public void test false true throws exception sample save configuration a new sample save configuration false sample save configuration b new sample save configuration true assert false hash codes should not be equal a hash code b hash code assert false objects should not be equal a equals b assert false objects should not be equal b equals a testfalsetrue samplesaveconfiguration samplesaveconfiguration samplesaveconfiguration samplesaveconfiguration assertfalse hashcode hashcode assertfalse assertfalse public void test formatter throws exception sample save configuration a new sample save configuration false sample save configuration b new sample save configuration false a set formatter null assert true hash codes should be equal a hash code b hash code assert true objects should be equal a equals b assert true objects should be equal b equals a b set formatter null assert true hash codes should be equal a hash code b hash code assert true objects should be equal a equals b assert true objects should be equal b equals a a set formatter new simple date format b set formatter new simple date format assert true hash codes should be equal a hash code b hash code assert true objects should be equal a equals b assert true objects should be equal b equals a testformatter samplesaveconfiguration samplesaveconfiguration samplesaveconfiguration samplesaveconfiguration setformatter asserttrue hashcode hashcode asserttrue asserttrue setformatter asserttrue hashcode hashcode asserttrue asserttrue setformatter simpledateformat setformatter simpledateformat asserttrue hashcode hashcode asserttrue asserttrue public x path xpath see org apache jmeter functions function execute sample result sampler public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception string my value non nls 1 string file name org apache jmeter engine util compound variable values 0 execute string xpath string org apache jmeter engine util compound variable values 1 execute if log is debug enabled log debug execute file name xpath string my value x path wrapper getx path string file name xpath string if log is debug enabled log debug execute value my value return my value sampleresult sampleresult previousresult currentsampler invalidvariableexception myvalue filename compoundvariable xpathstring compoundvariable isdebugenabled filename xpathstring myvalue xpathwrapper getxpathstring filename xpathstring isdebugenabled myvalue myvalue see org apache jmeter functions function get argument desc public list get argument desc return desc getargumentdesc getargumentdesc see org apache jmeter functions function get reference key public string get reference key return key getreferencekey getreferencekey see org apache jmeter functions function set parameters collection public synchronized void set parameters collection parameters throws invalid variable exception log debug set parameter collection size parameters size values parameters to array if log is debug enabled for int i 0 i parameters size i log debug i compound variable values i execute check parameter count parameters 2 need to reset the containers for repeated runs about the only way for functions to detect that a run is starting seems to be the set parameters call x path wrapper clear all todo only clear the relevant entry if possible setparameters setparameters invalidvariableexception setparameter toarray isdebugenabled compoundvariable checkparametercount setparameters xpathwrapper clearall public create function dialog helper new function helper createfunctiondialog functionhelper provide the list of action names that are available in this command public set get action names return commands getactionnames public void do action action event arg0 helper show doaction actionevent private object values public java script javascript public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception j meter context jmctx j meter context service get context j meter variables vars jmctx get variables string script compound variable values 0 execute allow variable to be omitted string var name values length 2 null compound variable values 1 execute trim string result str context cx context enter try scriptable scope cx init standard objects null set up some objects for the script to play with scope put log scope log non nls 1 scope put ctx scope jmctx non nls 1 scope put vars scope vars non nls 1 scope put props scope j meter utils getj meter properties non nls 1 previously mis spelt as thead name scope put thread name scope thread current thread get name non nls 1 scope put sampler scope current sampler non nls 1 scope put sample result scope previous result non nls 1 object result cx evaluate string scope script cmd 1 null non nls 1 result str context to string result if var name null vars null vars can be null if run from test plan vars put var name result str catch wrapped exception e log error error processing javascript e throw new invalid variable exception catch ecma error e log error error processing javascript e throw new invalid variable exception catch java script exception e log error error processing javascript e throw new invalid variable exception finally context exit return result str sampleresult previousresult currentsampler invalidvariableexception jmetercontext jmetercontextservice getcontext jmetervariables getvariables compoundvariable varname compoundvariable resultstr initstandardobjects jmeterutils getjmeterproperties theadname threadname currentthread getname currentsampler sampleresult previousresult evaluatestring resultstr tostring varname testplan varname resultstr wrappedexception invalidvariableexception ecmaerror invalidvariableexception javascriptexception invalidvariableexception resultstr see org apache jmeter functions function set parameters collection public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters 1 2 values parameters to array setparameters setparameters invalidvariableexception checkparametercount toarray see org apache jmeter functions function get reference key public string get reference key return key getreferencekey getreferencekey see org apache jmeter functions function get argument desc public list get argument desc return desc getargumentdesc getargumentdesc initializes the gui panel for the module controller instance public module controller gui nodes model new default combo box model nodes new j combo box nodes model warning label new j label non nls 1 init modulecontroller modulecontrollergui nodesmodel defaultcomboboxmodel jcombobox nodesmodel warninglabel jlabel public string get label resource return module controller title non nls 1 getlabelresource module_controller_title public void configure test element el super configure el module controller controller module controller el this selected controller get selected node if selected null controller get node path null warning label set text j meter utils get res string module controller warning non nls 1 render path controller get node path else warning label set text non nls 1 reinitialize testelement modulecontroller modulecontroller getselectednode getnodepath warninglabel settext jmeterutils getresstring module_controller_warning renderpath getnodepath warninglabel settext private string render path collection path iterator iter path iterator string buffer buf new string buffer boolean first true while iter has next if first first false iter next continue buf append iter next if iter has next buf append non nls 1 return buf to string renderpath stringbuffer stringbuffer hasnext hasnext tostring public test element create test element module controller mc new module controller configure test element mc if selected null mc set selected node selected return mc testelement createtestelement modulecontroller modulecontroller configuretestelement setselectednode public void modify test element test element element configure test element element tree node wrapper tnw tree node wrapper nodes model get selected item if tnw null tnw get tree node null selected tnw get tree node if selected null module controller element set selected node selected modifytestelement testelement configuretestelement treenodewrapper treenodewrapper nodesmodel getselecteditem gettreenode gettreenode modulecontroller setselectednode implements j metergui component clear gui public void clear gui super clear gui nodes set selected index 1 selected null jmeterguicomponent cleargui cleargui cleargui setselectedindex public j popup menu create popup menu j popup menu menu new j popup menu j menu add menu menu factory make menus new string menu factory config elements menu factory assertions menu factory timers menu factory listeners j meter utils get res string add non nls 1 action names add menu add add menu menu factory add edit menu menu true menu factory add file menu menu return menu jpopupmenu createpopupmenu jpopupmenu jpopupmenu jmenu addmenu menufactory makemenus menufactory config_elements menufactory menufactory menufactory jmeterutils getresstring actionnames addmenu menufactory addeditmenu menufactory addfilemenu private void init set layout new vertical layout 5 vertical layout both vertical layout top set border make border add make title panel drop down menu j panel modules panel new j panel new flow layout flow layout left 20 5 j label nodes label new j label j meter utils get res string module controller module to run non nls 1 modules panel add nodes label nodes label set label for nodes reinitialize modules panel add nodes modules panel add warning label add modules panel setlayout verticallayout verticallayout verticallayout setborder makeborder maketitlepanel jpanel modulespanel jpanel flowlayout flowlayout jlabel nodeslabel jlabel jmeterutils getresstring module_controller_module_to_run modulespanel nodeslabel nodeslabel setlabelfor modulespanel modulespanel warninglabel modulespanel private void reinitialize tree node wrapper current nodes model remove all elements gui package gp gui package get instance j meter tree node root if gp null root j meter tree node gui package get instance get tree model get root build nodes model root 0 non nls 1 if selected null for int i 0 i nodes model get size i current tree node wrapper nodes model get element at i if current get tree node null selected null current get tree node null current get tree node equals selected nodes model set selected item current break treenodewrapper nodesmodel removeallelements guipackage guipackage getinstance jmetertreenode jmetertreenode guipackage getinstance gettreemodel getroot buildnodesmodel nodesmodel getsize treenodewrapper nodesmodel getelementat gettreenode gettreenode gettreenode nodesmodel setselecteditem private void build nodes model j meter tree node node string parent name int level if level 0 parent name null parent name length 0 nodes model add element new tree node wrapper null non nls 1 string seperator non nls 1 if node null for int i 0 i node get child count i string buffer name new string buffer j meter tree node cur j meter tree node node get child at i test element te cur get test element if te instanceof thread group name append parent name name append cur get name name append seperator build nodes model cur name to string level else if te instanceof controller te instanceof module controller name append spaces level name append parent name name append cur get name tree node wrapper tnw new tree node wrapper cur name to string nodes model add element tnw name new string buffer name append cur get name name append seperator build nodes model cur name to string level 1 else if te instanceof test plan te instanceof work bench name append cur get name name append seperator build nodes model cur name to string 0 buildnodesmodel jmetertreenode parent_name parent_name parent_name nodesmodel addelement treenodewrapper getchildcount stringbuffer stringbuffer jmetertreenode jmetertreenode getchildat testelement gettestelement threadgroup parent_name getname buildnodesmodel tostring modulecontroller parent_name getname treenodewrapper treenodewrapper tostring nodesmodel addelement stringbuffer getname buildnodesmodel tostring testplan workbench getname buildnodesmodel tostring private string spaces int level int multi 4 string buffer spaces new string buffer level multi for int i 0 i level multi i spaces append non nls 1 return spaces to string stringbuffer stringbuffer tostring private final string label public tree node wrapper j meter tree node tn string label this tn tn this label label treenodewrapper jmetertreenode public j meter tree node get tree node return tn jmetertreenode gettreenode public string to string return label tostring private j labeled choice x items new j labeled choice public bar chart gui super init jlabeledchoice xitems jlabeledchoice barchartgui public string get label resource return report bar chart getlabelresource report_bar_chart public j popup menu create popup menu j popup menu pop new j popup menu report menu factory add file menu pop report menu factory add edit menu pop true return pop jpopupmenu createpopupmenu jpopupmenu jpopupmenu reportmenufactory addfilemenu reportmenufactory addeditmenu private void init called from ctor so must not be overridable set layout new border layout 10 10 set border make border set background color white j panel pane new j panel pane set layout new border layout 10 10 pane set background color white pane add this get name panel border layout north vertical panel options new vertical panel color white x axis label set background color white y axis label set background color white j label x label new j label j meter utils get res string report chart x axis horizontal panel xpanel new horizontal panel color white x label set border new empty border 5 2 5 2 x items set background color white x items set values abstract table xitems xpanel add x label xpanel add x items options add xpanel j label xa label new j label j meter utils get res string report chart x axis label horizontal panel x apanel new horizontal panel color white xa label set border new empty border 5 2 5 2 x axis label set background color white x axis label set values abstract chart x labels x apanel add xa label x apanel add x axis label options add x apanel j label y label new j label j meter utils get res string report chart y axis horizontal panel ypanel new horizontal panel color white y label set border new empty border 5 2 5 2 y items set background color white y items set values abstract table items ypanel add y label ypanel add y items options add ypanel options add y axis label options add caption options add url add pane border layout north add options border layout center setlayout borderlayout setborder makeborder setbackground jpanel jpanel setlayout borderlayout setbackground getnamepanel borderlayout verticalpanel verticalpanel xaxislabel setbackground yaxislabel setbackground jlabel xlabel jlabel jmeterutils getresstring report_chart_x_axis horizontalpanel horizontalpanel xlabel setborder emptyborder xitems setbackground xitems setvalues abstracttable xlabel xitems jlabel xalabel jlabel jmeterutils getresstring report_chart_x_axis_label horizontalpanel xapanel horizontalpanel xalabel setborder emptyborder xaxislabel setbackground xaxislabel setvalues abstractchart x_labels xapanel xalabel xapanel xaxislabel xapanel jlabel ylabel jlabel jmeterutils getresstring report_chart_y_axis horizontalpanel horizontalpanel ylabel setborder emptyborder yitems setbackground yitems setvalues abstracttable ylabel yitems yaxislabel borderlayout borderlayout public test element create test element bar chart element new bar chart modify test element element return element testelement createtestelement barchart barchart modifytestelement public void modify test element test element element this configure test element element bar chart bc bar chart element bc setx axis x items get text bc sety axis y items get text bc setx label x axis label get text bc sety label y axis label get text bc set caption caption get text bc seturl url get text modifytestelement testelement configuretestelement barchart barchart setxaxis xitems gettext setyaxis yitems gettext setxlabel xaxislabel gettext setylabel yaxislabel gettext setcaption gettext gettext public void configure test element element super configure element bar chart bc bar chart element x items set text bc getx axis y items set text bc gety axis x axis label set text bc getx label y axis label set text bc gety label caption set text bc get caption url set text bc geturl testelement barchart barchart xitems settext getxaxis yitems settext getyaxis xaxislabel settext getxlabel yaxislabel settext getylabel settext getcaption settext public report edit command reporteditcommand public void do action action event e report gui package gui package report gui package get instance gui package get main frame set main panel javax swing j component gui package get current gui gui package get main frame set edit menu gui package get tree listener get current node create popup menu todo i believe the following code to the end of the method is obsolete since name panel no longer seems to be the gui for any component if gui package get current gui instanceof name panel gui package get main frame set file load enabled true gui package get main frame set file save enabled true else gui package get main frame set file load enabled false gui package get main frame set file save enabled false doaction actionevent reportguipackage guipackage reportguipackage getinstance guipackage getmainframe setmainpanel jcomponent guipackage getcurrentgui guipackage getmainframe seteditmenu guipackage gettreelistener getcurrentnode createpopupmenu namepanel guipackage getcurrentgui namepanel guipackage getmainframe setfileloadenabled guipackage getmainframe setfilesaveenabled guipackage getmainframe setfileloadenabled guipackage getmainframe setfilesaveenabled public set get action names return commands getactionnames public html assertion log debug html assertion called htmlassertion htmlassertion returns the result of the assertion if so an assertion result containing a failure message will be returned otherwise the returned assertion result will reflect the success of the sample public assertion result get result sample result in response log debug html assertions get result called no error as default assertion result result new assertion result get name if in response get response data length 0 return result set result for null result set failure false create parser tidy tidy null try log debug html assertions get result setup tidy log debug doctype get doctype log debug errors only is errors only log debug error threshold get error threshold log debug warning threshold get warning threshold log debug html mode ishtml log debug xhtml mode isxhtml log debug xml mode isxml tidy new tidy tidy set char encoding org w3c tidy configuration utf8 tidy set quiet false tidy set show warnings true tidy set only errors is errors only tidy set doc type get doctype if isxhtml tidy setxhtml true else if isxml tidy set xml tags true log debug err file get filename tidy set errfile get filename if log is debug enabled log debug get parser tidy parser created tidy log debug html assertions get result tidy instance created catch exception e todo replace with proper exception log error unable to instantiate tidy parser e result set failure true result set failure message unable to instantiate tidy parser return with an error return result run tidy try log debug html assertions get result start parsing with tidy string writer errbuf new string writer tidy set errout new print writer errbuf node node tidy parsedom new byte array input stream response get response data null byte array output stream os new byte array output stream log debug start parse node node tidy parse new byte array input stream in response get response data os if log is debug enabled log debug node node log debug end parse log debug html assertions get result parsing with tidy done log debug output os to string write output to file write output errbuf to string evaluate result if tidy get parse errors get error threshold is errors only tidy get parse warnings get warning threshold log debug html assertions get result errors warnings detected log debug errbuf to string result set failure true result set failure message message format format tidy parser errors tidy get parse errors allowed get error threshold tidy parser warnings tidy get parse warnings allowed get warning threshold new object 0 return with an error else if tidy get parse errors 0 tidy get parse warnings 0 return with no error log debug html assertions get result there were errors warnings but threshold to high result set failure false else return with no error log debug html assertions get result no errors warnings detected result set failure false catch exception e todo replace with proper exception return with an error log warn cannot parse result content e result set failure true result set failure message e get message return result assertionresult failuremessage assertionresult assertionresult getresult sampleresult inresponse htmlassertions getresult assertionresult assertionresult getname inresponse getresponsedata setresultfornull setfailure htmlassertions getresult getdoctype iserrorsonly geterrorthreshold getwarningthreshold setcharencoding setquiet setshowwarnings setonlyerrors iserrorsonly setdoctype getdoctype setxmltags getfilename seterrfile getfilename isdebugenabled getparser htmlassertions getresult setfailure setfailuremessage htmlassertions getresult stringwriter stringwriter seterrout printwriter bytearrayinputstream getresponsedata bytearrayoutputstream bytearrayoutputstream bytearrayinputstream inresponse getresponsedata isdebugenabled htmlassertions getresult tostring writeoutput tostring getparseerrors geterrorthreshold iserrorsonly getparsewarnings getwarningthreshold htmlassertions getresult tostring setfailure setfailuremessage messageformat getparseerrors geterrorthreshold getparsewarnings getwarningthreshold getparseerrors getparsewarnings htmlassertions getresult setfailure htmlassertions getresult setfailure setfailure setfailuremessage getmessage writes the output of tidy to file param in output private void write output string in output string l filename get filename check if filename defined if l filename null equals l filename trim file writer l output writer null try open file l output writer new file writer l filename false write to file l output writer write in output flush l output writer flush log debug write output output successfully written to file l filename catch io exception ex log warn write output could not write output to file l filename ex finally close file io utils close quietly l output writer inoutput writeoutput inoutput lfilename getfilename lfilename lfilename filewriter loutputwriter loutputwriter filewriter lfilename loutputwriter inoutput loutputwriter writeoutput lfilename ioexception writeoutput lfilename ioutils closequietly loutputwriter gets the doctype return the documemt type public string get doctype return get property as string doctype key getdoctype getpropertyasstring doctype_key check if errors will be reported only return boolean report errors only public boolean is errors only return get property as boolean errors only key iserrorsonly getpropertyasboolean errors_only_key gets the threshold setting for errors return long error threshold public long get error threshold return get property as long error threshold key geterrorthreshold getpropertyaslong error_threshold_key gets the threshold setting for warnings return long warning threshold public long get warning threshold return get property as long warning threshold key getwarningthreshold getpropertyaslong warning_threshold_key sets the doctype setting param in doctype public void set doctype string in doctype if in doctype null in doctype trim equals set property new string property doctype key default doctype else set property new string property doctype key in doctype indoctype setdoctype indoctype indoctype indoctype setproperty stringproperty doctype_key default_doctype setproperty stringproperty doctype_key indoctype sets if errors shoud be tracked only param in errors only public void set errors only boolean in errors only set property new boolean property errors only key in errors only inerrorsonly seterrorsonly inerrorsonly setproperty booleanproperty errors_only_key inerrorsonly sets the threshold on error level param in error threshold public void set error threshold long in error threshold if in error threshold 0l throw new illegal argument exception j meter utils get res string argument must not be negative non nls 1 if in error threshold long max value set property new long property error threshold key 0 else set property new long property error threshold key in error threshold inerrorthreshold seterrorthreshold inerrorthreshold inerrorthreshold illegalargumentexception jmeterutils getresstring argument_must_not_be_negative inerrorthreshold max_value setproperty longproperty error_threshold_key setproperty longproperty error_threshold_key inerrorthreshold sets the threshold on warning level param in warning threshold public void set warning threshold long in warning threshold if in warning threshold 0l throw new illegal argument exception j meter utils get res string argument must not be negative non nls 1 if in warning threshold long max value set property new long property warning threshold key 0 else set property new long property warning threshold key in warning threshold inwarningthreshold setwarningthreshold inwarningthreshold inwarningthreshold illegalargumentexception jmeterutils getresstring argument_must_not_be_negative inwarningthreshold max_value setproperty longproperty warning_threshold_key setproperty longproperty warning_threshold_key inwarningthreshold enables html validation mode public void sethtml set property new long property format key 0 setproperty longproperty format_key check if html validation mode is set return boolean public boolean ishtml return get property as long format key 0 getpropertyaslong format_key enables xhtml validation mode public void setxhtml set property new long property format key 1 setproperty longproperty format_key check if xhtml validation mode is set return boolean public boolean isxhtml return get property as long format key 1 getpropertyaslong format_key enables xml validation mode public void setxml set property new long property format key 2 setproperty longproperty format_key check if xml validation mode is set return boolean public boolean isxml return get property as long format key 2 getpropertyaslong format_key sets the name of the file where tidy writes the output to return name of file public string get filename return get property as string filename key getfilename getpropertyasstring filename_key sets the name of the tidy output file param in name public void set filename string in name set property filename key in name inname setfilename inname setproperty filename_key inname public class j meter engine exception extends exception implements serializable public j meter engine exception super jmeterengineexception jmeterengineexception public j meter engine exception string msg super msg jmeterengineexception public monitor model super monitormodel public monitor model monitor stats stat this current stat monitormodel monitorstats public int get health return this current get health gethealth gethealth public int get load return this current get load getload getload public int get cpuload return this current get cpu load getcpuload getcpuload public int get memload return this current get mem load getmemload getmemload public int get threadload return this current get thread load getthreadload getthreadload public string get host return this current get host gethost gethost public string get port return this current get port getport getport public string get protocol return this current get protocol getprotocol getprotocol public long get timestamp return this current get time stamp gettimestamp gettimestamp public string geturl return this current geturl method will return a formatted date using simple date format return string public string get timestamp string date date new date this current get time stamp simple date format ft new simple date format return ft format date simpledateformat gettimestampstring gettimestamp simpledateformat simpledateformat method is used by default mutable tree node to get the label for the node public string to string return geturl defaultmutabletreenode tostring clear will create a new monitor stats object public void clear data current new monitor stats 0 0 0 0 0 system current time millis monitorstats cleardata monitorstats currenttimemillis a clone method is provided for convienance in some cases it may be desirable to clone the object public object clone return new monitor model clone monitor stats monitormodel clonemonitorstats a clone method to clone the stats return new instance of the class public monitor stats clone monitor stats return new monitor stats current get health current get load current get cpu load current get mem load current get thread load current get host current get port current get protocol current get time stamp monitorstats clonemonitorstats monitorstats gethealth getload getcpuload getmemload getthreadload gethost getport getprotocol gettimestamp default constructor the label and the text field are left empty public j labeled text area this null jlabeledtextarea constructs a new component with the label displaying the passed text param label the text to display in the label public j labeled text area string label this label null jlabeledtextarea constructs a new component with the label displaying the passed text param p label the text to display in the label param doc model the document for the text area public j labeled text area string p label document doc model super m label new j label p label init if doc model null m text area set document doc model plabel docmodel jlabeledtextarea plabel docmodel mlabel jlabel plabel docmodel mtextarea setdocument docmodel public list get component list list comps new linked list comps add m label comps add m text area return comps getcomponentlist linkedlist mlabel mtextarea public void set document model document doc model m text area set document doc model setdocumentmodel docmodel mtextarea setdocument docmodel initialises all of the components on this panel private void init set layout new border layout m text area new j text area m text area set rows 4 m text area set line wrap true m text area set wrap style word true register the handler for focus listening this handler will only notify the registered when the text changes from when the focus is gained to when it is lost m text area add focus listener this add the sub components this add m label border layout north this add new j scroll pane m text area border layout center setlayout borderlayout mtextarea jtextarea mtextarea setrows mtextarea setlinewrap mtextarea setwrapstyleword mtextarea addfocuslistener mlabel borderlayout jscrollpane mtextarea borderlayout callback method when the focus to the text field component is lost param p focus event the focus event that occured public void focus lost focus event p focus event compare if the value has changed since we received focus if old value equals m text area get text notify change listeners pfocusevent focuslost focusevent pfocusevent oldvalue mtextarea gettext notifychangelisteners catch what the value was when focus was gained public void focus gained focus event p focus event old value m text area get text focusgained focusevent pfocusevent oldvalue mtextarea gettext set the text displayed in the label param p label the new label text public void set label string p label m label set text p label plabel setlabel plabel mlabel settext plabel set the text displayed in the text field param p text the new text to display in the text field public void set text string p text m text area set text p text ptext settext ptext mtextarea settext ptext returns the text in the text field return the text in the text field public string get text return m text area get text gettext mtextarea gettext returns the text of the label return the text of the label public string get label return m label get text getlabel mlabel gettext public void set enabled boolean enable super set enabled enable m text area set enabled enable setenabled setenabled mtextarea setenabled registers the text to display in a tool tip the text displays when the cursor lingers over the component param text the string to display if the text is null the tool tip is turned off for this component public void set tool tip text string text m text area set tool tip text text settooltiptext mtextarea settooltiptext returns the tooltip string that has been set with set tool tip text return the text of the tool tip public string get tool tip text return m text area get tool tip text settooltiptext gettooltiptext mtextarea gettooltiptext adds a change listener that will be notified when the text in the text field is changed the change event that will be passed to registered listeners will contain this object as the source allowing the new text to be extracted using the link get text get text method param p change listener the listener to add public void add change listener change listener p change listener m change listeners add p change listener changeevent gettext gettext pchangelistener addchangelistener changelistener pchangelistener mchangelisteners pchangelistener removes a change listener param p change listener the change listener to remove public void remove change listener change listener p change listener m change listeners remove p change listener pchangelistener removechangelistener changelistener pchangelistener mchangelisteners pchangelistener notify all registered change listeners that the text in the text field has changed private void notify change listeners change event ce new change event this for int index 0 index m change listeners size index change listener m change listeners get index state changed ce notifychangelisteners changeevent changeevent mchangelisteners changelistener mchangelisteners statechanged initalize a file reporter from a file public void init string file throws io exception file datafile new file file buffered reader reader null try if datafile can read reader new buffered reader new file reader datafile else j option pane show message dialog null the file you specified cannot be read information j option pane information message return string line while line reader read line null try line line trim if line starts with line length 0 continue int splitter line last index of string key line substring 0 splitter int len line length 1 integer value null if line char at len value new integer line substring splitter 1 len else value new integer line substring splitter 1 vector v get data key if v null v new vector this data put key v v add element value catch number format exception nfe log error this line could not be parsed line nfe catch exception e log error this line caused a problem line e finally if reader null reader close show panel ioexception bufferedreader canread bufferedreader filereader joptionpane showmessagedialog joptionpane information_message readline startswith lastindexof charat getdata addelement numberformatexception showpanel public vector get data string key return vector data get key getdata show main panel with length graph and stats public void show panel j frame f new j frame data file report set layout new border layout graph panel gp new graph panel data add gp center add gp get stats border layout east add gp get legend border layout north f set size 500 300 f get content pane add this f show showpanel jframe jframe setlayout borderlayout graphpanel graphpanel getstats borderlayout getlegend borderlayout setsize getcontentpane public graph panel hashtable data this data data enumeration e data keys while e has more elements string key string e next element keys add element key for int a 0x33 a 0xff a 0x66 for int b 0x33 b 0xff b 0x66 for int c 0x33 c 0xff c 0x66 color list add element new color a b c graphpanel hasmoreelements nextelement addelement colorlist addelement get the maximum for all the data public float get max float max value 0 for int t 0 t keys size t string key string keys element at t vector temp vector data get key for int j 0 j temp size j float f integer temp element at j int value max value math max f max value return float max value max value 0 1 getmax maxvalue elementat elementat intvalue maxvalue maxvalue maxvalue maxvalue get the minimum for all the data public float get min float min value 9999999 for int t 0 t keys size t string key string keys element at t vector temp vector data get key for int j 0 j temp size j float f integer temp element at j int value min value math min f min value return float min value min value 0 1 getmin minvalue elementat elementat intvalue minvalue minvalue minvalue minvalue get the legend panel public j panel get legend j panel main new j panel grid bag layout g new grid bag layout main set layout g grid bag constraints c new grid bag constraints c insets new insets 3 3 3 3 c fill grid bag constraints both c gridwidth 1 c gridheight 1 for int t 0 t keys size t string key string keys element at t j label color swatch new j label color swatch set background color color list element at t color list size color swatch set opaque true c gridx 1 c gridy t g set constraints color swatch c main add color swatch j label name new j label key c gridx 2 c gridy t g set constraints name c main add name return main jpanel getlegend jpanel jpanel gridbaglayout gridbaglayout setlayout gridbagconstraints gridbagconstraints gridbagconstraints elementat jlabel colorswatch jlabel colorswatch setbackground colorlist elementat colorlist colorswatch setopaque setconstraints colorswatch colorswatch jlabel jlabel setconstraints get the stats panel public j panel get stats int total 0 float total value 0 float max value 0 float min value 999999 for int t 0 t keys size t string key string keys element at t vector temp vector data get key for int j 0 j temp size j float f integer temp element at j int value min value math min f min value max value math max f max value total value f total float average value total value total j panel main new j panel grid bag layout g new grid bag layout main set layout g decimal format df new decimal format 0 0 grid bag constraints c new grid bag constraints c insets new insets 3 6 3 6 c fill grid bag constraints both c gridwidth 1 c gridheight 1 j label count new j label count total c gridx 1 c gridy 1 g set constraints count c j label min new j label min df format new float min value c gridx 1 c gridy 2 g set constraints min c j label max new j label max df format new float max value c gridx 1 c gridy 3 g set constraints max c j label average new j label average df format new float average value c gridx 1 c gridy 4 g set constraints average c main add count main add min main add max main add average return main jpanel getstats totalvalue maxvalue minvalue elementat elementat intvalue minvalue minvalue maxvalue maxvalue totalvalue averagevalue totalvalue jpanel jpanel gridbaglayout gridbaglayout setlayout decimalformat decimalformat gridbagconstraints gridbagconstraints gridbagconstraints jlabel jlabel setconstraints jlabel jlabel minvalue setconstraints jlabel jlabel maxvalue setconstraints jlabel jlabel averagevalue setconstraints gets the size of the biggest vector public int get data width int size 0 for int t 0 t keys size t string key string keys element at t vector v vector data get key size math max size v size return size getdatawidth elementat draws the graph public void update graphics g setup drawing area int base 10 g set color color white g fill rect 0 0 get size width get size height int width get size width int height get size height float max value get max float min value get min draw grid g set color color gray int data width get data width int increment math round float width 1 data width 1 for int t 0 t data width t g draw line t increment 0 t increment height int y increment math round float height 1 base 10 1 for int t 0 t 10 t g draw line 0 height t y increment width height t y increment draw axis for int t 1 t data width t data width 25 1 g draw string new integer t to string t increment 2 height 2 float increment value max value min value 10 1 for int t 0 t 10 t g draw string new integer math round min value t increment value to string 2 height t y increment 2 base draw data lines int start 0 for int t 0 t keys size t string key string keys element at t vector v vector data get key start 0 g set color color color list element at t color list size for int i 0 i v size 1 i float y1 integer v element at i int value float y2 integer v element at i 1 int value y1 y1 min value y2 y2 min value int y1 math round height y1 max value min value int y2 math round height y2 max value min value y1 height y1 base y2 height y2 base g draw line start y1 start increment y2 start increment setcolor fillrect getsize getsize getsize getsize maxvalue getmax minvalue getmin setcolor datawidth getdatawidth datawidth datawidth drawline yincrement drawline yincrement yincrement datawidth datawidth drawstring tostring incrementvalue maxvalue minvalue drawstring minvalue incrementvalue tostring yincrement elementat setcolor colorlist elementat colorlist elementat intvalue elementat intvalue minvalue minvalue maxvalue minvalue maxvalue minvalue drawline public void paint graphics g update g create a new argument without a name value or metadata public argument create a new argument with the specified name and value and no metadata param name the argument name param value the argument value public argument string name string value set property new string property arg name name set property new string property value value setproperty stringproperty arg_name setproperty stringproperty create a new argument with the specified name value and metadata param name the argument name param value the argument value param metadata the argument metadata public argument string name string value string metadata set property new string property arg name name set property new string property value value set property new string property metadata metadata setproperty stringproperty arg_name setproperty stringproperty setproperty stringproperty set the name of the argument param new name the new name public void set name string new name set property new string property arg name new name newname setname newname setproperty stringproperty arg_name newname get the name of the argument return the attribute s name public string get name return get property as string arg name getname getpropertyasstring arg_name sets the value of the argument param new value the new value public void set value string new value set property new string property value new value newvalue setvalue newvalue setproperty stringproperty newvalue gets the value of the argument object return the attribute s value public string get value return get property as string value getvalue getpropertyasstring sets the meta data attribute of the argument param new meta data the new metadata public void set meta data string new meta data set property new string property metadata new meta data newmetadata setmetadata newmetadata setproperty stringproperty newmetadata gets the meta data attribute of the argument return the meta data value public string get meta data return get property as string metadata metadata getmetadata getpropertyasstring public string to string return get name get meta data get value tostring getname getmetadata getvalue is this parameter skippable i e empty blank string or it looks like an unrecognised variable param parameter name parameter name return true if parameter should be skipped public boolean is skippable string parameter name if parameter name trim length 0 return true skip parameters with a blank name allows use of optional variables in parameter lists todo improve this test if parameter name trim starts with parameter name ends with non nls 1 non nls 2 return true missing variable name return false parametername isskippable parametername parametername parametername startswith parametername endswith private list order public listed hash tree super order new linked list listedhashtree linkedlist public object clone listed hash tree new tree new listed hash tree clone tree new tree return new tree listedhashtree newtree listedhashtree clonetree newtree newtree public listed hash tree object key super order new linked list data put key new listed hash tree order add key listedhashtree linkedlist listedhashtree public listed hash tree collection keys super order new linked list iterator it keys iterator while it has next object temp it next data put temp new listed hash tree order add temp listedhashtree linkedlist hasnext listedhashtree public listed hash tree object keys super order new linked list for int x 0 x keys length x data put keys x new listed hash tree order add keys x listedhashtree linkedlist listedhashtree public void set object key object value if data contains key key order add key super set key value containskey public void set object key hash tree t if data contains key key order add key super set key t hashtree containskey public void set object key object values if data contains key key order add key super set key values containskey public void set object key collection values if data contains key key order add key super set key values containskey public void replace object current key object new key hash tree tree get tree current key data remove current key data put new key tree order set order index of current key new key currentkey newkey hashtree gettree currentkey currentkey newkey indexof currentkey newkey public hash tree create new tree return new listed hash tree hashtree createnewtree listedhashtree public hash tree create new tree object key return new listed hash tree key hashtree createnewtree listedhashtree public hash tree create new tree collection values return new listed hash tree values hashtree createnewtree listedhashtree public hash tree add object key if data contains key key hash tree new tree create new tree data put key new tree order add key return new tree return get tree key hashtree containskey hashtree newtree createnewtree newtree newtree gettree public collection list return order public object remove object key order remove key return data remove key public object get array return order to array getarray toarray make sure the hash code depends on the order as well public int hash code int hc 17 hc hc 37 order null 0 order hash code hc hc 37 super hash code return hc hashcode hashcode hashcode hashcode public boolean equals object o if o instanceof listed hash tree return false listed hash tree lht listed hash tree o return super equals lht order equals lht order boolean flag true if o instanceof listed hash tree listed hash tree oo listed hash tree o iterator it order iterator iterator it2 oo order iterator if size oo size flag false while it has next it2 has next flag if it next equals it2 next flag false if flag it order iterator while it has next flag object temp it next flag get temp equals oo get temp else flag false return flag listedhashtree listedhashtree listedhashtree listedhashtree listedhashtree listedhashtree hasnext hasnext hasnext public set key set return data key set keyset keyset public int size return data size private void read object object input stream ois throws class not found exception io exception ois default read object readobject objectinputstream classnotfoundexception ioexception defaultreadobject private void write object object output stream oos throws io exception oos default write object writeobject objectoutputstream ioexception defaultwriteobject see java util map clear public void clear super clear order clear final print writer pw final sample save configuration config file entry print writer pw sample save configuration config pw pw config config printwriter samplesaveconfiguration fileentry printwriter _pw samplesaveconfiguration _config _pw _config no arg constructor public result collector set error logging false set success only logging false set property new object property save config new sample save configuration resultcollector seterrorlogging setsuccessonlylogging setproperty objectproperty save_config samplesaveconfiguration n b clone only seems to be used for client server tests public object clone result collector clone result collector super clone clone set save config sample save configuration clone get save config clone return clone resultcollector resultcollector setsaveconfig samplesaveconfiguration getsaveconfig private void set filename property string f set property filename f setfilenameproperty setproperty public string get filename return get property as string filename getfilename getpropertyasstring public boolean is error logging return get property as boolean error logging iserrorlogging getpropertyasboolean error_logging public void set error logging boolean error logging set property new boolean property error logging error logging seterrorlogging errorlogging setproperty booleanproperty error_logging errorlogging public void set success only logging boolean value if value set property new boolean property success only logging true else remove property success only logging setsuccessonlylogging setproperty booleanproperty success_only_logging removeproperty success_only_logging public boolean is success only logging return get property as boolean success only logging false issuccessonlylogging getpropertyasboolean success_only_logging decides whether or not to a sample is wanted based on br error only br success only br sample success br should only be called for single samples param success is sample successful return whether to log display the sample public boolean is sample wanted boolean success boolean error only is error logging boolean success only is success only logging return is sample wanted success error only success only erroronly successonly issamplewanted erroronly iserrorlogging successonly issuccessonlylogging issamplewanted erroronly successonly decides whether or not to a sample is wanted based on br error only br success only br sample success br this version is intended to be called by code that loops over many samples it is cheaper than fetching the settings each time param success status of sample param error only if errors only wanted param success only if success only wanted return whether to log display the sample public static boolean is sample wanted boolean success boolean error only boolean success only return error only success only success success only success error only success only and error only cannot both be set erroronly successonly erroronly successonly issamplewanted erroronly successonly erroronly successonly successonly erroronly successonly erroronly sets the filename attribute of the result collector object param f the new filename value public void set filename string f if in test return set filename property f resultcollector setfilename intest setfilenameproperty public void test ended string host synchronized lock instance count if instance count 0 finalize file output in test false testended instancecount instancecount finalizefileoutput intest public synchronized void test started string host synchronized lock instance count try initialize file output if get visualizer null this is stats get visualizer is stats catch exception e log error e in test true teststarted instancecount initializefileoutput getvisualizer isstats getvisualizer isstats intest public void test ended test ended test is local testended testended test_is_local public void test started test started test is local teststarted teststarted test_is_local loads an existing sample data jtl file this can be one of x stream format avalon format csv format public void load existing file final visualizer visualizer get visualizer if visualizer null return no point reading the file if there s no visualiser boolean parsedok false string filename get filename file file new file filename if file exists buffered reader data reader null buffered input stream buffered input stream null try data reader new buffered reader new file reader file get the first line and see if it is xml string line data reader read line data reader close data reader null if line null log warn filename is empty else if line starts with xml no must be csv non nls 1 csv save service process samples filename visualizer this parsedok true else we are processing xml try assume x stream buffered input stream new buffered input stream new file input stream file save service load test results buffered input stream new result collector helper this visualizer parsedok true catch exception e log info failed to load filename using x stream trying old xml format error was e try old save service process samples filename visualizer this parsedok true catch exception e1 log warn error parsing avalon xml e1 get localized message catch io exception e log warn problem reading jtl file file catch j meter error e log warn problem reading jtl file file catch runtime exception e e g null pointer exception log warn problem reading jtl file file e catch out of memory error e log warn problem reading jtl file file e finally j orphan utils close quietly data reader j orphan utils close quietly buffered input stream if parsedok gui package show error message error loading results file see log file result file loader else gui package show error message error loading results file could not open file result file loader xstream loadexistingfile getvisualizer getfilename bufferedreader datareader bufferedinputstream bufferedinputstream datareader bufferedreader filereader datareader readline datareader datareader startswith csvsaveservice processsamples xstream bufferedinputstream bufferedinputstream fileinputstream saveservice loadtestresults bufferedinputstream resultcollectorhelper xstream oldsaveservice processsamples getlocalizedmessage ioexception jmetererror runtimeexception nullpointerexception outofmemoryerror jorphanutils closequietly datareader jorphanutils closequietly bufferedinputstream guipackage showerrormessage guipackage showerrormessage private static void write file start print writer writer sample save configuration save config if save config save as xml writer print xml header write the eol separately so we generate lf line ends on unix and windows writer print n non nls 1 string pi save config get xml pi if pi length 0 writer println pi can t do it as a static initialisation because save service is being constructed when this is called writer print testresults start v1 1 prever writer print save service getversion writer print testresults start v1 1 postver write the eol separately so we generate lf line ends on unix and windows writer print n non nls 1 else if save config save field names writer println csv save service printable field names to string save config writefilestart printwriter samplesaveconfiguration saveconfig saveconfig saveasxml xml_header saveconfig getxmlpi saveservice testresults_start_v1_1_prever saveservice testresults_start_v1_1_postver saveconfig savefieldnames csvsaveservice printablefieldnamestostring saveconfig private static void write file end print writer pw sample save configuration save config if save config save as xml pw print n non nls 1 pw print testresults end pw print n added in version 1 1 non nls 1 writefileend printwriter samplesaveconfiguration saveconfig saveconfig saveasxml testresults_end private static print writer get file writer string filename sample save configuration save config throws io exception if filename null filename length 0 return null file entry fe file entry files get filename print writer writer null boolean trimmed true if fe null if save config save as xml trimmed trim last line filename else trimmed new file filename exists find the name of the directory containing the file and create it if there is one file pdir new file filename get parent file if pdir null pdir mkdirs returns false if directory already exists so need to check again if pdir exists log warn error creating directories for pdir to string writer new print writer new output stream writer new buffered output stream new file output stream filename trimmed save service get file encoding utf 8 true non nls 1 log debug opened file filename files put filename new file entry writer save config else writer fe pw if trimmed write file start writer save config return writer printwriter getfilewriter samplesaveconfiguration saveconfig ioexception fileentry fileentry printwriter saveconfig saveasxml trimlastline getparentfile tostring printwriter outputstreamwriter bufferedoutputstream fileoutputstream saveservice getfileencoding fileentry saveconfig writefilestart saveconfig returns false if the file did not contain the terminator private static boolean trim last line string filename random access file raf null try raf new random access file filename rw non nls 1 long len raf length if len min xml file len return false raf seek len testresults end length 10 todo may not work on all o ses string line long pos raf get file pointer int end 0 while line raf read line null reads to end of line or end of file end line index of testresults end if end 0 found the string break pos raf get file pointer if line null log warn unexpected eof trying to find xml end marker in filename raf close return false raf set length pos end truncate the file raf close raf null catch file not found exception e return false catch io exception e log warn error trying to find xml terminator e to string return false finally try if raf null raf close catch io exception e1 log info could not close filename e1 get localized message return true trimlastline randomaccessfile randomaccessfile min_xml_file_len testresults_end oses getfilepointer readline indexof testresults_end getfilepointer setlength filenotfoundexception ioexception tostring ioexception getlocalizedmessage public void sample started sample event e samplestarted sampleevent public void sample stopped sample event e samplestopped sampleevent when a test result is received display it and save it param event the sample event that was received public void sample occurred sample event event sample result result event get result if is sample wanted result is successful send to visualizer result if out null is result marked result this is stats sample save configuration config get save config result set save config config try if config save as xml if save service is save test log format20 if serializer null serializer new default configuration serializer out write old save service get serialized sample result result serializer config else log format20 save service save sample result event out else save as xml string savee csv save service result to delimited string event out println savee catch exception err log error error trying to record a sample err should throw exception back to caller sampleoccurred sampleevent sampleresult getresult issamplewanted issuccessful sendtovisualizer isresultmarked isstats samplesaveconfiguration getsaveconfig setsaveconfig saveasxml saveservice issavetestlogformat20 defaultconfigurationserializer oldsaveservice getserializedsampleresult logformat20 saveservice savesampleresult saveasxml csvsaveservice resulttodelimitedstring protected final void send to visualizer sample result r if get visualizer null get visualizer add r sendtovisualizer sampleresult getvisualizer getvisualizer record stats is used to save statistics generated by visualizers param e throws exception used by monitor health visualizer add sample result res public void record stats test element e throws exception if out null save service save test element e out recordstats monitorhealthvisualizer sampleresult recordstats testelement saveservice savetestelement checks if the sample result is marked or not and marks it param res the sample result to check return code true code if the result was marked private boolean is result marked sample result res string filename get filename return res mark file filename isresultmarked sampleresult getfilename markfile private void initialize file output throws io exception string filename get filename if filename null if out null try out get file writer filename get save config catch file not found exception e out null initializefileoutput ioexception getfilename getfilewriter getsaveconfig filenotfoundexception private void finalize file output iterator it files entry set iterator while it has next map entry me map entry it next log debug closing me get key file entry fe file entry me get value write file end fe pw fe config fe pw close if fe pw check error log warn problem detected during use of me get key files clear finalizefileoutput entryset hasnext getkey fileentry fileentry getvalue writefileend checkerror getkey see test listener test iteration start loop iteration event public void test iteration start loop iteration event event testlistener testiterationstart loopiterationevent testiterationstart loopiterationevent return returns the save config public sample save configuration get save config try return sample save configuration get property save config get object value catch class cast exception e set save config new sample save configuration return get save config saveconfig samplesaveconfiguration getsaveconfig samplesaveconfiguration getproperty save_config getobjectvalue classcastexception setsaveconfig samplesaveconfiguration getsaveconfig param save config the save config to set public void set save config sample save configuration save config get property save config set object value save config saveconfig saveconfig setsaveconfig samplesaveconfiguration saveconfig getproperty save_config setobjectvalue saveconfig see org apache jmeter gui tree j meter tree model get nodes of type can find the clearable nodes the user object has to implement the interface public void clear data jmetertreemodel getnodesoftype userobject cleardata private j text field parameters parameters to pass to script file or script public bsf sampler gui init jtextfield bsfsamplergui public void configure test element element super configure element bsf sampler sampler bsf sampler element script field set text sampler get script lang field set selected item sampler get script language filename set text sampler get filename parameters set text sampler get parameters testelement bsfsampler bsfsampler scriptfield settext getscript langfield setselecteditem getscriptlanguage settext getfilename settext getparameters public test element create test element bsf sampler sampler new bsf sampler modify test element sampler return sampler testelement createtestelement bsfsampler bsfsampler modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element te te clear this configure test element te bsf sampler sampler bsf sampler te sampler set filename filename get text sampler set script language string lang field get selected item sampler set parameters parameters get text sampler set script script field get text testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement bsfsampler bsfsampler setfilename gettext setscriptlanguage langfield getselecteditem setparameters gettext setscript scriptfield gettext implements j metergui component clear gui public void clear gui super clear gui script field set text non nls 1 lang field set selected index 0 filename set text non nls 1 parameters set text non nls 1 jmeterguicomponent cleargui cleargui cleargui scriptfield settext langfield setselectedindex settext settext public string get label resource return bsf sampler title non nls 1 getlabelresource bsf_sampler_title private void init set layout new border layout 0 5 set border make border box box box create vertical box box add make title panel box add create language panel box add create filename panel box add create parameter panel add box border layout north j panel panel create script panel add panel border layout center don t let the input field shrink too much add box create vertical strut panel get preferred size height border layout west setlayout borderlayout setborder makeborder createverticalbox maketitlepanel createlanguagepanel createfilenamepanel createparameterpanel borderlayout jpanel createscriptpanel borderlayout createverticalstrut getpreferredsize borderlayout private j panel create parameter panel j label label new j label j meter utils get res string bsf script parameters non nls 1 parameters new j text field 10 label set label for parameters j panel parameter panel new j panel new border layout 5 0 parameter panel add label border layout west parameter panel add parameters border layout center return parameter panel jpanel createparameterpanel jlabel jlabel jmeterutils getresstring bsf_script_parameters jtextfield setlabelfor jpanel parameterpanel jpanel borderlayout parameterpanel borderlayout parameterpanel borderlayout parameterpanel private j panel create filename panel todo ought to be a file chooser j label label new j label j meter utils get res string bsf script file non nls 1 filename new j text field 10 label set label for filename j panel filename panel new j panel new border layout 5 0 filename panel add label border layout west filename panel add filename border layout center return filename panel jpanel createfilenamepanel filechooser jlabel jlabel jmeterutils getresstring bsf_script_file jtextfield setlabelfor jpanel filenamepanel jpanel borderlayout filenamepanel borderlayout filenamepanel borderlayout filenamepanel private j panel create language panel j label label new j label j meter utils get res string bsf script language non nls 1 properties p j meter utils load properties org apache bsf languages properties non nls 1 we have added jexl in bsf sampler p put jexl non nls 1 set key set p key set todo perhaps weed out ones which don t exist string items string key set to array new string arrays sort items lang field new j combo box items lang field set editable true label set label for lang field j panel lang panel new j panel new border layout 5 0 lang panel add label border layout west lang panel add lang field border layout center return lang panel jpanel createlanguagepanel jlabel jlabel jmeterutils getresstring bsf_script_language jmeterutils loadproperties bsfsampler keyset keyset keyset toarray langfield jcombobox langfield seteditable setlabelfor langfield jpanel langpanel jpanel borderlayout langpanel borderlayout langpanel langfield borderlayout langpanel private j panel create script panel script field new j text area script field set rows 4 script field set line wrap true script field set wrap style word true j label label new j label j meter utils get res string bsf script non nls 1 label set label for script field j panel panel new j panel new border layout panel add label border layout north panel add new j scroll pane script field border layout center return panel jpanel createscriptpanel scriptfield jtextarea scriptfield setrows scriptfield setlinewrap scriptfield setwrapstyleword jlabel jlabel jmeterutils getresstring bsf_script setlabelfor scriptfield jpanel jpanel borderlayout borderlayout jscrollpane scriptfield borderlayout public j meter thread hash tree test j meter thread monitor monitor listener notifier note this monitor monitor thread vars new j meter variables test tree test compiler new test compiler test tree thread vars controller controller test tree get array 0 search by class thread listener searcher new search by class test listener class test traverse thread listener searcher test listeners thread listener searcher get search results notifier note running true jmeterthread hashtree jmeterthreadmonitor listenernotifier threadvars jmetervariables testtree testcompiler testtree threadvars testtree getarray searchbyclass threadlistenersearcher searchbyclass testlistener threadlistenersearcher testlisteners threadlistenersearcher getsearchresults public void set initial context j meter context context thread vars put all context get variables setinitialcontext jmetercontext threadvars putall getvariables enable the scheduler for this j meter thread public void set scheduled boolean sche this scheduler sche jmeterthread setscheduled set the start time for this thread param stime the start time value public void set start time long stime start time stime starttime starttime setstarttime starttime get the start time value return the start time value public long get start time return start time getstarttime starttime set the end time for this thread param etime the end time value public void set end time long etime end time etime endtime endtime setendtime endtime get the end time value return the end time value public long get end time return end time getendtime endtime check the scheduled time is completed private void stop scheduler long delay system current time millis end time if delay 0 running false stopscheduler currenttimemillis endtime wait until the scheduled start time if necessary private void start scheduler long delay start time system current time millis if delay 0 try thread sleep delay catch exception e startscheduler starttime currenttimemillis public void set thread name string thread name this thread name thread name setthreadname threadname threadname threadname public void run thread context is not thread safe so keep within thread j meter context thread context j meter context service get context try init run thread context while running sampler sam while running sam controller next null process sampler sam null thread context if controller is done running false might be found by contoller next catch j meter stop test exception e log info stopping test e to string stop test catch j meter stop test now exception e log info stopping test now e to string stop test now catch j meter stop thread exception e log info stop thread seen e to string catch exception e log error test failed e catch thread death e throw e must not ignore this one catch error e make sure errors are output to the log file log error test failed e finally thread context clear log info thread finished thread name thread finished monitor thread finished this tell the engine we are done threadcontext jmetercontext threadcontext jmetercontextservice getcontext initrun threadcontext process_sampler threadcontext isdone jmeterstoptestexception tostring stoptest jmeterstoptestnowexception tostring stoptestnow jmeterstopthreadexception tostring threaddeath threadcontext threadname threadfinished threadfinished process the current sampler handling transaction samplers param current sampler param parent sampler param thread context return sample result if a transaction was processed private sample result process sampler sampler current sampler parent j meter context thread context sample result transaction result null try check if we are running a transaction transaction sampler transaction sampler null if current instanceof transaction sampler transaction sampler transaction sampler current find the package for the transaction sample package transaction pack null if transaction sampler null transaction pack compiler configure transaction sampler transaction sampler check if the transaction is done if transaction sampler is transaction done get the transaction sample result transaction result transaction sampler get transaction result transaction result set thread name thread name transaction result set group threads thread group get number of threads transaction result set all threads j meter context service get number of threads check assertions for the transaction sample check assertions transaction pack get assertions transaction result thread context notify listeners with the transaction sample result if parent instanceof transaction sampler notify listeners transaction pack get sample listeners transaction result compiler done transaction pack transaction is done we do not have a sampler to sample current null else sampler prev current it is the sub sampler of the transaction that will be sampled current transaction sampler get sub sampler if current instanceof transaction sampler sample result res process sampler current prev thread context recursive call thread context set current sampler prev current null if res null transaction sampler add sub sampler result res check if we have a sampler to sample if current null thread context set current sampler current get the sampler ready to sample sample package pack compiler configure sampler current run pre processors pack get pre processors hack save the package for any transaction controllers thread vars put object package object pack delay pack get timers sampler sampler pack get sampler sampler set thread context thread context sampler set thread name thread name test bean helper prepare sampler perform the actual sample current sampler sampler sample result result sampler sample null current sampler null todo remove this useless entry parameter if we got any results then perform processing on the result if result null result set group threads thread group get number of threads result set all threads j meter context service get number of threads result set thread name thread name thread context set previous result result run post processors pack get post processors check assertions pack get assertions result thread context do not send subsamples to listeners which receive the transaction sample list sample listeners get sample listeners pack transaction pack transaction sampler notify listeners sample listeners result compiler done pack add the result as subsample of transaction if we are in a transaction if transaction sampler null transaction sampler add sub sampler result result check if thread or test should be stopped if result is stop thread result is successful on error stop thread stop thread if result is stop test result is successful on error stop test stop test if result is stop test now result is successful on error stop test now stop test now else compiler done pack finish up if scheduler checks the scheduler to stop the iteration stop scheduler catch j meter stop test exception e log info stopping test e to string stop test catch j meter stop thread exception e log info stopping thread e to string stop thread catch exception e if current null log error error while processing sampler current get name e else log error e return transaction result threadcontext sampleresult sampleresult process_sampler jmetercontext threadcontext sampleresult transactionresult transactionsampler transactionsampler transactionsampler transactionsampler transactionsampler samplepackage transactionpack transactionsampler transactionpack configuretransactionsampler transactionsampler transactionsampler istransactiondone transactionresult transactionsampler gettransactionresult transactionresult setthreadname threadname transactionresult setgroupthreads threadgroup getnumberofthreads transactionresult setallthreads jmetercontextservice getnumberofthreads checkassertions transactionpack getassertions transactionresult threadcontext transactionsampler notifylisteners transactionpack getsamplelisteners transactionresult transactionpack transactionsampler getsubsampler transactionsampler sampleresult process_sampler threadcontext threadcontext setcurrentsampler transactionsampler addsubsamplerresult threadcontext setcurrentsampler samplepackage configuresampler runpreprocessors getpreprocessors threadvars putobject package_object gettimers getsampler setthreadcontext threadcontext setthreadname threadname testbeanhelper currentsampler sampleresult currentsampler setgroupthreads threadgroup getnumberofthreads setallthreads jmetercontextservice getnumberofthreads setthreadname threadname threadcontext setpreviousresult runpostprocessors getpostprocessors checkassertions getassertions threadcontext samplelisteners getsamplelisteners transactionpack transactionsampler notifylisteners samplelisteners transactionsampler transactionsampler addsubsamplerresult isstopthread issuccessful onerrorstopthread stopthread isstoptest issuccessful onerrorstoptest stoptest isstoptestnow issuccessful onerrorstoptestnow stoptestnow stopscheduler jmeterstoptestexception tostring stoptest jmeterstopthreadexception tostring stopthread getname transactionresult get the sample listeners for the sampler listeners who receive transaction sample will not be in this list param sample pack param transaction pack param transaction sampler return the listeners who should receive the sample result private list get sample listeners sample package sample pack sample package transaction pack transaction sampler transaction sampler list sample listeners sample pack get sample listeners do not send subsamples to listeners which receive the transaction sample if transaction sampler null array list only sub sampler listeners new array list list trans listeners transaction pack get sample listeners for iterator i sample listeners iterator i has next sample listener listener sample listener i next check if this instance is present in transaction listener list boolean found false for iterator j trans listeners iterator j has next check for the same instance if j next listener found true break if found only sub sampler listeners add listener sample listeners only sub sampler listeners return sample listeners samplelisteners samplepack transactionpack transactionsampler getsamplelisteners samplepackage samplepack samplepackage transactionpack transactionsampler transactionsampler samplelisteners samplepack getsamplelisteners transactionsampler arraylist onlysubsamplerlisteners arraylist translisteners transactionpack getsamplelisteners samplelisteners hasnext samplelistener samplelistener translisteners hasnext onlysubsamplerlisteners samplelisteners onlysubsamplerlisteners samplelisteners param thread context private void init run j meter context thread context thread context set variables thread vars thread context set thread num get thread num thread context get variables put last sample ok true thread context set thread this thread context set thread group thread group thread context set engine engine test tree traverse compiler listeners controller get listeners if scheduler set the scheduler to start start scheduler ramp up delay todo how to handle thread stopped here log info thread started thread current thread get name setting sampling started before the contollers are initialised allows them to access the running values of functions and variables however it does not seem to help with the listeners if start earlier thread context set sampling started true controller initialize controller add iteration listener new iteration listener if start earlier thread context set sampling started true thread started threadcontext initrun jmetercontext threadcontext threadcontext setvariables threadvars threadcontext setthreadnum getthreadnum threadcontext getvariables last_sample_ok threadcontext setthread threadcontext setthreadgroup threadgroup threadcontext setengine testtree getlisteners startscheduler rampupdelay currentthread getname samplingstarted startearlier threadcontext setsamplingstarted additerationlistener iterationlistener startearlier threadcontext setsamplingstarted threadstarted private void thread started j meter context service incr number of threads thread group incr number of threads gui package gp gui package get instance if gp null check there is a gui gp get main frame update counts thread listener traverser startup new thread listener traverser true test tree traverse startup call thread listener thread started threadstarted jmetercontextservice incrnumberofthreads threadgroup incrnumberofthreads guipackage guipackage getinstance getmainframe updatecounts threadlistenertraverser threadlistenertraverser testtree threadlistener threadstarted private void thread finished thread listener traverser shut new thread listener traverser false test tree traverse shut call thread listener thread finished j meter context service decr number of threads thread group decr number of threads gui package gp gui package get instance if gp null check there is a gui gp get main frame update counts threadfinished threadlistenertraverser threadlistenertraverser testtree threadlistener threadfinished jmetercontextservice decrnumberofthreads threadgroup decrnumberofthreads guipackage guipackage getinstance getmainframe updatecounts private boolean is start false private thread listener traverser boolean start is start start isstart threadlistenertraverser isstart public void add node object node hash tree sub tree if node instanceof thread listener thread listener tl thread listener node if is start tl thread started else tl thread finished addnode hashtree subtree threadlistener threadlistener threadlistener isstart threadstarted threadfinished public void subtract node subtractnode public void process path processpath public string get thread name return thread name getthreadname threadname public void stop called by standardj meter engine test action and access log sampler running false log info stopping thread name standardjmeterengine testaction accesslogsampler threadname inherit doc public boolean interrupt sampler samp current sampler fetch once if samp instanceof interruptible log warn interrupting thread name sampler samp get name try boolean found interruptible samp interrupt if found log warn no operation pending return found catch exception e log warn caught exception interrupting sampler e to string else if samp null log warn sampler is not interruptible samp get name return false inheritdoc currentsampler threadname getname tostring getname private void stop test running false log info stop test detected by thread thread name if engine null engine ask threads to stop stoptest threadname askthreadstostop private void stop test now running false log info stop test now detected by thread thread name if engine null engine stop test stoptestnow threadname stoptest private void stop thread running false log info stop thread detected by thread thread name stopthread threadname private void check assertions list assertions sample result parent j meter context thread context iterator iter assertions iterator while iter has next assertion assertion assertion iter next test bean helper prepare test element assertion if assertion instanceof abstract scoped assertion abstract scoped assertion scoped assertion abstract scoped assertion assertion string scope scoped assertion fetch scope if scoped assertion is scope parent scope scoped assertion is scope all scope process assertion parent assertion if scoped assertion is scope children scope scoped assertion is scope all scope sample result children parent get sub results boolean child error false for int i 0 i children length i process assertion children i assertion if children i is successful child error true if parent is ok but child failed add a message and flag the parent as failed if child error parent is successful assertion result assertion result new assertion result abstract test element assertion get name assertion result set result for failure one or more sub samples failed parent add assertion result assertion result parent set successful false else process assertion parent assertion thread context get variables put last sample ok boolean to string parent is successful checkassertions sampleresult jmetercontext threadcontext hasnext testbeanhelper testelement abstractscopedassertion abstractscopedassertion scopedassertion abstractscopedassertion scopedassertion fetchscope scopedassertion isscopeparent scopedassertion isscopeall processassertion scopedassertion isscopechildren scopedassertion isscopeall sampleresult getsubresults childerror processassertion issuccessful childerror childerror issuccessful assertionresult assertionresult assertionresult abstracttestelement getname assertionresult setresultforfailure addassertionresult assertionresult setsuccessful processassertion threadcontext getvariables last_sample_ok tostring issuccessful private void process assertion sample result result assertion assertion assertion result assertion result assertion get result result result set successful result is successful assertion result is error assertion result is failure result add assertion result assertion result processassertion sampleresult assertionresult assertionresult getresult setsuccessful issuccessful assertionresult iserror assertionresult isfailure addassertionresult assertionresult private void run post processors list extractors list iterator iter if reverse post processors original rather odd behaviour iter extractors list iterator extractors size start at the end while iter has previous post processor ex post processor iter previous test bean helper prepare test element ex ex process else iter extractors list iterator start at the beginning while iter has next post processor ex post processor iter next test bean helper prepare test element ex ex process runpostprocessors listiterator reversepostprocessors listiterator hasprevious postprocessor postprocessor testbeanhelper testelement listiterator hasnext postprocessor postprocessor testbeanhelper testelement private void run pre processors list pre processors iterator iter pre processors iterator while iter has next pre processor ex pre processor iter next if log is debug enabled log debug running preprocessor abstract test element ex get name test bean helper prepare test element ex ex process runpreprocessors preprocessors preprocessors hasnext preprocessor preprocessor isdebugenabled abstracttestelement getname testbeanhelper testelement private void delay list timers long sum 0 iterator iter timers iterator while iter has next timer timer timer iter next test bean helper prepare test element timer sum timer delay if sum 0 try thread sleep sum catch interrupted exception e log warn the delay timer was interrupted probably did not wait as long as intended hasnext testbeanhelper testelement interruptedexception private void notify test listeners thread vars inc iteration iterator iter test listeners iterator while iter has next test listener listener test listener iter next if listener instanceof test element listener test iteration start new loop iteration event controller thread vars get iteration test element listener recover running version else listener test iteration start new loop iteration event controller thread vars get iteration notifytestlisteners threadvars inciteration testlisteners hasnext testlistener testlistener testelement testiterationstart loopiterationevent threadvars getiteration testelement recoverrunningversion testiterationstart loopiterationevent threadvars getiteration private void notify listeners list listeners sample result result sample event event new sample event result thread group get name thread vars notifier notify listeners event listeners notifylisteners sampleresult sampleevent sampleevent threadgroup getname threadvars notifylisteners public void set initial delay int delay initial delay delay setinitialdelay initialdelay initial delay if ramp up period is active for this thread group private void ramp up delay if initial delay 0 long start system current time millis try thread sleep initial delay catch interrupted exception e long actual system current time millis start log warn ramp up delay for thread name was interrupted waited actual milli seconds out of initial delay threadgroup rampupdelay initialdelay currenttimemillis initialdelay interruptedexception currenttimemillis rampup threadname initialdelay returns the thread num public int get thread num return thread num threadnum getthreadnum threadnum sets the thread num param thread num the thread num to set public void set thread num int thread num this thread num thread num threadnum threadnum threadnum setthreadnum threadnum threadnum threadnum see loop iteration listener iteration start loop iteration event public void iteration start loop iteration event iter event notify test listeners loopiterationlistener iterationstart loopiterationevent iterationstart loopiterationevent iterevent notifytestlisteners save the engine instance for access to the stop methods param engine public void set engine standardj meter engine engine this engine engine setengine standardjmeterengine should test stop on sampler error param b true or false public void set on error stop test boolean b on error stop test b setonerrorstoptest onerrorstoptest should test stop abruptly on sampler error param b true or false public void set on error stop test now boolean b on error stop test now b setonerrorstoptestnow onerrorstoptestnow should thread stop on sampler error param b true or false public void set on error stop thread boolean b on error stop thread b setonerrorstopthread onerrorstopthread public void set thread group thread group group this thread group group setthreadgroup threadgroup threadgroup public csv data set bean info super csv data set class resource bundle rb resource bundle get bean descriptor get value resource bundle these must agree with the resources share tags share all rb get string share mode all non nls 1 share tags share group rb get string share mode group non nls 1 share tags share thread rb get string share mode thread non nls 1 create property group csv data non nls 1 new string filename file encoding variable names delimiter quoted data recycle stopthread sharemode property descriptor p property filename p set value not undefined boolean true p set value default non nls 1 p set value not expression boolean true p property file encoding p set value not undefined boolean true p set value default non nls 1 p set value not expression boolean true p property variable names p set value not undefined boolean true p set value default non nls 1 p set value not expression boolean true p property delimiter p set value not undefined boolean true p set value default non nls 1 p set value not expression boolean true p property quoted data p set value not undefined boolean true p set value default boolean false p property recycle p set value not undefined boolean true p set value default boolean true p property stopthread p set value not undefined boolean true p set value default boolean false p property sharemode non nls 1 p set value not undefined boolean true p set value default share tags 0 p set value not other boolean false p set value not expression boolean false p set value tags share tags csvdatasetbeaninfo csvdataset resourcebundle resourcebundle getbeandescriptor getvalue resource_bundle share_tags share_all getstring sharemode share_tags share_group getstring sharemode share_tags share_thread getstring sharemode createpropertygroup csv_data file_encoding variable_names quoted_data propertydescriptor setvalue not_undefined setvalue setvalue not_expression file_encoding setvalue not_undefined setvalue setvalue not_expression variable_names setvalue not_undefined setvalue setvalue not_expression setvalue not_undefined setvalue setvalue not_expression quoted_data setvalue not_undefined setvalue setvalue not_undefined setvalue setvalue not_undefined setvalue setvalue not_undefined setvalue share_tags setvalue not_other setvalue not_expression setvalue share_tags todo need to find better way to do this public static int get share mode as int string mode if mode null mode length 0 return share all default e g if test plan does not have definition for int i 0 i share tags length i if share tags i equals mode return i return 1 getsharemodeasint share_all share_tags share_tags private map variables new hash map public value replacer hashmap valuereplacer public value replacer test plan tp set user defined variables tp get user defined variables valuereplacer testplan setuserdefinedvariables getuserdefinedvariables boolean contains key string k return variables contains key k containskey containskey return variables contains key k public void set user defined variables map variables this variables variables containskey setuserdefinedvariables public void replace values test element el throws invalid variable exception collection new props replace values el property iterator new replace string with functions master function variables set properties el new props replacevalues testelement invalidvariableexception newprops replacevalues propertyiterator replacestringwithfunctions masterfunction setproperties newprops private void set properties test element el collection new props iterator iter new props iterator el clear while iter has next el set property j meter property iter next setproperties testelement newprops newprops hasnext setproperty jmeterproperty public void reverse replace test element el throws invalid variable exception collection new props replace values el property iterator new replace functions with strings master function variables set properties el new props reversereplace testelement invalidvariableexception newprops replacevalues propertyiterator replacefunctionswithstrings masterfunction setproperties newprops public void reverse replace test element el boolean regex match throws invalid variable exception collection new props replace values el property iterator new replace functions with strings master function variables regex match set properties el new props reversereplace testelement regexmatch invalidvariableexception newprops replacevalues propertyiterator replacefunctionswithstrings masterfunction regexmatch setproperties newprops public void undo reverse replace test element el throws invalid variable exception collection new props replace values el property iterator new undo variable replacement master function variables set properties el new props undoreversereplace testelement invalidvariableexception newprops replacevalues propertyiterator undovariablereplacement masterfunction setproperties newprops public void add variable string name string value variables put name value addvariable add all the given variables to this replacer s variables map param vars a map of variable name value pairs string to string public void add variables map vars variables put all vars addvariables putall private collection replace values property iterator iter value transformer transform throws invalid variable exception list props new linked list while iter has next j meter property val iter next if log is debug enabled log debug about to replace in property of type val get class val if val instanceof string property must not convert test element gui class etc if val get name equals test element gui class val get name equals test element test class val transform transform value val if log is debug enabled log debug replacement result val else if val instanceof multi property multi property multi val multi property val collection new values replace values multi val iterator transform multi val clear iterator prop iter new values iterator while prop iter has next multi val add property j meter property prop iter next if log is debug enabled log debug replacement result multi val else if log is debug enabled log debug won t replace val props add val return props replacevalues propertyiterator valuetransformer invalidvariableexception linkedlist hasnext jmeterproperty isdebugenabled getclass stringproperty testelement gui_class getname testelement gui_class getname testelement test_class transformvalue isdebugenabled multiproperty multiproperty multival multiproperty newvalues replacevalues multival multival propiter newvalues propiter hasnext multival addproperty jmeterproperty propiter isdebugenabled multival isdebugenabled private object soap header null public header manager set property new collection property headers new array list soapheader headermanager setproperty collectionproperty arraylist public void clear super clear set property new collection property headers new array list setproperty collectionproperty arraylist get the collection of j meter property entries representing the headers return the header collection property public collection property get headers return collection property get property headers jmeterproperty collectionproperty getheaders collectionproperty getproperty public int get column count return column count getcolumncount column_count public string get column name int column return column resource names column getcolumnname column_resource_names public class get column class int column return column resource names column get class getcolumnclass column_resource_names getclass public header get header int row return header get headers get row get object value getheader getheaders getobjectvalue save the header data to a file public void save string head file throws io exception file file new file head file if file is absolute file new file system get property user dir non nls 1 file separator head file print writer writer new print writer new file writer file writer println j meter generated header file non nls 1 final collection property hdrs get headers for int i 0 i hdrs size i final j meter property hdr hdrs get i header head header hdr get object value writer println head to string writer flush writer close headfile ioexception headfile isabsolute getproperty headfile printwriter printwriter filewriter jmeter collectionproperty getheaders jmeterproperty getobjectvalue tostring add header data from a file public void add file string header file throws io exception file file new file header file if file is absolute file new file system get property user dir non nls 1 file separator header file if file can read throw new io exception the file you specified cannot be read buffered reader reader null try reader new buffered reader new file reader file string line while line reader read line null try if line starts with line trim length 0 non nls 1 continue string st j orphan utils split line t non nls 1 non nls 2 int name 0 int value 1 header header new header st name st value get headers add item header catch exception e throw new io exception error parsing header line n t line n t e finally io utils close quietly reader addfile headerfile ioexception headerfile isabsolute getproperty headerfile canread ioexception bufferedreader bufferedreader filereader readline startswith jorphanutils getheaders additem ioexception ioutils closequietly add a header public void add header h get headers add item h getheaders additem add an empty header public void add get headers add item new header getheaders additem remove a header public void remove int index get headers remove index getheaders return the number of headers public int size return get headers size getheaders return the header at index i public header get int i return header get headers get i get object value getheaders getobjectvalue public void remove header named string name vector remove indices new vector for int i get headers size 1 i 0 i header header header get headers get i get object value if header null continue if header get name equals ignore case name remove indices add element new integer i for enumeration e remove indices elements e has more elements get headers remove integer e next element int value removeheadernamed removeindices getheaders getheaders getobjectvalue getname equalsignorecase removeindices addelement removeindices hasmoreelements getheaders nextelement intvalue added support for soap related header stuff 1 29 04 peter lin return the soap header object public object getsoap header return this soap header getsoapheader soapheader set the soap header with the soaphttp connection object we may or may not want to rename this to set header object object concievably other samplers may need this kind of functionality 1 29 04 peter lin param header public void setsoap header object header this soap header header soapheader soaphttpconnection setheaderobject setsoapheader soapheader merge the attributes with a another header manager s attributes param element the object to be merged with param prefer local values when both objects have a value for the same attribute this flag determines which value is preferresd public header manager merge test element element boolean prefer local values if element instanceof header manager throw new illegal argument exception cannot merge type this get class get name with type element get class get name start off with a merged object as a copy of the local object header manager merged header manager this clone header manager other header manager element iterate thru each of the other headers for int i 0 i other get headers size i header other header other get i boolean found false find the same property in the local headers for int j 0 j merged get headers size j header merged header merged get j if merged header get name equals ignore case other header get name we have a match found true if prefer local values prefer values from the other object if other header get value null other header get value length 0 the other object has an empty value so remove this value from the merged object merged remove j else use the other object s value merged header set value other header get value break out of the inner loop break if found the other object has a new value to be added to the merged merged add other header finally merge the names so it s clear they ve been merged merged set name merged get name other get name return merged headermanager preferlocalvalues headermanager testelement preferlocalvalues headermanager illegalargumentexception getclass getname getclass getname headermanager headermanager headermanager headermanager getheaders otherheader getheaders mergedheader mergedheader getname equalsignorecase otherheader getname preferlocalvalues otherheader getvalue otherheader getvalue mergedheader setvalue otherheader getvalue otherheader setname getname getname public tc log parser super tclogparser param source public tc log parser string source set source file source tclogparser setsourcefile by default decode is set to true if the parameters shouldn t be decoded call the method with false param decodeparams public void set decode parameter values boolean decodeparams this decode decodeparams setdecodeparametervalues decode the parameter values is to true by default return if paramter values should be decoded public boolean decode parameter value return this decode decodeparametervalue calls this method to set whether or not to use the path in the log we may want to provide the ability to filter the log file later on by default the parser uses the file in the log param file public void set use parsed file boolean file this usefile file setuseparsedfile use the filter to include exclude files in the access logs this is provided as a convienance and reduce the need to spend hours cleaning up log files param filter public void set filter filter filter filter filter setfilter sets the source file param source public void set source file string source this filename source setsourcefile parse the entire file return boolean success failure public int parse test element el int parse count if this source null this source new file this filename try if this reader null this reader get reader this source return parse this reader el parse count catch exception exception log error problem creating samples exception return 1 indicate that an error occured testelement parsecount getreader parsecount private static buffered reader get reader file file throws io exception if isgzip file return new buffered reader new file reader file gzip input stream in new gzip input stream new file input stream file return new buffered reader new input stream reader in bufferedreader getreader ioexception bufferedreader filereader gzipinputstream gzipinputstream fileinputstream bufferedreader inputstreamreader private static boolean isgzip file file throws io exception file input stream in new file input stream file try return in read gzip input stream gzip magic 0xff in read gzip input stream gzip magic 8 finally in close ioexception fileinputstream fileinputstream gzipinputstream gzip_magic gzipinputstream gzip_magic parse a set number of lines from the access log keep in mind the number of lines parsed will depend the filter and number of lines in the log the method returns the actual lines parsed param count return lines parsed public int parse and configure int count test element el return this parse el count parseandconfigure testelement the method is responsible for reading each line and breaking out of the while loop if a set number of lines is given param breader protected int parse buffered reader breader test element el int parse count int actual count 0 string line null try read one line at a time using buffered reader line breader read line while line null if line length 0 actual count this parse line line el we check the count to see if we have exceeded the number of lines to parse there s no way to know where to stop in the file therefore we use break to escape the while loop when we ve reached the count if parse count 1 actual count parse count break line breader read line if line null breader close breader null this reader null this reader new buffered reader new file reader this source parse this reader el catch io exception ioe log error error reading log file ioe return actual count bufferedreader testelement parsecount actualcount bufferedreader readline actualcount parseline parsecount actualcount parsecount readline bufferedreader filereader ioexception actualcount parse line calls the other parse methods to parse the given text param line protected int parse line string line test element el int count 0 we clean the line to get rid of extra stuff string cleaned line this cleanurl line log debug parsing line line now we set request method el set property http sampler base method rmethod if filter null log debug filter is not null if filter is filtered line el log debug line was not filtered increment the current count count we filter the line first before we try to separate the url into file and parameters line filter filter cleaned line if line null create url line el else log debug line was filtered else log debug filter was null increment the current count count in the case when the filter is not set we parse all the lines create url cleaned line el return count parseline parseline testelement cleanedline setproperty httpsamplerbase isfiltered cleanedline createurl createurl cleanedline param line private void create url string line test element el string param string null check the url for symbol param string this strip file line el if param string null this check param format line now that we have stripped the file we can parse the parameters this convert string tojm request param string el createurl testelement paramstring paramstring stripfile paramstring checkparamformat convertstringtojmrequest paramstring the method cleans the url using the following algorithm ol li check for double quotes li check the request method li tokenize using double quotes li find first token containing request method li tokenize string using space li find first token that begins with ol example tomcat log entry p 127 0 0 1 08 jan 2003 07 03 54 0500 get addrbook http 1 1 200 1981 p param entry return cleaned url public string cleanurl string entry string url entry if the string contains atleast one double quote and check method is true go ahead and tokenize the string if entry index of 1 check method entry string tokenizer tokens null we tokenize using double quotes this means for tomcat we should have 3 tokens if there isn t any additional information in the logs tokens this tokenize entry while tokens has more tokens string toke tokens next token if check method on the token is true we tokenzie it using space and escape the while loop only the first matching token will be used if check method toke string tokenizer token2 this tokenize toke while token2 has more tokens string t string token2 next element if t equals ignore case get rmethod get else if t equals ignore case post rmethod post there should only be one token that starts with slash character if t starts with url t break break return url we return the original string return url checkmethod indexof checkmethod stringtokenizer hasmoretokens nexttoken checkmethod checkmethod stringtokenizer hasmoretokens nextelement equalsignorecase equalsignorecase startswith the method checks for post and get methods currently the other methods aren t supported yet param text return if method is supported public boolean check method string text if text index of get 1 this rmethod get return true else if text index of post 1 this rmethod post return true else return false checkmethod indexof indexof tokenize the url into two tokens if the url has more than one the parse may fail only the first two tokens are used the first token is automatically parsed and set at url path param url return string parameters public string strip file string url test element el if url index of 1 string tokenizer tokens this tokenize url this url path tokens next token el set property http sampler base path url path return tokens has more tokens tokens next token null el set property http sampler base path url return null url_path stripfile testelement indexof stringtokenizer url_path nexttoken setproperty httpsamplerbase url_path hasmoretokens nexttoken setproperty httpsamplerbase checks the string to make sure it has path file name value format if the string doesn t have it will return false param url return boolean public boolean checkurl string url if url index of 1 return true return false indexof checks the string to see if it contains and if it does return true so that it can be parsed param text return boolean public boolean check param format string text if text index of 1 text index of 1 return true return false checkparamformat indexof indexof convert a single line into xml param text public void convert string tojm request string text test element el http sampler base el parse arguments text convertstringtojmrequest testelement httpsamplerbase parsearguments parse the string parameters into nv pair array once they are parsed it is returned the method uses parse one parameter string to convert each pair param stringparams public nv pair convert stringtonv pair string stringparams vector vparams this parse parameters stringparams nv pair nvparams new nv pair vparams size convert the parameters for int idx 0 idx nvparams length idx nvparams idx this parse one parameter string vparams get idx return nvparams nvpair parseoneparameter nvpair convertstringtonvpair parseparameters nvpair nvpair parseoneparameter method expects name and value to be separated by an equal sign the method uses string tokenizer to make a nv pair object if there happens to be more than one sign the others are ignored the chance of a string containing more than one is unlikely and would not conform to http spec i should double check the protocol spec to make sure this is accurate param parameter to be parsed return nv pair protected nv pair parse one parameter string parameter string name avoid possible npe when trimming the name string value null try string tokenizer param this tokenize parameter name param next token value param next token catch exception e do nothing it s naive but since the utility is meant to parse access logs the formatting should be correct if value null value else if decode try value url decoder decode value utf 8 catch unsupported encoding exception e log warn e get message return new nv pair name trim value trim stringtokenizer nvpair nvpair nvpair parseoneparameter stringtokenizer nexttoken nexttoken urldecoder unsupportedencodingexception getmessage nvpair method uses string tokenizer to convert the string into single pairs the string should conform to http protocol spec which means the name value pairs are separated by the ampersand symbol some one could write the querystrings by hand but that would be round about and go against the purpose of this utility param parameters return vector protected vector parse parameters string parameters vector parsed params new vector string tokenizer paramtokens this tokenize parameters while paramtokens has more elements parsed params add paramtokens next element return parsed params stringtokenizer parseparameters parsedparams stringtokenizer hasmoreelements parsedparams nextelement parsedparams parses the line using java util string tokenizer param line line to be parsed param delim delimiter return string tokenizer public string tokenizer tokenize string line string delim return new string tokenizer line delim stringtokenizer stringtokenizer stringtokenizer stringtokenizer public void close try this reader close this reader null this source null catch io exception e do nothing ioexception public class test anchor modifier extends j meter test case private anchor modifier parser new anchor modifier public test anchor modifier string name super name testanchormodifier jmetertestcase anchormodifier anchormodifier testanchormodifier private j meter context jmctx null public void set up jmctx j meter context service get context parser set thread context jmctx jmetercontext setup jmetercontextservice getcontext setthreadcontext public void test processinghtml file string html file name throws exception http sampler base config http sampler base save service load tree new file input stream system get property user dir testfiles load bug list jmx get array 0 config set running version true http sample result result new http sample result http sampler base context http sampler base save service load tree new file input stream system get property user dir testfiles load jmeter page jmx get array 0 jmctx set current sampler context jmctx set current sampler config result set response data new text file system get property user dir html file name get text get bytes result set sample label context to string result set sampler data context to string result seturl new url http issues apache org fakepage html jmctx set previous result result anchor modifier modifier new anchor modifier modifier set thread context jmctx modifier process assert equals http issues apache org bugzilla buglist cgi bug status new bug status assigned bug status reopened email1 emailtype1 substring emailassigned to1 1 email2 emailtype2 substring emailreporter2 1 bugidtype include bug id changedin votes chfieldfrom chfieldto now chfieldvalue product j meter short desc short desc type substring long desc long desc type substring bug file loc bug file loc type substring keywords keywords type anywords field0 0 0 noop type0 0 0 noop value0 0 0 cmdtype doit order reuse same sort as last time config to string config recover running version assert equals http issues apache org bugzilla buglist cgi bug status bug status bug status email1 emailtype1 substring emailassigned to1 1 email2 emailtype2 substring emailreporter2 1 bugidtype include bug id changedin votes chfieldfrom chfieldto now chfieldvalue product j meter short desc short desc type substring long desc long desc type substring bug file loc bug file loc type substring keywords keywords type anywords field0 0 0 noop type0 0 0 noop value0 0 0 cmdtype doit order reuse same sort as last time config to string testprocessinghtmlfile htmlfilename httpsamplerbase httpsamplerbase saveservice loadtree fileinputstream getproperty load_bug_list getarray setrunningversion httpsampleresult httpsampleresult httpsamplerbase httpsamplerbase saveservice loadtree fileinputstream getproperty load_jmeter_page getarray setcurrentsampler setcurrentsampler setresponsedata textfile getproperty htmlfilename gettext getbytes setsamplelabel tostring setsamplerdata tostring setpreviousresult anchormodifier anchormodifier setthreadcontext assertequals bug_status bug_status bug_status emailassigned_to1 bug_id jmeter short_desc short_desc_type long_desc long_desc_type bug_file_loc bug_file_loc_type keywords_type tostring recoverrunningversion assertequals bug_status bug_status bug_status emailassigned_to1 bug_id jmeter short_desc short_desc_type long_desc long_desc_type bug_file_loc bug_file_loc_type keywords_type tostring public void test modify sampler throws exception test processinghtml file testfiles jmeter home page html testmodifysampler testprocessinghtmlfile jmeter_home_page public void test modify sampler with relative link throws exception test processinghtml file testfiles jmeter home page with relative links html testmodifysamplerwithrelativelink testprocessinghtmlfile jmeter_home_page_with_relative_links public void test modify sampler with baseh ref throws exception test processinghtml file testfiles jmeter home page with base href html testmodifysamplerwithbasehref testprocessinghtmlfile jmeter_home_page_with_base_href public void test simple parse throws exception http sampler base config make url config index html http sampler base context make context http www apache org subdir previous html string response text html head title test page title head body a href index html goto index page a body html http sample result result new http sample result jmctx set current sampler context jmctx set current sampler config result set response data response text get bytes result set sample label context to string result set sampler data context to string result seturl context get url jmctx set previous result result parser process assert equals http www apache org subdir index html config get url to string testsimpleparse httpsamplerbase makeurlconfig httpsamplerbase makecontext responsetext httpsampleresult httpsampleresult setcurrentsampler setcurrentsampler setresponsedata responsetext getbytes setsamplelabel tostring setsamplerdata tostring geturl setpreviousresult assertequals geturl tostring test https works too public void test simple parse1 throws exception http sampler base config make url config index html config set protocol http sampler base protocol https config set port http sampler base default https port http sampler base context make context https www apache org subdir previous html string response text html head title test page title head body a href index html goto index page a body html http sample result result new http sample result jmctx set current sampler context jmctx set current sampler config result set response data response text get bytes result set sample label context to string result set sampler data context to string result seturl context get url jmctx set previous result result parser process assert equals https www apache org subdir index html config get url to string testsimpleparse1 httpsamplerbase makeurlconfig setprotocol httpsamplerbase protocol_https setport httpsamplerbase default_https_port httpsamplerbase makecontext responsetext httpsampleresult httpsampleresult setcurrentsampler setcurrentsampler setresponsedata responsetext getbytes setsamplelabel tostring setsamplerdata tostring geturl setpreviousresult assertequals geturl tostring public void test simple parse2 throws exception http sampler base config make url config index html http sampler base context make context http www apache org subdir previous html string response text html head title test page title head body a href index html goto index page a hfdfjiudfjdfjkjfkdjf b bold text b a href lowerdir index html lower a body html http sample result result new http sample result result set response data response text get bytes result set sample label context to string result seturl context get url jmctx set current sampler context jmctx set current sampler config jmctx set previous result result parser process string new url config get url to string assert true http www apache org index html equals new url http www apache org subdir lowerdir index html equals new url testsimpleparse2 httpsamplerbase makeurlconfig httpsamplerbase makecontext responsetext httpsampleresult httpsampleresult setresponsedata responsetext getbytes setsamplelabel tostring geturl setcurrentsampler setcurrentsampler setpreviousresult newurl geturl tostring asserttrue newurl newurl public void test simple parse3 throws exception http sampler base config make url config index config get arguments add argument param1 value1 http sampler base context make context http www apache org subdir previous html string response text html head title test page title head body a href home index html param1 value1 goto index page a body html http sample result result new http sample result result set response data response text get bytes result set sample label context to string result seturl context get url jmctx set current sampler context jmctx set current sampler config jmctx set previous result result parser process string new url config get url to string assert equals http www apache org home index html param1 value1 new url testsimpleparse3 httpsamplerbase makeurlconfig getarguments addargument httpsamplerbase makecontext responsetext httpsampleresult httpsampleresult setresponsedata responsetext getbytes setsamplelabel tostring geturl setcurrentsampler setcurrentsampler setpreviousresult newurl geturl tostring assertequals newurl public void test simple parse4 throws exception http sampler base config make url config subdir index http sampler base context make context http www apache org subdir previous html string response text html head title test page title head body a href index html goto index page a body html http sample result result new http sample result result set response data response text get bytes result set sample label context to string result seturl context get url jmctx set current sampler context jmctx set current sampler config jmctx set previous result result parser process string new url config get url to string assert equals http www apache org subdir index html new url testsimpleparse4 httpsamplerbase makeurlconfig httpsamplerbase makecontext responsetext httpsampleresult httpsampleresult setresponsedata responsetext getbytes setsamplelabel tostring geturl setcurrentsampler setcurrentsampler setpreviousresult newurl geturl tostring assertequals newurl public void test simple parse5 throws exception http sampler base config make url config subdir index h http sampler base context make context http www apache org subdir one previous html string response text html head title test page title head body a href index html goto index page a body html http sample result result new http sample result result set response data response text get bytes result set sample label context to string result seturl context get url jmctx set current sampler context jmctx set current sampler config jmctx set previous result result parser process string new url config get url to string assert equals http www apache org subdir index html new url testsimpleparse5 httpsamplerbase makeurlconfig httpsamplerbase makecontext responsetext httpsampleresult httpsampleresult setresponsedata responsetext getbytes setsamplelabel tostring geturl setcurrentsampler setcurrentsampler setpreviousresult newurl geturl tostring assertequals newurl public void test fail simple parse1 throws exception http sampler base config make url config index param2 1 http sampler base context make context http www apache org subdir previous html string response text html head title test page title head body a href home index html param1 value1 goto index page a body html http sample result result new http sample result string new url config get url to string result set response data response text get bytes result set sample label context to string result seturl context get url jmctx set current sampler context jmctx set current sampler config jmctx set previous result result parser process assert equals new url config get url to string testfailsimpleparse1 httpsamplerbase makeurlconfig httpsamplerbase makecontext responsetext httpsampleresult httpsampleresult newurl geturl tostring setresponsedata responsetext getbytes setsamplelabel tostring geturl setcurrentsampler setcurrentsampler setpreviousresult assertequals newurl geturl tostring public void test fail simple parse3 throws exception http sampler base config make url config home index html http sampler base context make context http www apache org subdir previous html string response text html head title test page title head body a href home index html param1 value1 goto index page a body html http sample result result new http sample result string new url config get url to string result set response data response text get bytes result set sample label context to string result seturl context get url jmctx set current sampler context jmctx set current sampler config jmctx set previous result result parser process assert equals new url param1 value1 config get url to string testfailsimpleparse3 httpsamplerbase makeurlconfig httpsamplerbase makecontext responsetext httpsampleresult httpsampleresult newurl geturl tostring setresponsedata responsetext getbytes setsamplelabel tostring geturl setcurrentsampler setcurrentsampler setpreviousresult assertequals newurl geturl tostring public void test fail simple parse2 throws exception http sampler base config make url config login html http sampler base context make context http www apache org subdir previous html string response text html head title test page title head body a href home index html param1 value1 goto index page a body html http sample result result new http sample result result set response data response text get bytes result set sample label context to string result seturl context get url jmctx set current sampler context jmctx set previous result result parser process string new url config get url to string assert true http www apache org home index html param1 value1 equals new url assert equals config get url to string new url testfailsimpleparse2 httpsamplerbase makeurlconfig httpsamplerbase makecontext responsetext httpsampleresult httpsampleresult setresponsedata responsetext getbytes setsamplelabel tostring geturl setcurrentsampler setpreviousresult newurl geturl tostring asserttrue newurl assertequals geturl tostring newurl public void test simple form parse throws exception http sampler base config make url config index html config add argument test g config set method http sampler base post http sampler base context make context http www apache org subdir previous html string response text html head title test page title head body form action index html method post input type checkbox name test value goto goto index page form body html http sample result result new http sample result result set response data response text get bytes result set sample label context to string result seturl context get url jmctx set current sampler context jmctx set current sampler config jmctx set previous result result parser process assert equals http www apache org subdir index html config get url to string assert equals test goto config get query string testsimpleformparse httpsamplerbase makeurlconfig addargument setmethod httpsamplerbase httpsamplerbase makecontext responsetext httpsampleresult httpsampleresult setresponsedata responsetext getbytes setsamplelabel tostring geturl setcurrentsampler setcurrentsampler setpreviousresult assertequals geturl tostring assertequals getquerystring public void test bad char parse throws exception http sampler base config make url config index html config add argument te st g config set method http sampler base post http sampler base context make context http www apache org subdir previous html string response text html head title test page title head body form action index html method post input type checkbox name te st value goto goto index page form body html http sample result result new http sample result result set response data response text get bytes result set sample label context to string result seturl context get url jmctx set current sampler context jmctx set current sampler config jmctx set previous result result parser process assert equals http www apache org subdir index html config get url to string assert equals te 24st goto config get query string testbadcharparse httpsamplerbase makeurlconfig addargument setmethod httpsamplerbase httpsamplerbase makecontext responsetext httpsampleresult httpsampleresult setresponsedata responsetext getbytes setsamplelabel tostring geturl setcurrentsampler setcurrentsampler setpreviousresult assertequals geturl tostring assertequals getquerystring public void test special char parse throws exception string special chars 25 these are some of the special characters string html encoded fixture url encoder encode special chars utf 8 http sampler base config make url config index html config add argument test config set method http sampler base post http sampler base context make context http www apache org subdir previous html string response text html head title test page title head body form action index html method post input type hidden name test value html encoded fixture goto index page form body html http sample result result new http sample result result set response data response text get bytes result set sample label context to string result seturl context get url jmctx set current sampler context jmctx set current sampler config jmctx set previous result result parser process assert equals http www apache org subdir index html config get url to string assert equals test html encoded fixture config get query string testspecialcharparse specialchars _ htmlencodedfixture urlencoder specialchars httpsamplerbase makeurlconfig addargument setmethod httpsamplerbase httpsamplerbase makecontext responsetext htmlencodedfixture httpsampleresult httpsampleresult setresponsedata responsetext getbytes setsamplelabel tostring geturl setcurrentsampler setcurrentsampler setpreviousresult assertequals geturl tostring assertequals htmlencodedfixture getquerystring private http sampler base make context string url throws malformedurl exception url u new url url http sampler base context new http null sampler context set domain u get host context set path u get path context set port u get port context set protocol u get protocol context parse arguments u get query return context httpsamplerbase makecontext malformedurlexception httpsamplerbase httpnullsampler setdomain gethost setpath getpath setport getport setprotocol getprotocol parsearguments getquery private http sampler base make url config string path http sampler base config new http null sampler config set domain www apache org config set method http sampler base get config set path path config set port http sampler base default http port config set protocol http sampler base protocol http return config httpsamplerbase makeurlconfig httpsamplerbase httpnullsampler setdomain setmethod httpsamplerbase setpath setport httpsamplerbase default_http_port setprotocol httpsamplerbase protocol_http private constructor so that no instance can ever be created private cl util clutil format options into string buffer and return this is typically used to print usage text in response to a help or invalid option param options the option descriptors return the formatted description help for options public static final string buffer describe options final cl option descriptor options final string l sep system get property line separator final string buffer sb new string buffer for int i 0 i options length i final char ch char options i get id final string name options i get name string description options i get description int flags options i get flags boolean argument optional flags cl option descriptor argument optional cl option descriptor argument optional boolean argument required flags cl option descriptor argument required cl option descriptor argument required boolean two arguments required flags cl option descriptor arguments required 2 cl option descriptor arguments required 2 boolean need comma false if two arguments required argument required true sb append t if character is letter ch sb append sb append ch need comma true if null name if need comma sb append sb append sb append name if argument optional sb append argument if argument required sb append argument if two arguments required sb append value sb append l sep if null description while description length max description column length final string description part description substring 0 max description column length description description substring max description column length sb append t t sb append description part sb append l sep sb append t t sb append description sb append l sep return sb stringbuffer stringbuffer describeoptions cloptiondescriptor lsep getproperty stringbuffer stringbuffer getid getname getdescription getflags argumentoptional cloptiondescriptor argument_optional cloptiondescriptor argument_optional argumentrequired cloptiondescriptor argument_required cloptiondescriptor argument_required twoargumentsrequired cloptiondescriptor arguments_required_2 cloptiondescriptor arguments_required_2 needcomma twoargumentsrequired argumentrequired isletter needcomma needcomma argumentoptional argumentrequired twoargumentsrequired lsep max_description_column_length descriptionpart max_description_column_length max_description_column_length descriptionpart lsep lsep public customx509 trust manager final x509 trust manager default trust manager super if default trust manager null throw new illegal argument exception trust manager may not be null this default trust manager default trust manager customx509trustmanager x509trustmanager defaulttrustmanager defaulttrustmanager illegalargumentexception defaulttrustmanager defaulttrustmanager see javax net ssl x509 trust manager check client trusted x509 certificate string public void check client trusted x509 certificate certificates string auth type throws certificate exception if log is debug enabled certificates null for int c 0 c certificates length c x509 certificate cert certificates c log debug client certificate c 1 log debug subject dn cert get subjectdn log debug signature algorithm cert get sig alg name log debug valid from cert get not before log debug valid until cert get not after log debug issuer cert get issuerdn try default trust manager check client trusted certificates auth type catch certificate exception e log warn ignoring failed client trust check e get message x509trustmanager checkclienttrusted x509certificate checkclienttrusted x509certificate authtype certificateexception isdebugenabled x509certificate getsubjectdn getsigalgname getnotbefore getnotafter getissuerdn defaulttrustmanager checkclienttrusted authtype certificateexception getmessage see javax net ssl x509 trust manager check server trusted x509 certificate string public void check server trusted x509 certificate certificates string auth type throws certificate exception if log is debug enabled certificates null for int c 0 c certificates length c x509 certificate cert certificates c log debug server certificate c 1 log debug subject dn cert get subjectdn log debug signature algorithm cert get sig alg name log debug valid from cert get not before log debug valid until cert get not after log debug issuer cert get issuerdn try default trust manager check server trusted certificates auth type catch certificate exception e log warn ignoring failed server trust check e get message x509trustmanager checkservertrusted x509certificate checkservertrusted x509certificate authtype certificateexception isdebugenabled x509certificate getsubjectdn getsigalgname getnotbefore getnotafter getissuerdn defaulttrustmanager checkservertrusted authtype certificateexception getmessage see javax net ssl x509 trust manager get accepted issuers public x509 certificate get accepted issuers return this default trust manager get accepted issuers x509trustmanager getacceptedissuers x509certificate getacceptedissuers defaulttrustmanager getacceptedissuers private static final string default content type text xml non nls 1 public void set xml data string data set property xml data data default_content_type setxmldata setproperty xml_data public string get xml data return get property as string xml data getxmldata getpropertyasstring xml_data it s kinda obvious but we state it anyways set the xml file with a string path param filename public void set xml file string filename set property xml data file filename setxmlfile setproperty xml_data_file get the file location of the xml file return string file path public string get xml file return get property as string xml data file getxmlfile getpropertyasstring xml_data_file public string geturl data return get property as string url data geturldata getpropertyasstring url_data public void seturl data string url set property url data url seturldata setproperty url_data public string getsoap action return get property as string soap action getsoapaction getpropertyasstring soap_action public string getsoap action quoted string action getsoap action string buffer sb new string buffer action length 2 sb append double quote sb append action sb append double quote return sb to string getsoapactionquoted getsoapaction stringbuffer stringbuffer double_quote double_quote tostring public void setsoap action string action set property soap action action setsoapaction setproperty soap_action public boolean get sendsoap action return get property as boolean send soap action getsendsoapaction getpropertyasboolean send_soap_action public void set sendsoap action boolean action set property send soap action string value of action setsendsoapaction setproperty send_soap_action valueof protected int set post headers post method post int length 0 take length from file if get header manager null header manager was set so let s set the connection to use it header manager mngr get header manager int header size mngr size for int idx 0 idx header size idx header hd mngr get header idx if header content length equals ignore case hd get name use this to override file length length integer parse int hd get value all the other headers are set up by http sampler2 setup connection else otherwise we use text xml as the default post add parameter header content type default content type non nls 1 if get sendsoap action post set request header soapaction getsoap action quoted return length setpostheaders postmethod getheadermanager headermanager headermanager getheadermanager headersize headersize getheader header_content_length equalsignorecase getname parseint getvalue httpsampler2 setupconnection addparameter header_content_type default_content_type getsendsoapaction setrequestheader getsoapactionquoted send post data from code entry code to the open connection param post throws io exception if an i o exception occurs private string send post data post method post final int length buffer to hold the post body except file content string buffer posted body new string buffer 1000 final string xml file get xml file if xml file null xml file length 0 we just add placeholder text for file content posted body append filename append xml file append n posted body append actual file content not shown here post set request entity new request entity public boolean is repeatable return true public void write request output stream out throws io exception input stream in null try in new file input stream xml file io utils copy in out out flush finally io utils close quietly in public long get content length switch length case 1 return 1 case 0 no header provided return new file xml file length default return length public string get content type todo do we need to add a charset for the file contents return default content type non nls 1 else posted body append get xml data post set request entity new request entity public boolean is repeatable return true public void write request output stream out throws io exception charset must agree with content type below io utils write get xml data out encoding non nls 1 out flush public long get content length try return get xml data get bytes encoding length so we don t generate chunked encoding catch unsupported encoding exception e log warn e get localized message return 1 will use chunked encoding public string get content type return default content type charset encoding non nls 1 return posted body to string ioexception sendpostdata postmethod stringbuffer postedbody stringbuffer xmlfile getxmlfile xmlfile xmlfile postedbody xmlfile postedbody setrequestentity requestentity isrepeatable writerequest outputstream ioexception inputstream fileinputstream xmlfile ioutils ioutils closequietly getcontentlength xmlfile getcontenttype default_content_type postedbody getxmldata setrequestentity requestentity isrepeatable writerequest outputstream ioexception ioutils getxmldata getcontentlength getxmldata getbytes unsupportedencodingexception getlocalizedmessage getcontenttype default_content_type postedbody tostring posted body append actual file content not shown here post set request entity new request entity public boolean is repeatable return true postedbody setrequestentity requestentity isrepeatable public void write request output stream out throws io exception input stream in null try in new file input stream xml file io utils copy in out out flush finally io utils close quietly in writerequest outputstream ioexception inputstream fileinputstream xmlfile ioutils ioutils closequietly public long get content length switch length case 1 return 1 case 0 no header provided return new file xml file length default return length getcontentlength xmlfile public string get content type todo do we need to add a charset for the file contents return default content type non nls 1 getcontenttype default_content_type posted body append get xml data post set request entity new request entity public boolean is repeatable return true postedbody getxmldata setrequestentity requestentity isrepeatable public void write request output stream out throws io exception charset must agree with content type below io utils write get xml data out encoding non nls 1 out flush writerequest outputstream ioexception ioutils getxmldata public long get content length try return get xml data get bytes encoding length so we don t generate chunked encoding catch unsupported encoding exception e log warn e get localized message return 1 will use chunked encoding getcontentlength getxmldata getbytes unsupportedencodingexception getlocalizedmessage public string get content type return default content type charset encoding non nls 1 getcontenttype default_content_type protected http sample result sample url url string method boolean are following redirect int frame depth string url str url to string log debug start sample url str post method http method http method new post method url str http sample result res new http sample result res set monitor false res set sample label url str may be replaced later res sethttp method http constants post res sample start count the retries as well in the time http client client null input stream instream null try int content len set post headers http method client setup connection url http method res saved client client res set query string send post data http method content len int status code client execute method http method some headers are set by execute method res set request headers get connection headers http method request sent now get the response instream http method get response body as stream if instream null will be null for head org apache commons httpclient header response header http method get response header transfer encoding if response header null encoding gzip equals response header get value instream new gzip input stream instream int content length http method get response content length not visible todo size ouststream according to actual content length byte array output stream outstream new byte array output stream 4 1024 content length 0 content length default initial buffer size byte buffer new byte 4096 int len boolean first true first response while len instream read buffer 0 if first save the latency res latency end first false outstream write buffer 0 len res set response data outstream to byte array outstream close res sample end done with the sampling proper now collect the results into the http sample result res set sample label http method geturi to string pick up actual path after redirects res set response code integer to string status code res set successful is success code status code res set response message http method get status text set up the defaults may be overridden below res set data encoding encoding res set content type default content type string ct null org apache commons httpclient header h http method get response header header content type if h null can be missing e g on redirect ct h get value res set content type ct e g text html charset iso 8859 1 res set encoding and type ct res set response headers get response headers http method if res is redirect res set redirect location http method get response header header location get value if we redirected automatically the url may have changed if get auto redirects res seturl new url http method geturi to string store any cookies received in the cookie manager save connection cookies http method res geturl get cookie manager save cache information final cache manager cache manager get cache manager if cache manager null cache manager save details http method res follow redirects and download page resources if appropriate res result processing are following redirect frame depth res log debug end sample http method release connection return res catch illegal argument exception e e g some kinds of invalid url res sample end http sample result err error result e res err set sample label error url to string return err catch io exception e res sample end http sample result err error result e res err set sample label error url to string return err finally j orphan utils close quietly instream saved client null http method release connection httpsampleresult arefollowingredirect framedepth urlstr tostring urlstr postmethod httpmethod httpmethod postmethod urlstr httpsampleresult httpsampleresult setmonitor setsamplelabel urlstr sethttpmethod httpconstants samplestart httpclient inputstream content_len setpostheaders httpmethod setupconnection httpmethod savedclient setquerystring sendpostdata httpmethod content_len statuscode executemethod httpmethod executemethod setrequestheaders getconnectionheaders httpmethod httpmethod getresponsebodyasstream responseheader httpmethod getresponseheader transfer_encoding responseheader encoding_gzip responseheader getvalue gzipinputstream contentlength httpmethod getresponsecontentlength bytearrayoutputstream bytearrayoutputstream contentlength contentlength default_initial_buffer_size latencyend setresponsedata tobytearray sampleend httpsampleresult setsamplelabel httpmethod tostring setresponsecode tostring statuscode setsuccessful issuccesscode statuscode setresponsemessage httpmethod getstatustext setdataencoding setcontenttype default_content_type httpmethod getresponseheader header_content_type getvalue setcontenttype setencodingandtype setresponseheaders getresponseheaders httpmethod isredirect setredirectlocation httpmethod getresponseheader header_location getvalue getautoredirects httpmethod tostring saveconnectioncookies httpmethod getcookiemanager cachemanager cachemanager getcachemanager cachemanager cachemanager savedetails httpmethod resultprocessing arefollowingredirect framedepth httpmethod releaseconnection illegalargumentexception sampleend httpsampleresult errorresult setsamplelabel tostring ioexception sampleend httpsampleresult errorresult setsamplelabel tostring jorphanutils closequietly savedclient httpmethod releaseconnection public url get url throws malformedurl exception return new url geturl data geturl malformedurlexception geturldata private object values public log function2 logfunction2 public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception string string to log compound variable values 0 execute string priority string if values length 1 we have a default priority string compound variable values 1 execute if priority string length 0 priority string default priority else priority string default priority throwable t null if values length 2 throwable wanted t new throwable compound variable values 2 execute log function log details log string to log priority string t return sampleresult previousresult currentsampler invalidvariableexception stringtolog compoundvariable prioritystring prioritystring compoundvariable prioritystring prioritystring default_priority prioritystring default_priority compoundvariable logfunction logdetails stringtolog prioritystring public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters min parameter count max parameter count values parameters to array setparameters invalidvariableexception checkparametercount min_parameter_count max_parameter_count toarray public string get reference key return key getreferencekey public list get argument desc return desc getargumentdesc private j radio button put box public ftp config gui this true jradiobutton putbox ftpconfiggui public ftp config gui boolean display name this display name display name init ftpconfiggui displayname displayname displayname public string get label resource return ftp sample title non nls 1 getlabelresource ftp_sample_title public void configure test element element super configure element todo should this be done for embedded usage note the element is a config test element when used standalone so we cannot use ftp sampler access methods server set text element get property as string ftp sampler server port set text element get property as string ftp sampler port remote file set text element get property as string ftp sampler remote filename local file set text element get property as string ftp sampler local filename input data set text element get property as string ftp sampler input data binary mode set selected element get property as boolean ftp sampler binary mode false save response data set selected element get property as boolean ftp sampler save response false final boolean uploading element get property as boolean ftp sampler upload file false if uploading put box set selected true else get box set selected true testelement configtestelement ftpsampler settext getpropertyasstring ftpsampler settext getpropertyasstring ftpsampler remotefile settext getpropertyasstring ftpsampler remote_filename localfile settext getpropertyasstring ftpsampler local_filename inputdata settext getpropertyasstring ftpsampler input_data binarymode setselected getpropertyasboolean ftpsampler binary_mode saveresponsedata setselected getpropertyasboolean ftpsampler save_response getpropertyasboolean ftpsampler upload_file putbox setselected getbox setselected public test element create test element config test element element new config test element modify test element element return element testelement createtestelement configtestelement configtestelement modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element element configure test element element note the element is a config test element so cannot use ftp sampler access methods element set property ftp sampler server server get text element set property ftp sampler port port get text element set property ftp sampler remote filename remote file get text element set property ftp sampler local filename local file get text element set property ftp sampler input data input data get text element set property ftp sampler binary mode binary mode is selected element set property ftp sampler save response save response data is selected element set property ftp sampler upload file put box is selected testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement configtestelement ftpsampler setproperty ftpsampler gettext setproperty ftpsampler gettext setproperty ftpsampler remote_filename remotefile gettext setproperty ftpsampler local_filename localfile gettext setproperty ftpsampler input_data inputdata gettext setproperty ftpsampler binary_mode binarymode isselected setproperty ftpsampler save_response saveresponsedata isselected setproperty ftpsampler upload_file putbox isselected implements j metergui component clear gui public void clear gui super clear gui server set text non nls 1 port set text non nls 1 remote file set text non nls 1 local file set text non nls 1 input data set text non nls 1 binary mode set selected false save response data set selected false get box set selected true put box set selected false jmeterguicomponent cleargui cleargui cleargui settext settext remotefile settext localfile settext inputdata settext binarymode setselected saveresponsedata setselected getbox setselected putbox setselected private j panel create server panel j label label new j label j meter utils get res string server non nls 1 server new j text field 10 label set label for server j panel server panel new j panel new border layout 5 0 server panel add label border layout west server panel add server border layout center return server panel jpanel createserverpanel jlabel jlabel jmeterutils getresstring jtextfield setlabelfor jpanel serverpanel jpanel borderlayout serverpanel borderlayout serverpanel borderlayout serverpanel private j panel get port panel port new j text field 4 j label label new j label j meter utils get res string web server port non nls 1 label set label for port j panel panel new j panel new border layout 5 0 panel add label border layout west panel add port border layout center return panel jpanel getportpanel jtextfield jlabel jlabel jmeterutils getresstring web_server_port setlabelfor jpanel jpanel borderlayout borderlayout borderlayout private j panel create local filename panel j label label new j label j meter utils get res string ftp local file non nls 1 local file new j text field 10 label set label for local file j panel filename panel new j panel new border layout 5 0 filename panel add label border layout west filename panel add local file border layout center return filename panel jpanel createlocalfilenamepanel jlabel jlabel jmeterutils getresstring ftp_local_file localfile jtextfield setlabelfor localfile jpanel filenamepanel jpanel borderlayout filenamepanel borderlayout filenamepanel localfile borderlayout filenamepanel private j panel create local file contents panel j label label new j label j meter utils get res string ftp local file contents non nls 1 input data new j text area label set label for input data j panel contents panel new j panel new border layout 5 0 contents panel add label border layout west contents panel add input data border layout center return contents panel jpanel createlocalfilecontentspanel jlabel jlabel jmeterutils getresstring ftp_local_file_contents inputdata jtextarea setlabelfor inputdata jpanel contentspanel jpanel borderlayout contentspanel borderlayout contentspanel inputdata borderlayout contentspanel private j panel create remote filename panel j label label new j label j meter utils get res string ftp remote file non nls 1 remote file new j text field 10 label set label for remote file j panel filename panel new j panel new border layout 5 0 filename panel add label border layout west filename panel add remote file border layout center return filename panel jpanel createremotefilenamepanel jlabel jlabel jmeterutils getresstring ftp_remote_file remotefile jtextfield setlabelfor remotefile jpanel filenamepanel jpanel borderlayout filenamepanel borderlayout filenamepanel remotefile borderlayout filenamepanel private j panel create options panel button group group new button group get box new j radio button j meter utils get res string ftp get non nls 1 group add get box get box set selected true put box new j radio button j meter utils get res string ftp put non nls 1 group add put box binary mode new j check box j meter utils get res string ftp binary mode non nls 1 save response data new j check box j meter utils get res string ftp save response data non nls 1 j panel options panel new horizontal panel options panel add get box options panel add put box options panel add binary mode options panel add save response data return options panel jpanel createoptionspanel buttongroup buttongroup getbox jradiobutton jmeterutils getresstring ftp_get getbox getbox setselected putbox jradiobutton jmeterutils getresstring ftp_put putbox binarymode jcheckbox jmeterutils getresstring ftp_binary_mode saveresponsedata jcheckbox jmeterutils getresstring ftp_save_response_data jpanel optionspanel horizontalpanel optionspanel getbox optionspanel putbox optionspanel binarymode optionspanel saveresponsedata optionspanel private void init set layout new border layout 0 5 if display name set border make border add make title panel border layout north main panel vertical panel main panel new vertical panel j panel server panel new horizontal panel server panel add create server panel border layout center server panel add get port panel border layout east main panel add server panel main panel add create remote filename panel main panel add create local filename panel main panel add create local file contents panel main panel add create options panel add main panel border layout center setlayout borderlayout displayname setborder makeborder maketitlepanel borderlayout verticalpanel mainpanel verticalpanel jpanel serverpanel horizontalpanel serverpanel createserverpanel borderlayout serverpanel getportpanel borderlayout mainpanel serverpanel mainpanel createremotefilenamepanel mainpanel createlocalfilenamepanel mainpanel createlocalfilecontentspanel mainpanel createoptionspanel mainpanel borderlayout public mail reader sampler set server type type pop3 set folder inbox set num messages all messages set delete messages false mailreadersampler setservertype type_pop3 setfolder setnummessages all_messages setdeletemessages public sample result sample entry e sample result parent new sample result boolean isok false did sample succeed boolean delete messages get delete messages parent set sample label get name parent set sampler data get server type get user name get server perform the sampling parent sample start start timing try create empty properties properties props new properties get session session session session get default instance props null get the store store store session get store get server type store connect get server get user name get password get folder folder folder store get folder get folder if delete messages folder open folder read write else folder open folder read only get directory message messages folder get messages message message string buffer pdata new string buffer pdata append messages length pdata append messages found n int n get num messages if n all messages n messages length n messages length for int i 0 i n i string buffer cdata new string buffer sample result child new sample result child sample start message messages i if i 0 assumes all the messaged have the same type child set content type message get content type cdata append message non nls 1 cdata append message get message number child set sample label cdata to string child set sampler data cdata to string cdata set length 0 if is store mime message append message as mime cdata message else append message data cdata message if delete messages message set flag flags flag deleted true child set response data cdata to string get bytes child set data type sample result text child set response codeok child set response message ok non nls 1 child set successful true child sample end parent add sub result child close connection folder close true store close set up the sample result details parent set response data pdata to string get bytes parent set data type sample result text parent set content type text plain non nls 1 parent set response codeok parent set response message ok non nls 1 isok true catch no class def found error ex log debug ex no need to log normally as we set the status parent set response code 500 non nls 1 parent set response message ex to string catch messaging exception ex log debug ex no need to log normally as we set the status parent set response code 500 non nls 1 parent set response message ex to string catch io exception ex log debug ex no need to log normally as we set the status parent set response code 500 non nls 1 parent set response message ex to string if parent get end time 0 not been set by any child samples parent sample end parent set successful isok return parent sampleresult sampleresult sampleresult deletemessages getdeletemessages setsamplelabel getname setsamplerdata getservertype getusername getserver samplestart getdefaultinstance getstore getservertype getserver getusername getpassword getfolder getfolder deletemessages read_write read_only getmessages stringbuffer stringbuffer getnummessages all_messages stringbuffer stringbuffer sampleresult sampleresult samplestart setcontenttype getcontenttype getmessagenumber setsamplelabel tostring setsamplerdata tostring setlength isstoremimemessage appendmessageasmime appendmessagedata deletemessages setflag setresponsedata tostring getbytes setdatatype sampleresult setresponsecodeok setresponsemessage setsuccessful sampleend addsubresult setresponsedata tostring getbytes setdatatype sampleresult setcontenttype setresponsecodeok setresponsemessage noclassdeffounderror setresponsecode setresponsemessage tostring messagingexception setresponsecode setresponsemessage tostring ioexception setresponsecode setresponsemessage tostring getendtime sampleend setsuccessful private void append message data string buffer cdata message message throws messaging exception io exception cdata append date non nls 1 cdata append message get sent date todo use a different format here cdata append new line cdata append to non nls 1 address recips message get all recipients for int j 0 j recips length j cdata append recips j to string if j recips length 1 cdata append non nls 1 cdata append new line cdata append from non nls 1 address from message get from for int j 0 j from length j cdata append from j to string if j from length 1 cdata append non nls 1 cdata append new line cdata append subject non nls 1 cdata append message get subject cdata append new line cdata append new line object content message get content if content instanceof mime multipart mime multipart mmp mime multipart content int count mmp get count cdata append multipart count cdata append count cdata append new line for int j 0 j count j body part body part mmp get body part j cdata append type cdata append body part get content type cdata append new line try cdata append body part get content catch unsupported encoding exception ex cdata append ex get localized message else cdata append content appendmessagedata stringbuffer messagingexception ioexception getsentdate new_line getallrecipients tostring new_line getfrom tostring new_line getsubject new_line new_line getcontent mimemultipart mimemultipart mimemultipart getcount new_line bodypart bodypart getbodypart bodypart getcontenttype new_line bodypart getcontent unsupportedencodingexception getlocalizedmessage private void append message as mime string buffer cdata message message throws messaging exception io exception byte array output stream bout new byte array output stream message write to bout cdata append bout appendmessageasmime stringbuffer messagingexception ioexception bytearrayoutputstream bytearrayoutputstream writeto sets the type of protocol to use when talking with the remote mail server either mail reader sampler type imap s or mail reader sampler type pop3 s default is mail reader sampler type pop3 param server type public void set server type string server type set property server type server type mailreadersampler type_imap mailreadersampler type_pop3 mailreadersampler type_pop3 servertype setservertype servertype setproperty server_type servertype returns the type of the protocol set to use when talking with the remote server either mail reader sampler type imap s or mail reader sampler type pop3 s return server type public string get server type return get property server type to string mailreadersampler type_imap mailreadersampler type_pop3 getservertype getproperty server_type tostring param server the name or address of the remote server public void set server string server set property server server setserver setproperty return the name or address of the remote server public string get server return get property server to string getserver getproperty tostring param username the username of the mail account public void set user name string username set property username username setusername setproperty return the username of the mail account public string get user name return get property username to string getusername getproperty tostring param password public void set password string password set property password password setpassword setproperty return password public string get password return get property password to string getpassword getproperty tostring param folder name of the folder to read emails from inbox is the only acceptable value if the server type is pop3 public void set folder string folder set property folder folder setfolder setproperty return folder public string get folder return get property folder to string getfolder getproperty tostring param num messages the number of messages to retrieve from the mail server set this value to 1 to retrieve all messages public void set num messages int num messages set property new integer property num messages num messages num_messages setnummessages num_messages setproperty integerproperty num_messages num_messages param num messages the number of messages to retrieve from the mail server set this value to 1 to retrieve all messages public void set num messages string num messages set property new string property num messages num messages num_messages setnummessages num_messages setproperty stringproperty num_messages num_messages return the number of messages to retrieve from the mail server 1 denotes get all messages public int get num messages return get property as int num messages getnummessages getpropertyasint num_messages return the number of messages to retrieve from the mail server 1 denotes get all messages public string get num messages string return get property as string num messages getnummessagesstring getpropertyasstring num_messages param delete whether or not to delete the read messages from the folder public void set delete messages boolean delete set property new boolean property delete delete setdeletemessages setproperty booleanproperty return whether or not to delete the read messages from the folder public boolean get delete messages return get property as boolean delete getdeletemessages getpropertyasboolean return whether or not to store the retrieved message as mime message in the sample result public boolean is store mime message return get property as boolean store mime message false isstoremimemessage getpropertyasboolean store_mime_message param store mime message whether or not to store the retrieved message as mime message in the sample result public void set store mime message boolean store mime message set property store mime message store mime message false storemimemessage setstoremimemessage storemimemessage setproperty store_mime_message storemimemessage constructor for the argument object public http argument string name string value string metadata this name value false this set meta data metadata httpargument setmetadata public void set use equals boolean ue if ue set meta data else set meta data set property new boolean property use equals ue setuseequals setmetadata setmetadata setproperty booleanproperty use_equals public boolean is use equals boolean eq get property as boolean use equals if get meta data equals get value null get value length 0 set use equals true return true return eq isuseequals getpropertyasboolean use_equals getmetadata getvalue getvalue setuseequals public void set always encoded boolean ae set property new boolean property always encode ae setalwaysencoded setproperty booleanproperty always_encode public boolean is always encoded return get property as boolean always encode isalwaysencoded getpropertyasboolean always_encode constructor for the argument object public http argument string name string value this name value false httpargument public http argument string name string value boolean already encoded we assume the argument value is encoded according to the http spec i e utf 8 this name value already encoded encoder cache url argument encoding httpargument alreadyencoded alreadyencoded encodercache url_argument_encoding construct a new http argument instance param name the name of the parameter param value the value of the parameter param already encoded true if the name and value is already encoded param content encoding the encoding used for the parameter value public http argument string name string value boolean already encoded string content encoding set always encoded true if already encoded try we assume the name is always encoded according to spec name url decoder decode name encoder cache url argument encoding the value is encoded in the specified encoding value url decoder decode value content encoding catch unsupported encoding exception e log error content encoding encoding not supported throw new error e to string set name name set value value set meta data httpargument alreadyencoded contentencoding httpargument alreadyencoded contentencoding setalwaysencoded alreadyencoded urldecoder encodercache url_argument_encoding urldecoder contentencoding unsupportedencodingexception contentencoding tostring setname setvalue setmetadata public http argument string name string value string meta data boolean already encoded we assume the argument value is encoded according to the http spec i e utf 8 this name value meta data already encoded encoder cache url argument encoding httpargument metadata alreadyencoded metadata alreadyencoded encodercache url_argument_encoding construct a new http argument instance param name the name of the parameter param value the value of the parameter param meta data the separator to use between name and value param already encoded true if the name and value is already encoded param content encoding the encoding used for the parameter value public http argument string name string value string meta data boolean already encoded string content encoding this name value already encoded content encoding set meta data meta data httpargument metadata alreadyencoded contentencoding httpargument metadata alreadyencoded contentencoding alreadyencoded contentencoding setmetadata metadata public http argument argument arg this arg get name arg get value arg get meta data httpargument getname getvalue getmetadata constructor for the argument object public http argument httpargument sets the name attribute of the argument object param new name the new name value public void set name string new name if new name null new name equals get name super set name new name newname setname newname newname newname getname setname newname get the argument value encoded using utf 8 return the argument value encoded in utf 8 public string get encoded value encode according to the http spec i e utf 8 try return get encoded value encoder cache url argument encoding catch unsupported encoding exception e this can t happen how should utf8 not be supported so just throw an error throw new error should not happen e to string getencodedvalue getencodedvalue encodercache url_argument_encoding unsupportedencodingexception tostring get the argument value encoded in the specified encoding param content encoding the encoding to use when encoding the argument value return the argument value encoded in the specified encoding throws unsupported encoding exception public string get encoded value string content encoding throws unsupported encoding exception if is always encoded return cache get encoded get value content encoding else return get value contentencoding unsupportedencodingexception getencodedvalue contentencoding unsupportedencodingexception isalwaysencoded getencoded getvalue contentencoding getvalue public string get encoded name if is always encoded return cache get encoded get name else return get name getencodedname isalwaysencoded getencoded getname getname public static void convert arguments tohttp arguments args list new arguments new linked list property iterator iter args get arguments iterator while iter has next argument arg argument iter next get object value if arg instanceof http argument new arguments add new http argument arg else new arguments add arg args remove all arguments args set arguments new arguments convertargumentstohttp newarguments linkedlist propertyiterator getarguments hasnext getobjectvalue httpargument newarguments httpargument newarguments removeallarguments setarguments newarguments creates a transaction controller public transaction controller lnf new listener notifier transactioncontroller listenernotifier private object read resolve lnf new listener notifier return this readresolve listenernotifier public void set parent boolean parent set property new boolean property parent parent setparent _parent setproperty booleanproperty _parent public boolean is parent return get property as boolean parent isparent getpropertyasboolean see org apache jmeter control controller next public sampler next if is parent return next1 return next2 isparent private sampler next1 check if transaction is done if transaction sampler null transaction sampler is transaction done if log is debug enabled log debug end of transaction get name this transaction is done transaction sampler null return null check if it is the start of a new transaction if is first must be the start of the subtree if log is debug enabled log debug start of transaction get name transaction sampler new transaction sampler this get name sample the children of the transaction sampler sub sampler super next transaction sampler set sub sampler sub sampler if we do not get any sub samplers the transaction is done if sub sampler null transaction sampler set transaction done return transaction sampler transactionsampler transactionsampler istransactiondone isdebugenabled getname transactionsampler isfirst isdebugenabled getname transactionsampler transactionsampler getname subsampler transactionsampler setsubsampler subsampler subsampler transactionsampler settransactiondone transactionsampler protected sampler next isa controller controller controller throws next is null exception if is parent return super next isa controller controller sampler return value sampler sampler controller next if sampler null current returned null controller we need to call the super next instead of this next which is done in generic controller because if we call this next it will return the transaction sampler and we do not want that we need to get the next real sampler or controller return value super next else return value sampler return return value nextisacontroller nextisnullexception isparent nextisacontroller returnvalue currentreturnednull genericcontroller transactionsampler returnvalue returnvalue returnvalue private sampler next2 if is first must be the start of the subtree calls 0 no failing samples 0 res new sample result res set sample label get name assume success res set successful true res sample start sampler return value super next if return value null must be the end of the controller if res null res sample end res set response message number of samples in transaction calls number of failing samples no failing samples if res is successful res set response codeok todo could these be done earlier or just once j meter context thread context get thread context j meter variables thread vars thread context get variables sample package pack sample package thread vars get object j meter thread package object if pack null log warn could not fetch sample package else sample event event new sample event res thread context get thread group get name thread vars we must set res to null now before sending the event for the transaction so that we can ignore that event in our sample occured method res null lnf notify listeners event pack get sample listeners else we have sampled one of our children calls return return value isfirst nofailingsamples sampleresult setsamplelabel getname setsuccessful samplestart returnvalue returnvalue sampleend setresponsemessage nofailingsamples issuccessful setresponsecodeok jmetercontext threadcontext getthreadcontext jmetervariables threadvars threadcontext getvariables samplepackage samplepackage threadvars getobject jmeterthread package_object samplepackage sampleevent sampleevent threadcontext getthreadgroup getname threadvars sampleoccured notifylisteners getsamplelisteners returnvalue public void sample occurred sample event se if is parent check if we are still sampling our children if res null sample result sample result se get result res set thread name sample result get thread name res set bytes res get bytes sample result get bytes if sample result is successful res set successful false no failing samples sampleoccurred sampleevent isparent sampleresult sampleresult getresult setthreadname sampleresult getthreadname setbytes getbytes sampleresult getbytes sampleresult issuccessful setsuccessful nofailingsamples public void sample started sample event e samplestarted sampleevent public void sample stopped sample event e samplestopped sampleevent create a new loop control panel as a standalone component public run time gui this true loopcontrolpanel runtimegui create a new loop control panel as either a standalone or an embedded component param display name indicates whether or not this component should display its name if true this is a standalone component if false this component is intended to be used as a subpanel for another component public run time gui boolean display name this display name display name init set state 1 loopcontrolpanel displayname runtimegui displayname displayname displayname setstate a newly created component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui param element the test element to configure public void configure test element element super configure element if element instanceof run time set state run time element get runtime string else set state 1 testelement testelement runtime setstate runtime getruntimestring setstate implements j metergui component create test element public test element create test element run time lc new run time modify test element lc return lc jmeterguicomponent createtestelement testelement createtestelement runtime runtime modifytestelement implements j metergui component modify test element test element public void modify test element test element lc configure test element lc if lc instanceof run time if seconds get text length 0 run time lc set runtime seconds get text else run time lc set runtime 0 jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement runtime gettext runtime setruntime gettext runtime setruntime implements j metergui component clear gui public void clear gui super clear gui seconds set text 1 non nls 1 jmeterguicomponent cleargui cleargui cleargui settext invoked when an action occurs this implementation assumes that the target component is the infinite seconds checkbox param event the event that has occurred public void action performed action event event seconds set enabled true actionperformed actionevent setenabled public string get label resource return runtime controller title non nls 1 getlabelresource runtime_controller_title initialize the gui components and layout for this component private void init the loop controller panel can be displayed standalone or inside another panel for standalone we want to display the title name etc everything however if we want to display it within another panel we just display the loop count fields not the title and name standalone if display name set layout new border layout 0 5 set border make border add make title panel border layout north j panel main panel new j panel new border layout main panel add create loop count panel border layout north add main panel border layout center else embedded set layout new border layout add create loop count panel border layout north displayname setlayout borderlayout setborder makeborder maketitlepanel borderlayout jpanel mainpanel jpanel borderlayout mainpanel createloopcountpanel borderlayout mainpanel borderlayout setlayout borderlayout createloopcountpanel borderlayout create a gui panel containing the components related to the number of seconds which should be executed return a gui panel containing the loop count components private j panel create loop count panel j panel loop panel new j panel new border layout 5 0 seconds label j label seconds label new j label j meter utils get res string runtime seconds non nls 1 loop panel add seconds label border layout west j panel loop sub panel new j panel new border layout 5 0 text field seconds new j text field 1 5 non nls 1 seconds label set label for seconds loop sub panel add seconds border layout center loop panel add loop sub panel border layout center loop panel add box create horizontal strut seconds label get preferred size width seconds get preferred size width border layout north return loop panel jpanel createloopcountpanel jpanel looppanel jpanel borderlayout jlabel secondslabel jlabel jmeterutils getresstring runtime_seconds looppanel secondslabel borderlayout jpanel loopsubpanel jpanel borderlayout jtextfield secondslabel setlabelfor loopsubpanel borderlayout looppanel loopsubpanel borderlayout looppanel createhorizontalstrut secondslabel getpreferredsize getpreferredsize borderlayout looppanel set the number of seconds which should be reflected in the gui the secs count parameter should contain the string representation of an integer this integer will be treated as the number of seconds if this integer is less than 0 the number of seconds will be assumed to be infinity param secs count the string representation of the number of seconds private void set state string secs count seconds set text secs count seconds set enabled true secscount secscount setstate secscount settext secscount setenabled set the number of seconds which should be reflected in the gui if the secs count is less than 0 the number of seconds will be assumed to be infinity param secs count the number of seconds private void set state long secs count seconds set enabled true seconds set text secs count non nls 1 secscount secscount setstate secscount setenabled settext secscount returns the result of the assertion here it checks the sample response data length public assertion result get result sample result response assertion result result new assertion result get name result set failure false long result size response get bytes is the sample the correct size if compare size result size result set failure true object arguments new long result size comparator error message new long get allowed size string message message format format j meter utils get res string size assertion failure arguments non nls 1 result set failure message message return result responsedata assertionresult getresult sampleresult assertionresult assertionresult getname setfailure resultsize getbytes comparesize resultsize setfailure resultsize comparatorerrormessage getallowedsize messageformat jmeterutils getresstring size_assertion_failure setfailuremessage returns the size in bytes to be asserted public long get allowed size return get property as long size key getallowedsize getpropertyaslong size_key set the operator public void set comp oper int operator set property new integer property operator key operator setcompoper setproperty integerproperty operator_key returns the operator to be asserted equal 1 notequal 2 greaterthan 3 lessthan 4 greaterthanequal 5 lessthanequal 6 public int get comp oper return get property as int operator key getcompoper getpropertyasint operator_key set the size that shall be asserted param size a number of bytes is not allowed to be negative use long max value to indicate illegal or empty inputs this will result in not checking the assertion throws illegal argument exception if code size code is negative public void set allowed size long size throws illegal argument exception if size 0l throw new illegal argument exception j meter utils get res string argument must not be negative non nls 1 if size long max value set property new long property size key 0 else set property new long property size key size max_value illegalargumentexception setallowedsize illegalargumentexception illegalargumentexception jmeterutils getresstring argument_must_not_be_negative max_value setproperty longproperty size_key setproperty longproperty size_key compares the the size of a return result to the set allowed size using a logical comparator set in set logical comparator possible values are equal not equal greater than less than greater than eqaul less than equal private boolean compare size long result size boolean result false int comp get comp oper switch comp case equal result result size get allowed size comparator error message j meter utils get res string size assertion comparator error equal non nls 1 break case notequal result result size get allowed size comparator error message j meter utils get res string size assertion comparator error notequal non nls 1 break case greaterthan result result size get allowed size comparator error message j meter utils get res string size assertion comparator error greater non nls 1 break case lessthan result result size get allowed size comparator error message j meter utils get res string size assertion comparator error less non nls 1 break case greaterthanequal result result size get allowed size comparator error message j meter utils get res string size assertion comparator error greaterequal non nls 1 break case lessthanequal result result size get allowed size comparator error message j meter utils get res string size assertion comparator error lessequal non nls 1 break default result false comparator error message error invalid condition break return result setlogicalcomparator comparesize resultsize getcompoper resultsize getallowedsize comparatorerrormessage jmeterutils getresstring size_assertion_comparator_error_equal resultsize getallowedsize comparatorerrormessage jmeterutils getresstring size_assertion_comparator_error_notequal resultsize getallowedsize comparatorerrormessage jmeterutils getresstring size_assertion_comparator_error_greater resultsize getallowedsize comparatorerrormessage jmeterutils getresstring size_assertion_comparator_error_less resultsize getallowedsize comparatorerrormessage jmeterutils getresstring size_assertion_comparator_error_greaterequal resultsize getallowedsize comparatorerrormessage jmeterutils getresstring size_assertion_comparator_error_lessequal comparatorerrormessage see org apache jmeter protocol tcp sampler tcp client get eol byte public byte get eol byte return eol byte tcpclient geteolbyte geteolbyte eolbyte public void set eol byte int eol int if eol int byte min value eol int byte max value this eol byte byte eol int use eol byte true else use eol byte false seteolbyte eolint eolint min_value eolint max_value eolbyte eolint useeolbyte useeolbyte see org apache jmeter protocol tcp sampler tcp client setup test public void setup test tcpclient setuptest setuptest see org apache jmeter protocol tcp sampler tcp client teardown test public void teardown test tcpclient teardowntest teardowntest public user parameter modifier gui super init userparametermodifiergui public test element create test element user parameter modifier mod new user parameter modifier modify test element mod return mod testelement createtestelement userparametermodifier userparametermodifier modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element mod this configure test element mod user parameter modifier mod set xml uri file name field get text testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement userparametermodifier setxmluri filenamefield gettext implements j metergui component clear gui public void clear gui super clear gui file name field set text users xml non nls 1 jmeterguicomponent cleargui cleargui cleargui filenamefield settext public void update gui updategui public string get label resource return http user parameter modifier non nls 1 getlabelresource http_user_parameter_modifier public void configure test element el super configure el file name field set text user parameter modifier el get xml uri testelement filenamefield settext userparametermodifier getxmluri private void init set layout new border layout 0 5 set border make border add make title panel border layout north j panel main panel new j panel new border layout 0 5 main panel add get file locator border layout north we want the help text to look like a label but wrap like a text area j text area help text new j text area j meter utils get res string user param mod help note non nls 1 help text set line wrap true help text set wrap style word true help text set background get background help text set editable false j label dummy label new j label help text set font dummy label get font help text set foreground dummy label get foreground j scroll pane scroller new j scroll pane help text scroller set border border factory create empty border main panel add scroller border layout center add main panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout jpanel mainpanel jpanel borderlayout mainpanel getfilelocator borderlayout jtextarea helptext jtextarea jmeterutils getresstring user_param_mod_help_note helptext setlinewrap helptext setwrapstyleword helptext setbackground getbackground helptext seteditable jlabel dummylabel jlabel helptext setfont dummylabel getfont helptext setforeground dummylabel getforeground jscrollpane jscrollpane helptext setborder borderfactory createemptyborder mainpanel borderlayout mainpanel borderlayout private j panel get file locator file name field new j text field users xml 15 j label label new j label j meter utils get res string filename non nls 1 label set label for file name field j panel file locator new j panel new border layout file locator add label border layout west file locator add file name field border layout center return file locator jpanel getfilelocator filenamefield jtextfield jlabel jlabel jmeterutils getresstring setlabelfor filenamefield jpanel filelocator jpanel borderlayout filelocator borderlayout filelocator filenamefield borderlayout filelocator public dimension get preferred size return get minimum size getpreferredsize getminimumsize todo does not appear to be used public static string decode string s return util substitute expression s prevent instantiation of utility class private argument decoder argumentdecoder public final class component util use this static method if you want to center and set its position compared to the size of the current users screen size valid percent is between 0 100 minus is treated as plus bigger than 100 is always set to 100 param component the component you want to center and set size on param percent of screen the percent of the current screensize you want the component to be public static void center component in window component component int percent of screen if percent of screen 0 center component in window component percent of screen return if percent of screen 100 center component in window component 100 return double percent percent of screen 100 d dimension dimension component get toolkit get screen size component set size int dimension get width percent int dimension get height percent center component in window component componentutil percentofscreen centercomponentinwindow percentofscreen percentofscreen centercomponentinwindow percentofscreen percentofscreen centercomponentinwindow percentofscreen gettoolkit getscreensize setsize getwidth getheight centercomponentinwindow use this static method if you want to center a component in window param component the component you want to center in window public static void center component in window component component dimension dimension component get toolkit get screen size component set location int dimension get width component get width 2 int dimension get height component get height 2 component validate component repaint centercomponentinwindow gettoolkit getscreensize setlocation getwidth getwidth getheight getheight use this static method if you want to center a component over another component param parent the component you want to use to place it on param to be centered the component you want to center public static void center component in component component parent component to be centered to be centered set location parent getx parent get width to be centered get width 2 parent gety parent get height to be centered get height 2 to be centered validate to be centered repaint tobecentered centercomponentincomponent tobecentered tobecentered setlocation getwidth tobecentered getwidth getheight tobecentered getheight tobecentered tobecentered private constructor to prevent instantiation private component util componentutil returns the converter version used to check for possible incompatibilities public static string get version return revision 674365 non nls 1 getversion see com thoughtworks xstream converters converter can convert java lang class public boolean can convert class arg0 return arg0 equals integer property class canconvert canconvert integerproperty public void marshal object obj hierarchical stream writer writer marshalling context arg2 integer property prop integer property obj writer add attribute att name conversion help encode prop get name writer set value prop get string value hierarchicalstreamwriter marshallingcontext integerproperty integerproperty addattribute att_name conversionhelp getname setvalue getstringvalue public object unmarshal hierarchical stream reader reader unmarshalling context arg1 integer property prop new integer property conversion help decode reader get attribute att name integer parse int reader get value return prop hierarchicalstreamreader unmarshallingcontext integerproperty integerproperty conversionhelp getattribute att_name parseint getvalue create a new assertion gui panel public assertion gui init assertiongui assertiongui public string get label resource return assertion title non nls 1 getlabelresource assertion_title implements j metergui component create test element public test element create test element response assertion el new response assertion modify test element el return el jmeterguicomponent createtestelement testelement createtestelement responseassertion responseassertion modifytestelement implements j metergui component modify test element test element public void modify test element test element el configure test element el if el instanceof response assertion response assertion ra response assertion el save scope settings ra ra clear test strings string test strings table model get data get column col resource name for int i 0 i test strings length i ra add test string test strings i if response string button is selected ra set test field response data else if response code button is selected ra set test field response code else if response message button is selected ra set test field response message else if response headers button is selected ra set test field response headers else assume url ra set test fieldurl ra set assume success assume success is selected if contains box is selected ra set to contains type else if equals box is selected ra set to equals type else if substring box is selected ra set to substring type else ra set to match type if not box is selected ra set to not type else ra unset not type jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement responseassertion responseassertion responseassertion savescopesettings clearteststrings teststrings tablemodel getdata getcolumn col_resource_name teststrings addteststring teststrings responsestringbutton isselected settestfieldresponsedata responsecodebutton isselected settestfieldresponsecode responsemessagebutton isselected settestfieldresponsemessage responseheadersbutton isselected settestfieldresponseheaders settestfieldurl setassumesuccess assumesuccess isselected containsbox isselected settocontainstype equalsbox isselected settoequalstype substringbox isselected settosubstringtype settomatchtype notbox isselected settonottype unsetnottype implements j metergui component clear gui public void clear gui super clear gui table model clear data response string button set selected true url button set selected false response code button set selected false response message button set selected false response headers button set selected false assume success set selected false contains box set selected true not box set selected false jmeterguicomponent cleargui cleargui cleargui tablemodel cleardata responsestringbutton setselected urlbutton setselected responsecodebutton setselected responsemessagebutton setselected responseheadersbutton setselected assumesuccess setselected containsbox setselected notbox setselected a newly created component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui param el the test element to configure public void configure test element el super configure el response assertion model response assertion el show scope settings model if model is contains type contains box set selected true else if model is equals type equals box set selected true else if model is substring type substring box set selected true else matches box set selected true not box set selected model is not type if model is test field response data response string button set selected true else if model is test field response code response code button set selected true else if model is test field response message response message button set selected true else if model is test field response headers response headers button set selected true else assume it is the url url button set selected true assume success set selected model get assume success table model clear data property iterator tests model get test strings iterator while tests has next table model add row new object tests next get string value if model get test strings size 0 delete pattern set enabled false else delete pattern set enabled true table model fire table data changed testelement testelement responseassertion responseassertion showscopesettings iscontainstype containsbox setselected isequalstype equalsbox setselected issubstringtype substringbox setselected matchesbox setselected notbox setselected isnottype istestfieldresponsedata responsestringbutton setselected istestfieldresponsecode responsecodebutton setselected istestfieldresponsemessage responsemessagebutton setselected istestfieldresponseheaders responseheadersbutton setselected urlbutton setselected assumesuccess setselected getassumesuccess tablemodel cleardata propertyiterator getteststrings hasnext tablemodel addrow getstringvalue getteststrings deletepattern setenabled deletepattern setenabled tablemodel firetabledatachanged initialize the gui components and layout private void init set layout new border layout box box box create vertical box set border make border box add make title panel box add create scope panel box add create field panel box add create type panel add box border layout north add create string panel border layout center setlayout borderlayout createverticalbox setborder makeborder maketitlepanel createscopepanel createfieldpanel createtypepanel borderlayout createstringpanel borderlayout create a panel allowing the user to choose which response field should be tested return a new panel for selecting the response field private j panel create field panel j panel panel new j panel panel set border border factory create titled border j meter utils get res string assertion resp field non nls 1 response string button new j radio button j meter utils get res string assertion text resp non nls 1 url button new j radio button j meter utils get res string assertion url samp non nls 1 response code button new j radio button j meter utils get res string assertion code resp non nls 1 response message button new j radio button j meter utils get res string assertion message resp non nls 1 response headers button new j radio button j meter utils get res string assertion headers non nls 1 button group group new button group group add response string button group add url button group add response code button group add response message button group add response headers button panel add response string button panel add url button panel add response code button panel add response message button panel add response headers button response string button set selected true assume success new j check box j meter utils get res string assertion assume success non nls 1 panel add assume success return panel jpanel createfieldpanel jpanel jpanel setborder borderfactory createtitledborder jmeterutils getresstring assertion_resp_field responsestringbutton jradiobutton jmeterutils getresstring assertion_text_resp urlbutton jradiobutton jmeterutils getresstring assertion_url_samp responsecodebutton jradiobutton jmeterutils getresstring assertion_code_resp responsemessagebutton jradiobutton jmeterutils getresstring assertion_message_resp responseheadersbutton jradiobutton jmeterutils getresstring assertion_headers buttongroup buttongroup responsestringbutton urlbutton responsecodebutton responsemessagebutton responseheadersbutton responsestringbutton urlbutton responsecodebutton responsemessagebutton responseheadersbutton responsestringbutton setselected assumesuccess jcheckbox jmeterutils getresstring assertion_assume_success assumesuccess create a panel allowing the user to choose what type of test should be performed return a new panel for selecting the type of assertion test private j panel create type panel j panel panel new j panel panel set border border factory create titled border j meter utils get res string assertion pattern match rules non nls 1 button group group new button group contains box new j radio button j meter utils get res string assertion contains non nls 1 group add contains box contains box set selected true panel add contains box matches box new j radio button j meter utils get res string assertion matches non nls 1 group add matches box panel add matches box equals box new j radio button j meter utils get res string assertion equals non nls 1 group add equals box panel add equals box substring box new j radio button j meter utils get res string assertion substring non nls 1 group add substring box panel add substring box not box new j check box j meter utils get res string assertion not non nls 1 panel add not box return panel jpanel createtypepanel jpanel jpanel setborder borderfactory createtitledborder jmeterutils getresstring assertion_pattern_match_rules buttongroup buttongroup containsbox jradiobutton jmeterutils getresstring assertion_contains containsbox containsbox setselected containsbox matchesbox jradiobutton jmeterutils getresstring assertion_matches matchesbox matchesbox equalsbox jradiobutton jmeterutils getresstring assertion_equals equalsbox equalsbox substringbox jradiobutton jmeterutils getresstring assertion_substring substringbox substringbox notbox jcheckbox jmeterutils getresstring assertion_not notbox create a panel allowing the user to supply a list of string patterns to test against return a new panel for adding string patterns private j panel create string panel table model new power table model new string col resource name new class string class string table new j table table model string table get table header set default renderer new header as property renderer text area cell renderer renderer new text area cell renderer string table set row height renderer get preferred height string table set default renderer string class renderer string table set default editor string class new text area table cell editor string table set preferred scrollable viewport size new dimension 100 70 j panel panel new j panel panel set layout new border layout panel set border border factory create titled border j meter utils get res string assertion patterns to test non nls 1 panel add new j scroll pane string table border layout center panel add create button panel border layout south return panel jpanel createstringpanel tablemodel powertablemodel col_resource_name stringtable jtable tablemodel stringtable gettableheader setdefaultrenderer headeraspropertyrenderer textareacellrenderer textareacellrenderer stringtable setrowheight getpreferredheight stringtable setdefaultrenderer stringtable setdefaulteditor textareatablecelleditor stringtable setpreferredscrollableviewportsize jpanel jpanel setlayout borderlayout setborder borderfactory createtitledborder jmeterutils getresstring assertion_patterns_to_test jscrollpane stringtable borderlayout createbuttonpanel borderlayout create a panel with buttons to add and delete string patterns return the new panel with add and delete buttons private j panel create button panel add pattern new j button j meter utils get res string add non nls 1 add pattern add action listener new add pattern listener delete pattern new j button j meter utils get res string delete non nls 1 delete pattern add action listener new clear patterns listener delete pattern set enabled false j panel button panel new j panel button panel add add pattern button panel add delete pattern return button panel jpanel createbuttonpanel addpattern jbutton jmeterutils getresstring addpattern addactionlistener addpatternlistener deletepattern jbutton jmeterutils getresstring deletepattern addactionlistener clearpatternslistener deletepattern setenabled jpanel buttonpanel jpanel buttonpanel addpattern buttonpanel deletepattern buttonpanel private class clear patterns listener implements action listener public void action performed action event e int index string table get selected row if index 1 string table get cell editor index string table get selected column cancel cell editing table model remove row index table model fire table data changed if string table get model get row count 0 delete pattern set enabled false clearpatternslistener actionlistener actionperformed actionevent stringtable getselectedrow stringtable getcelleditor stringtable getselectedcolumn cancelcellediting tablemodel removerow tablemodel firetabledatachanged stringtable getmodel getrowcount deletepattern setenabled private class add pattern listener implements action listener public void action performed action event e table model add new row delete pattern set enabled true table model fire table data changed addpatternlistener actionlistener actionperformed actionevent tablemodel addnewrow deletepattern setenabled tablemodel firetabledatachanged public class example2 bean info extends bean info support public example2 bean info super example2 class example2beaninfo beaninfosupport example2beaninfo private static remotej meter engine get engine string h throws malformedurl exception remote exception not bound exception final string name h remotej meter engine impl jmeter engine rmi name non nls 1 non nls 2 remote remobj naming lookup name if remobj instanceof remotej meter engine final remotej meter engine rje remotej meter engine remobj if remobj instanceof remote object remote object robj remote object remobj system out println using remote object robj get ref remote to string return rje throw new remote exception could not find name remotejmeterengine getengine malformedurlexception remoteexception notboundexception remotejmeterengineimpl jmeter_engine_rmi_name remotejmeterengine remotejmeterengine remotejmeterengine remoteobject remoteobject remoteobject getref remotetostring remoteexception public clientj meter engine string host throws malformedurl exception not bound exception remote exception this remote get engine host this host host clientjmeterengine malformedurlexception notboundexception remoteexception getengine public void configure hash tree test tree tree cloner cloner new tree cloner false test tree traverse cloner test cloner get cloned tree hashtree testtree treecloner treecloner testtree getclonedtree public void run test log info about to run remote test on host new thread this start log info done initiating run command runtest public void stop test log info about to stop remote test on host try remote stop test catch exception ex log error ex non nls 1 stoptest stoptest public void reset try try remote reset catch java rmi connect exception e remote get engine host remote reset catch exception ex log error ex non nls 1 connectexception getengine public void run log info running clientengine run method search by class test listeners new search by class test listener class convert listeners sample listeners new convert listeners hash tree test tree test pre compiler compiler new pre compiler true limit the changes to client only test elements synchronized test tree test tree traverse compiler test tree traverse new turn elements on test tree traverse test listeners test tree traverse sample listeners try j meter context service start test remote configure test host log info sent test to host if savep null log info sending properties savep try remote set properties savep catch remote exception e log warn could not set properties e to string remote run test log info sent run command to host catch exception ex log error ex non nls 1 searchbyclass testlisteners searchbyclass testlistener convertlisteners samplelisteners convertlisteners hashtree testtree precompiler precompiler testtree testtree testtree turnelementson testtree testlisteners testtree samplelisteners jmetercontextservice starttest setproperties remoteexception tostring runtest public void exit log info about to exit remote server on host try remote exit catch remote exception e log warn could not perform remote exit e to string remoteexception tostring private properties savep public void set properties properties p savep p sent later setproperties ensure transient object is created by the server private object read resolve sync new object return this readresolve return returns the num threads public int get group size return group size numthreads getgroupsize groupsize param num threads the num threads to set public void set group size int num threads this group size num threads numthreads numthreads setgroupsize numthreads groupsize numthreads public long delay synchronized sync timer counter 0 final int group sz get group size final int count timer counter 0 if group sz 0 count j meter context service get number of threads group sz 0 count group sz sync notify all else try sync wait catch interrupted exception e log warn e get localized message timer counter 0 0 reset for next time return 0 timercounter groupsz getgroupsize timercounter groupsz jmetercontextservice getnumberofthreads groupsz groupsz notifyall interruptedexception getlocalizedmessage timercounter we have to control the cloning process because we need some cross thread communication if our synctimers are to be able to determine when to block and when to release public object clone sync timer new timer sync timer super clone new timer timer counter timer counter new timer sync sync return new timer synctimer newtimer synctimer newtimer timercounter timercounter newtimer newtimer create a new argument without a name value or metadata public ldap argument ldapargument create a new argument with the specified name and value and no metadata param name the argument name param value the argument value public ldap argument string name string value string opcode set property new string property arg name name set property new string property value value set property new string property opcode opcode ldapargument setproperty stringproperty arg_name setproperty stringproperty setproperty stringproperty create a new argument with the specified name value and metadata param name the argument name param value the argument value param metadata the argument metadata public ldap argument string name string value string opcode string metadata set property new string property arg name name set property new string property value value set property new string property opcode opcode set property new string property metadata metadata ldapargument setproperty stringproperty arg_name setproperty stringproperty setproperty stringproperty setproperty stringproperty set the name of the argument param new name the new name public void set name string new name set property new string property arg name new name newname setname newname setproperty stringproperty arg_name newname get the name of the argument return the attribute s name public string get name return get property as string arg name getname getpropertyasstring arg_name sets the value of the argument param new value the new value public void set value string new value set property new string property value new value newvalue setvalue newvalue setproperty stringproperty newvalue gets the value of the argument object return the attribute s value public string get value return get property as string value getvalue getpropertyasstring sets the opcode of the argument param new opcode the new value public void set opcode string new opcode set property new string property opcode new opcode newopcode setopcode newopcode setproperty stringproperty newopcode gets the opcode of the argument object return the attribute s value public string get opcode return get property as string opcode getopcode getpropertyasstring sets the meta data attribute of the argument param new meta data the new metadata public void set meta data string new meta data set property new string property metadata new meta data newmetadata setmetadata newmetadata setproperty stringproperty newmetadata gets the meta data attribute of the argument return the meta data value public string get meta data return get property as string metadata metadata getmetadata getpropertyasstring private j label proxy message3 new j label j meter utils get res string webservice proxy note3 non nls 1 public web service sampler gui init jlabel proxymessage3 jlabel jmeterutils getresstring webservice_proxy_note3 webservicesamplergui public string get label resource return webservice sampler title non nls 1 getlabelresource webservice_sampler_title see org apache jmeter gui j metergui component create test element public test element create test element web service sampler sampler new web service sampler this configure test element sampler this modify test element sampler return sampler jmeterguicomponent createtestelement testelement createtestelement webservicesampler webservicesampler configuretestelement modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element s web service sampler sampler web service sampler s this configure test element sampler sampler set domain domain get text sampler set property http sampler base port port get text sampler set protocol protocol get text sampler set path path get text sampler set wsdlurl wsdl field get text sampler set method http sampler base post sampler set soap action soap action get text sampler set xml data soap xml get text sampler set xml file soap xml file get filename sampler set xml path loc random xml file get text sampler set timeout connect timeout get text sampler set memory cache mem cache is selected sampler set read response read response is selected sampler set use proxy use proxy is selected sampler set proxy host proxy host get text sampler set proxy port proxy port get text testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement webservicesampler webservicesampler configuretestelement setdomain gettext setproperty httpsamplerbase gettext setprotocol gettext setpath gettext setwsdlurl wsdlfield gettext setmethod httpsamplerbase setsoapaction soapaction gettext setxmldata soapxml gettext setxmlfile soapxmlfile getfilename setxmlpathloc randomxmlfile gettext settimeout connecttimeout gettext setmemorycache memcache isselected setreadresponse readresponse isselected setuseproxy useproxy isselected setproxyhost proxyhost gettext setproxyport proxyport gettext implements j metergui component clear gui public void clear gui super clear gui domain set text non nls 1 protocol set text non nls 1 port set text non nls 1 path set text non nls 1 soap action set text non nls 1 soap xml set text non nls 1 wsdl field set text non nls 1 random xml file set text non nls 1 connect timeout set text non nls 1 proxy host set text non nls 1 proxy port set text non nls 1 mem cache set selected true read response set selected false use proxy set selected false soap xml file set filename non nls 1 jmeterguicomponent cleargui cleargui cleargui settext settext settext settext soapaction settext soapxml settext wsdlfield settext randomxmlfile settext connecttimeout settext proxyhost settext proxyport settext memcache setselected readresponse setselected useproxy setselected soapxmlfile setfilename init adds soap action to the main panel the class reuses logic from soap sampler since it is common private void init set layout new border layout 0 5 set border make border add make title panel border layout north wsdl message set font plain text wsdl message2 set font plain text wsdl message3 set font plain text wsdl message4 set font plain text wsdl message5 set font plain text read message set font plain text read message2 set font plain text read message3 set font plain text main panel j panel main panel new j panel border margin new empty border 10 10 5 10 main panel set border margin main panel set layout new vertical layout 5 vertical layout both button for browsing webservice wsdl j panel wsdl entry new j panel main panel add wsdl entry wsdl entry add wsdl field wsdl entry add wsdl button wsdl button add action listener this web methods j panel list panel new j panel j label select label new j label web methods wsdl methods new j labeled choice main panel add list panel list panel add select label list panel add wsdl methods list panel add select button select button add action listener this main panel add protocol main panel add domain main panel add port main panel add path main panel add connect timeout main panel add soap action optional tasks we create a preferred size for the soap text area the width is the same as the soap file browser dimension pref new dimension 400 200 soap xml set preferred size pref main panel add soap xml main panel add soap xml file main panel add wsdl message main panel add wsdl message2 main panel add wsdl message3 main panel add wsdl message4 main panel add wsdl message5 main panel add random xml file main panel add mem cache main panel add read response main panel add read message main panel add read message2 main panel add read message3 add the proxy elements main panel add use proxy use proxy add action listener this main panel add proxy host main panel add proxy port add the proxy notes proxy message set font plain text proxy message2 set font plain text proxy message3 set font plain text main panel add proxy message main panel add proxy message2 main panel add proxy message3 this add main panel soapaction mainpanel soapsampler setlayout borderlayout setborder makeborder maketitlepanel borderlayout wsdlmessage setfont plaintext wsdlmessage2 setfont plaintext wsdlmessage3 setfont plaintext wsdlmessage4 setfont plaintext wsdlmessage5 setfont plaintext readmessage setfont plaintext readmessage2 setfont plaintext readmessage3 setfont plaintext jpanel mainpanel jpanel emptyborder mainpanel setborder mainpanel setlayout verticallayout verticallayout jpanel wsdlentry jpanel mainpanel wsdlentry wsdlentry wsdlfield wsdlentry wsdlbutton wsdlbutton addactionlistener jpanel listpanel jpanel jlabel selectlabel jlabel wsdlmethods jlabeledchoice mainpanel listpanel listpanel selectlabel listpanel wsdlmethods listpanel selectbutton selectbutton addactionlistener mainpanel mainpanel mainpanel mainpanel mainpanel connecttimeout mainpanel soapaction soapxml setpreferredsize mainpanel soapxml mainpanel soapxmlfile mainpanel wsdlmessage mainpanel wsdlmessage2 mainpanel wsdlmessage3 mainpanel wsdlmessage4 mainpanel wsdlmessage5 mainpanel randomxmlfile mainpanel memcache mainpanel readresponse mainpanel readmessage mainpanel readmessage2 mainpanel readmessage3 mainpanel useproxy useproxy addactionlistener mainpanel proxyhost mainpanel proxyport proxymessage setfont plaintext proxymessage2 setfont plaintext proxymessage3 setfont plaintext mainpanel proxymessage mainpanel proxymessage2 mainpanel proxymessage3 mainpanel the implementation loads the url and the soap action for the request public void configure test element el super configure el web service sampler sampler web service sampler el wsdl field set text sampler get wsdlurl protocol set text sampler get protocol domain set text sampler get domain port set text sampler get property as string http sampler base port path set text sampler get path soap action set text sampler get soap action soap xml set text sampler get xml data soap xml file set filename sampler get xml file random xml file set text sampler get xml path loc connect timeout set text sampler get timeout mem cache set selected sampler get memory cache read response set selected sampler get read response use proxy set selected sampler get use proxy if sampler get proxy host length 0 proxy host set enabled false else proxy host set text sampler get proxy host if sampler get proxy port 0 proxy port set enabled false else proxy port set text string value of sampler get proxy port testelement webservicesampler webservicesampler wsdlfield settext getwsdlurl settext getprotocol settext getdomain settext getpropertyasstring httpsamplerbase settext getpath soapaction settext getsoapaction soapxml settext getxmldata soapxmlfile setfilename getxmlfile randomxmlfile settext getxmlpathloc connecttimeout settext gettimeout memcache setselected getmemorycache readresponse setselected getreadresponse useproxy setselected getuseproxy getproxyhost proxyhost setenabled proxyhost settext getproxyhost getproxyport proxyport setenabled proxyport settext valueof getproxyport configure the sampler from the wsdl if the wsdl did not include service node it will use the original url minus the querystring that may not be correct so we should probably add a note for microsoft webservices it will work since that s how iis works public void configure fromwsdl if helper null if helper get binding null this protocol set text helper get protocol this domain set text helper get binding host if helper get binding port 0 this port set text string value of helper get binding port else this port set text 80 non nls 1 this path set text helper get binding path this soap action set text helper get soap action this wsdl methods get text configurefromwsdl getbinding settext getprotocol settext getbindinghost getbindingport settext valueof getbindingport settext settext getbindingpath soapaction settext getsoapaction wsdlmethods gettext the method uses wsdl helper to get the information from the wsdl since the logic for getting the description is isolated to this method we can easily replace it with a different wsdl driver later on param url return array of web methods public string browsewsdl string url try we get the auth manager and pass it to the wsdl helper once the sampler is updated to axis all of this stuff should not be necessary now i just need to find the time and motivation to do it web service sampler sampler web service sampler this create test element auth manager manager sampler get auth manager helper new wsdl helper url manager helper parse return helper get web methods catch exception exception j option pane show confirm dialog this j meter utils get res string wsdl helper error non nls 1 n exception non nls 1 warning j option pane default option j option pane error message return array utils empty string array wsdlhelper authmanager wsdlhelper webservicesampler webservicesampler createtestelement authmanager getauthmanager wsdlhelper getwebmethods joptionpane showconfirmdialog jmeterutils getresstring wsdl_helper_error joptionpane default_option joptionpane error_message arrayutils empty_string_array method from action listener param event that occurred public void action performed action event event final object event source event get source if event source select button this configure fromwsdl else if event source use proxy if use proxy is checked we enable the text fields for the host and port boolean use use proxy is selected if use proxy host set enabled true proxy port set enabled true else proxy host set enabled false proxy port set enabled false else if event source wsdl button final string wsdl text wsdl field get text if wsdl text null wsdl text length 0 string wsdl data browsewsdl wsdl text if wsdl data null wsdl methods set values wsdl data wsdl methods repaint else j option pane show confirm dialog this j meter utils get res string wsdl url error non nls 1 warning j option pane default option j option pane error message actionlistener actionperformed actionevent eventsource getsource eventsource selectbutton configurefromwsdl eventsource useproxy useproxy isselected proxyhost setenabled proxyport setenabled proxyhost setenabled proxyport setenabled eventsource wsdlbutton wsdltext wsdlfield gettext wsdltext wsdltext wsdldata wsdltext wsdldata wsdlmethods setvalues wsdldata wsdlmethods joptionpane showconfirmdialog jmeterutils getresstring wsdl_url_error joptionpane default_option joptionpane error_message private constructor to prevent instantiation private j orphan utils jorphanutils this is almost equivalent to the string split method in jdk 1 4 it is here to enable us to support earlier jd ks note that unlike jdk1 4 split it optionally ignores leading split characters and the split char parameter is not a regular expression p this piece of code used to be part of j meter utils but was moved here because some j orphan classes use it too param splittee string to be split param split char character s to split the string on these are treated as a single unit param truncate should adjacent and leading trailing split chars be removed return array of all the tokens see split string string string public static string split string splittee string split char boolean truncate if splittee null split char null return new string 0 final string empty element int spot final int split length split char length final string adjacent split split char split char final int adjacent split length adjacent split length if truncate while spot splittee index of adjacent split 1 splittee splittee substring 0 spot split length splittee substring spot adjacent split length splittee length if splittee starts with split char splittee splittee substring split length if splittee ends with split char remove trailing splitter splittee splittee substring 0 splittee length split length vector returns new vector final int length splittee length this is the new length int start 0 spot 0 while start length spot splittee index of split char start 1 if spot 0 returns add element splittee substring start spot else returns add element empty element start spot split length if start length returns add splittee substring start else if spot length split length found split char at end of line returns add element empty element string values new string returns size returns copy into values return values _almost_ jdks splitchar jmeterutils jorphan splitchar splitchars splitchar splitchar empty_element splitlength splitchar adjacentsplit splitchar splitchar adjacentsplitlength adjacentsplit indexof adjacentsplit splitlength adjacentsplitlength startswith splitchar splitlength endswith splitchar splitlength indexof splitchar addelement addelement empty_element splitlength splitlength splitchar addelement empty_element copyinto public static string split string splittee string split char return split splittee split char true splitchar splitchar takes a string and a tokenizer character string and returns a new array of strings of the string split by the tokenizer character s trailing delimiters are significant unless the default null param splittee string to be split param delims delimiter character s to split the string on param def default value to place between two split chars that have nothing between them if null then ignore omitted elements return array of all the tokens throws null pointer exception if splittee or delims are null see split string string boolean see split string string this is a rewritten version of j meter utils split public static string split string splittee string delims string def string tokenizer tokens new string tokenizer splittee delims def null boolean last was delim false list str list new array list while tokens has more tokens string tok tokens next token if tok length 1 we have a single character could be a token delims index of tok 1 it is a token if last was delim we saw a delimiter last time str list add def so add the default last was delim true else last was delim false str list add tok if last was delim str list add def return string str list to array new string 0 nullpointerexception jmeterutils stringtokenizer stringtokenizer lastwasdelim strlist arraylist hasmoretokens nexttoken indexof lastwasdelim strlist lastwasdelim lastwasdelim strlist lastwasdelim strlist strlist toarray right aligns some text in a string buffer n b modifies the input buffer param in string buffer containing some text param len output length desired return input string buffer with leading spaces public static string buffer right align string buffer in int len int pfx len in length if pfx 0 return in if pfx spaces len pfx spaces len in insert 0 spaces substring 0 pfx return in stringbuffer stringbuffer stringbuffer stringbuffer rightalign stringbuffer spaces_len spaces_len left aligns some text in a string buffer n b modifies the input buffer param in string buffer containing some text param len output length desired return input string buffer with trailing spaces public static string buffer left align string buffer in int len int sfx len in length if sfx 0 return in if sfx spaces len sfx spaces len in append spaces substring 0 sfx return in stringbuffer stringbuffer stringbuffer stringbuffer leftalign stringbuffer spaces_len spaces_len convert a boolean to its string representation equivalent to boolean value of boolean to string to upper case but valid also for jdk 1 3 which does not have value of boolean param value boolean to convert return true or false public static string boolean tostring boolean value return value true false valueof tostring touppercase valueof booleantostring simple minded string replace for jdk1 3 should probably be recoded param source input string param search string to look for no regular expressions param replace string to replace the search string return the output string public static string replace first string source string search string replace int start source index of search int len search length if start 1 return source if start 0 return replace source substring len return source substring 0 start replace source substring start len replacefirst indexof version of string replace all for jdk1 3 see below for another version which replaces strings rather than chars param source input string param search char to look for no regular expressions param replace string to replace the search string return the output string public static string replace all chars string source char search string replace char chars source to char array string buffer sb new string buffer source length 20 for int i 0 i chars length i char c chars i if c search sb append replace else sb append c return sb to string replaceall replaceallchars tochararray stringbuffer stringbuffer tostring replace all patterns in a string see string replace all string regex string replacement jdk1 4 only param input string to be transformed param pattern pattern to replace param sub replacement return the updated string public static string substitute final string input final string pattern final string sub string buffer ret new string buffer input length int start 0 int index 1 final int length pattern length while index input index of pattern start start ret append input substring start index ret append sub start index length ret append input substring start return ret to string replaceall stringbuffer stringbuffer indexof tostring trim a string by the tokens provided param input string to trim param delims list of delimiters return input trimmed at the first delimiter public static string trim final string input final string delims string tokenizer tokens new string tokenizer input delims return tokens has more tokens tokens next token stringtokenizer stringtokenizer hasmoretokens nexttoken returns a slice of a byte array todo add bounds checking param array input array param begin start of slice param end end of slice return slice from the input array public static byte get byte array slice byte array int begin int end byte slice new byte end begin 1 int count 0 for int i begin i end i slice count array i count return slice getbytearrayslice todo perhaps deprecate these in favour of commons io close a stream with no error thrown param is input stream may be null public static void close quietly input stream is try if is null is close catch io exception ignored inputstream closequietly inputstream ioexception close a stream with no error thrown param os output stream may be null public static void close quietly output stream os try if os null os close catch io exception ignored outputstream closequietly outputstream ioexception close a writer with no error thrown param wr writer may be null public static void close quietly writer wr try if wr null wr close catch io exception ignored closequietly ioexception close a reader with no error thrown param rd reader may be null public static void close quietly reader rd try if rd null rd close catch io exception ignored closequietly ioexception close a socket with no error thrown param sock socket may be null public static void close quietly socket sock try if sock null sock close catch io exception ignored closequietly ioexception close a socket with no error thrown param sock server socket may be null public static void close quietly server socket sock try if sock null sock close catch io exception ignored serversocket closequietly serversocket ioexception check if a byte array starts with the given byte array see string starts with string int param target array to scan param search array to search for param offset starting offset 0 return true if the search array matches the target at the current offset public static boolean starts with byte target byte search int offset final int target length target length final int search length search length if offset 0 search length target length offset return false for int i 0 i search length i if target i offset search i return false return true startswith startswith targetlength searchlength searchlength targetlength searchlength detects if some content starts with the standard xml prefix param target the content to check return true if the document starts with the standard xml prefix public static boolean isxml byte target return starts with target xml pfx 0 startswith xml_pfx convert binary byte array to hex string param ba input binary byte array return hex representation of binary input public static string ba to hex string byte ba str builder sb new str builder ba length 2 for int i 0 i ba length i int j ba i 0xff if j 16 sb append 0 non nls 1 add zero padding sb append integer to hex string j return sb to string batohexstring strbuilder strbuilder tohexstring tostring public class xml assertion gui extends abstract assertion gui the constructor public xml assertion gui init xmlassertiongui abstractassertiongui xmlassertiongui returns the label to be shown within the j tree component public string get label resource return xml assertion title non nls 1 jtree getlabelresource xml_assertion_title public test element create test element xml assertion el new xml assertion modify test element el return el testelement createtestelement xmlassertion xmlassertion modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element el configure test element el testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement configures the associated test element param el public void configure test element el super configure el testelement inits the gui private void init set layout new vertical layout 5 vertical layout both vertical layout top set border make border add make title panel setlayout verticallayout verticallayout verticallayout setborder makeborder maketitlepanel default constructor public auth panel table model new inner table model init authpanel tablemodel innertablemodel public test element create test element auth manager auth man table model manager configure test element auth man return test element auth man clone testelement createtestelement authmanager authman tablemodel configuretestelement authman testelement authman modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element el if auth table is editing auth table get cell editor stop cell editing el clear el add test element test element table model manager clone configure test element el testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement authtable isediting authtable getcelleditor stopcellediting addtestelement testelement tablemodel configuretestelement implements j metergui component clear public void clear gui super clear gui table model clear data delete button set enabled false save button set enabled false jmeterguicomponent cleargui cleargui tablemodel cleardata deletebutton setenabled savebutton setenabled public void configure test element el super configure el table model manager clear table model manager add test element auth manager el clone if table model get row count 0 delete button set enabled true save button set enabled true testelement tablemodel tablemodel addtestelement authmanager tablemodel getrowcount deletebutton setenabled savebutton setenabled public string get label resource return auth manager title non nls 1 getlabelresource auth_manager_title shows the main authentication panel for this object private void init called from ctor so must not be overridable set layout new border layout set border make border add make title panel border layout north add create auth table panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout createauthtablepanel borderlayout public void action performed action event e string action e get action command if action equals delete command if table model get row count 0 if a table cell is being edited we must cancel the editing before deleting the row if auth table is editing table cell editor cell editor auth table get cell editor auth table get editing row auth table get editing column cell editor cancel cell editing int row selected auth table get selected row if row selected 1 table model remove row row selected table model fire table data changed disable the delete and save buttons if no rows remaining after delete if table model get row count 0 delete button set enabled false save button set enabled false table still contains one or more rows so highlight select the appropriate one else int row to select row selected if row selected table model get row count row to select row selected 1 auth table set row selection interval row to select row to select else if action equals add command if a table cell is being edited we should accept the current value and stop the editing before adding a new row if auth table is editing table cell editor cell editor auth table get cell editor auth table get editing row auth table get editing column cell editor stop cell editing table model add new row table model fire table data changed enable the delete and save buttons if they are currently disabled if delete button is enabled delete button set enabled true if save button is enabled save button set enabled true highlight select the appropriate row int row to select table model get row count 1 auth table set row selection interval row to select row to select else if action equals load command try final string txt txt non nls 1 final j file chooser dialog file dialoger prompt to open file txt if dialog null table model manager add file dialog get selected file get absolute path table model fire table data changed if table model get row count 0 delete button set enabled true save button set enabled true catch io exception ex log error ex else if action equals save command try final j file chooser chooser file dialoger prompt to save file auth txt non nls 1 if chooser null table model manager save chooser get selected file get absolute path catch io exception ex log error ex actionperformed actionevent getactioncommand delete_command tablemodel getrowcount authtable isediting tablecelleditor celleditor authtable getcelleditor authtable geteditingrow authtable geteditingcolumn celleditor cancelcellediting rowselected authtable getselectedrow rowselected tablemodel removerow rowselected tablemodel firetabledatachanged tablemodel getrowcount deletebutton setenabled savebutton setenabled rowtoselect rowselected rowselected tablemodel getrowcount rowtoselect rowselected authtable setrowselectioninterval rowtoselect rowtoselect add_command authtable isediting tablecelleditor celleditor authtable getcelleditor authtable geteditingrow authtable geteditingcolumn celleditor stopcellediting tablemodel addnewrow tablemodel firetabledatachanged deletebutton isenabled deletebutton setenabled savebutton isenabled savebutton setenabled rowtoselect tablemodel getrowcount authtable setrowselectioninterval rowtoselect rowtoselect load_command _txt jfilechooser filedialoger prompttoopenfile _txt tablemodel addfile getselectedfile getabsolutepath tablemodel firetabledatachanged tablemodel getrowcount deletebutton setenabled savebutton setenabled ioexception save_command jfilechooser filedialoger prompttosavefile tablemodel getselectedfile getabsolutepath ioexception public j panel create auth table panel create the j table that holds auth per row auth table new j table table model auth table get table header set default renderer new header as property renderer auth table set selection mode list selection model single selection auth table set preferred scrollable viewport size new dimension 100 70 table column password column auth table get column model get column auth manager col password password column set cell editor new default cell editor new j password field password column set cell renderer new password cell renderer j panel panel new j panel new border layout 0 5 panel set border border factory create titled border border factory create etched border j meter utils get res string auths stored non nls 1 panel add new j scroll pane auth table panel add create button panel border layout south return panel jpanel createauthtablepanel jtable authtable jtable tablemodel authtable gettableheader setdefaultrenderer headeraspropertyrenderer authtable setselectionmode listselectionmodel single_selection authtable setpreferredscrollableviewportsize tablecolumn passwordcolumn authtable getcolumnmodel getcolumn authmanager col_password passwordcolumn setcelleditor defaultcelleditor jpasswordfield passwordcolumn setcellrenderer passwordcellrenderer jpanel jpanel borderlayout setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring auths_stored jscrollpane authtable createbuttonpanel borderlayout private j button create button string res name char mnemonic string command boolean enabled j button button new j button j meter utils get res string res name button set mnemonic mnemonic button set action command command button set enabled enabled button add action listener this return button jbutton createbutton resname jbutton jbutton jmeterutils getresstring resname setmnemonic setactioncommand setenabled addactionlistener private j panel create button panel boolean table empty table model get row count 0 add button create button add a add command true non nls 1 delete button create button delete d delete command table empty non nls 1 load button create button load l load command true non nls 1 save button create button save s save command table empty non nls 1 button panel j panel button panel new j panel button panel add add button button panel add delete button button panel add load button button panel add save button return button panel jpanel createbuttonpanel tableempty tablemodel getrowcount addbutton createbutton add_command deletebutton createbutton delete_command tableempty loadbutton createbutton load_command savebutton createbutton save_command tableempty jpanel buttonpanel jpanel buttonpanel addbutton buttonpanel deletebutton buttonpanel loadbutton buttonpanel savebutton buttonpanel auth manager manager public inner table model auth manager man manager man authmanager innertablemodel authmanager public inner table model manager new auth manager innertablemodel authmanager public void clear data manager clear fire table data changed cleardata firetabledatachanged public void remove row int row manager remove row removerow public void add new row manager add auth addnewrow addauth public boolean is cell editable int row int column all table cells are editable return true iscelleditable public class get column class int column return get value at 0 column get class getcolumnclass getvalueat getclass required by table model interface public int get row count return manager get auth objects size getrowcount getauthobjects required by table model interface public int get column count return manager get column count getcolumncount getcolumncount required by table model interface public string get column name int column return manager get column name column getcolumnname getcolumnname required by table model interface public object get value at int row int column authorization auth manager get auth object at row switch column case auth manager col url return auth geturl case auth manager col username return auth get user case auth manager col password return auth get pass case auth manager col domain return auth get domain case auth manager col realm return auth get realm default return null getvalueat getauthobjectat authmanager col_url authmanager col_username getuser authmanager col_password getpass authmanager col_domain getdomain authmanager col_realm getrealm public void set value at object value int row int column authorization auth manager get auth object at row log debug setting auth value value switch column case auth manager col url auth seturl string value break case auth manager col username auth set user string value break case auth manager col password auth set pass string value break case auth manager col domain auth set domain string value break case auth manager col realm auth set realm string value break default break setvalueat getauthobjectat authmanager col_url authmanager col_username setuser authmanager col_password setpass authmanager col_domain setdomain authmanager col_realm setrealm public password cell renderer super my border new empty border 1 2 1 2 set opaque true set border my border passwordcellrenderer myborder emptyborder setopaque setborder myborder public component get table cell renderer component j table table object value boolean is selected boolean has focus int row int column set text string value set background is selected has focus table get selection background table get background set foreground is selected has focus table get selection foreground table get foreground set font table get font return this gettablecellrenderercomponent jtable isselected hasfocus settext setbackground isselected hasfocus getselectionbackground getbackground setforeground isselected hasfocus getselectionforeground getforeground setfont getfont todo is this used public sample long data long average long deviation double throughput long median boolean success this null data average deviation median 0 throughput 0 success 0 0 todo is this used public sample long data this null data 0 0 0 0 0 0 false 0 0 public sample string name long data long average long deviation long median long distribution line double throughput long error count boolean success long num long end time this data data this average average this deviation deviation this throughput throughput this success success this median median this distribution line distribution line this label name this error count error count this count num this end time end time this bytes 0 this thread name distributionline errorcount endtime distributionline distributionline errorcount errorcount endtime endtime threadname public sample string name long data long average long deviation long median long distribution line double throughput long error count boolean success long num long end time int bytes this data data this average average this deviation deviation this throughput throughput this success success this median median this distribution line distribution line this label name this error count error count this count num this end time end time this bytes bytes this thread name distributionline errorcount endtime distributionline distributionline errorcount errorcount endtime endtime threadname public sample string name long data long average long deviation long median long distribution line double throughput long error count boolean success long num long end time int bytes string thread name this data data this average average this deviation deviation this throughput throughput this success success this median median this distribution line distribution line this label name this error count error count this count num this end time end time this bytes bytes this thread name thread name distributionline errorcount endtime threadname distributionline distributionline errorcount errorcount endtime endtime threadname threadname public sample this null 0 0 0 0 0 0 0 true 0 0 appears not to be used however it is invoked via the functor class public int get bytes return bytes getbytes return returns the average public long get average return average getaverage return returns the count public long get count return count getcount return returns the data usually elapsed time public long get data return data getdata return returns the deviation public long get deviation return deviation getdeviation return returns the distribution line public long get distribution line return distribution line distributionline getdistributionline distributionline return returns the error public boolean is success return success issuccess return returns the error rate public long get error count return error count errorrate geterrorcount errorcount return returns the label public string get label return label getlabel return returns the thread name public string get thread name return thread name threadname getthreadname threadname return returns the median public long get median return median getmedian return returns the throughput public double get throughput return throughput getthroughput see java lang comparable compare to java lang object public int compare to object o sample oo sample o return count oo count 0 1 count oo count 0 1 compareto compareto return returns the end time public long get end time return end time endtime getendtime endtime return returns the calculated start time assuming data is the elapsed time public long get start time return end time data starttime getstarttime endtime return the start time using the specified format intended for use from functors public string get start time formatted format format return format format new date get start time getstarttimeformatted getstarttime public class wsdl exception extends exception public wsdl exception super wsdlexception wsdlexception param message public wsdl exception string message super message wsdlexception param exception public wsdl exception exception exception super exception get message wsdlexception getmessage private final key store store public default key store string type throws exception this store key store get instance type keystore defaultkeystore keystore getinstance public void load input stream is string pword throws exception store load is pword to char array private key key null x509 certificate certchain null if null is no point checking an empty keystore enumeration aliases store aliases while aliases has more elements this alias string aliases next element if store is key entry alias key private key store get key alias pword to char array certificate chain store get certificate chain alias certchain new x509 certificate chain length for int i 0 i chain length i certchain i x509 certificate chain i break if null key throw new exception no key found if null certchain throw new exception no certificate chain found this key key this cert chain certchain inputstream tochararray privatekey _key x509certificate _certchain hasmoreelements nextelement iskeyentry _key privatekey getkey tochararray getcertificatechain _certchain x509certificate _certchain x509certificate _key _certchain _key certchain _certchain public final x509 certificate get certificate chain return this cert chain x509certificate getcertificatechain certchain public final private key get private key return this key privatekey getprivatekey public final string get alias return this alias getalias public worker impl super workerimpl public int get request processing time return this request processing time getrequestprocessingtime requestprocessingtime public void set request processing time int value this request processing time value setrequestprocessingtime requestprocessingtime public long get request bytes sent return this request bytes sent getrequestbytessent requestbytessent public void set request bytes sent long value this request bytes sent value setrequestbytessent requestbytessent public string get current query string return this current query string getcurrentquerystring currentquerystring public void set current query string string value this current query string value setcurrentquerystring currentquerystring public string get remote addr return this remote addr getremoteaddr remoteaddr public void set remote addr string value this remote addr value setremoteaddr remoteaddr public string get current uri return this current uri getcurrenturi currenturi public void set current uri string value this current uri value setcurrenturi currenturi public string get stage return this stage getstage public void set stage string value this stage value setstage public string get virtual host return this virtual host getvirtualhost virtualhost public void set virtual host string value this virtual host value setvirtualhost virtualhost public string get protocol return this protocol getprotocol public void set protocol string value this protocol value setprotocol public long get request bytes received return this request bytes received getrequestbytesreceived requestbytesreceived public void set request bytes received long value this request bytes received value setrequestbytesreceived requestbytesreceived public string get method return this method getmethod public void set method string value this method value setmethod public class test functor users extends j meter test case public test functor users string arg0 super arg0 testfunctorusers jmetertestcase testfunctorusers public void test summary report throws exception assert true summary report functor summary report test functors testsummaryreport asserttrue summaryreport summaryreport testfunctors public void test table visualizer throws exception assert true table visualizer functor table visualizer test functors testtablevisualizer asserttrue tablevisualizer tablevisualizer testfunctors public void test stat graph visualizer throws exception assert true stat graph visualizer functor stat graph visualizer test functors teststatgraphvisualizer asserttrue statgraphvisualizer statgraphvisualizer testfunctors public void test stat visualizer throws exception assert true stat visualizer functor stat visualizer test functors teststatvisualizer asserttrue statvisualizer statvisualizer testfunctors public void test arguments panel throws exception assert true arguments panel functor arguments panel test functors testargumentspanel asserttrue argumentspanel argumentspanel testfunctors public void testhttp arguments panel throws exception assert true http arguments panel functor http arguments panel test functors testhttpargumentspanel asserttrue httpargumentspanel httpargumentspanel testfunctors public void testldap arguments panel throws exception assert true ldap arguments panel functor ldap arguments panel test functors testldapargumentspanel asserttrue ldapargumentspanel ldapargumentspanel testfunctors the method is responsible for taking a status object and calculating an int value from 1 to 100 we use a combination of free memory and free threads the current factor is 50 50 p param stat return calculated load value public static int calculate load status stat if stat null equation for calculating the weight w int 33 used max long tot mem stat get jvm get memory get total long free mem stat get jvm get memory get free long used mem tot mem free mem double memdiv double used mem double tot mem double mem weight default memory factor memdiv changed the logic for bea weblogic in the case a user uses tomcat s status servlet without any modifications weblogic will return nothing for the connector therefore we need to check the size of the list peter 12 22 04 double thread weight 0 if stat get connector size 0 connector cntr fetch connector stat int max thread cntr get thread info get max threads int cur thread cntr get thread info get current threads busy double thdiv double cur thread double max thread thread weight default thread factor thdiv return int mem weight thread weight else return 0 calculateload totmem getjvm getmemory gettotal freemem getjvm getmemory getfree usedmem totmem freemem usedmem totmem memweight default_memory_factor threadweight getconnector fetchconnector maxthread getthreadinfo getmaxthreads curthread getthreadinfo getcurrentthreadsbusy curthread maxthread threadweight default_thread_factor memweight threadweight method should calculate if the server is dead active warning or healthy we do this by looking at the current busy threads ol li free gt spare is healthy li free lt spare is active li busy threads gt 75 is warning li none of the above is dead ol param stat return integer representing the status public static int calculate status status stat if stat null stat get connector size 0 connector cntr fetch connector stat int max cntr get thread info get max threads int current cntr get thread info get current threads busy int spare cntr get thread info get max spare threads double per double current double max if per warning per return warning else if per active per per warning per return active else if per active per per healthy per return healthy else return dead else return dead calculatestatus getconnector fetchconnector getthreadinfo getmaxthreads getthreadinfo getcurrentthreadsbusy getthreadinfo getmaxsparethreads warning_per active_per warning_per active_per healthy_per method will calculate the memory load used max load the load value is an integer between 1 and 100 it is the percent memory used changed this to be more like other system monitors peter lin 2 11 05 param stat return memory load public static int calculate memory load status stat double load 0 if stat null double total stat get jvm get memory get total double free stat get jvm get memory get free double used total free load used total return int load 100 calculatememoryload getjvm getmemory gettotal getjvm getmemory getfree method will calculate the thread load busy max load the value is an integer between 1 and 100 it is the percent busy param stat return thread load public static int calculate thread load status stat int load 0 if stat null stat get connector size 0 connector cntr fetch connector stat double max cntr get thread info get max threads double current cntr get thread info get current threads busy load int current max 100 return load calculatethreadload getconnector fetchconnector getthreadinfo getmaxthreads getthreadinfo getcurrentthreadsbusy method to get connector to use for calculate server status param stat return connector private static connector fetch connector status stat connector cntr null string connector prefix stat get connector prefix if connector prefix null connector prefix length 0 loop to fetch desired connector for int i 0 i stat get connector size i cntr connector stat get connector get i if cntr get name starts with connector prefix return cntr default get first connector cntr connector stat get connector get 0 return cntr fetchconnector connectorprefix getconnectorprefix connectorprefix connectorprefix getconnector getconnector getname startswith connectorprefix getconnector private remote sample listener listener public hold sample sender log warn constructor only intended for use in testing non nls 1 remotesamplelistener holdsamplesender hold sample sender remote sample listener listener log info using sample store for this test run this listener listener holdsamplesender remotesamplelistener public void test ended log info test ended try synchronized sample store iterator i sample store iterator while i has next sample event se sample event i next listener sample occurred se listener test ended sample store null catch throwable ex log warn test ended ex testended samplestore samplestore hasnext sampleevent sampleevent sampleoccurred testended samplestore testended public void test ended string host log info test ended on host should this be debug try iterator i sample store iterator while i has next sample event se sample event i next listener sample occurred se listener test ended host sample store null catch throwable ex log error test ended host ex testended samplestore hasnext sampleevent sampleevent sampleoccurred testended samplestore testended public void sample occurred sample event e log debug sample occurred synchronized sample store sample store add e sampleoccurred sampleevent samplestore samplestore non instantiable private http client default parameters httpclientdefaultparameters public static void load string file http params params log info reading httpclient parameters from file file f new file file input stream is null properties props new properties try is new file input stream f props load is iterator pi props entry set iterator while pi has next map entry me map entry pi next string key string me get key string value string me get value int type sep key index of non nls 1 try if type sep 0 string type key substring type sep 1 get past separator string name key substring 0 type sep log info defining name as value type if type equals integer params set parameter name integer value of value else if type equals long params set parameter name long value of value else if type equals boolean params set parameter name boolean value of value else if type equals http version params set parameter name http version parse http value else log warn unexpected type type else log info defining key as value params set parameter key value catch number format exception e log error error in property key value e to string catch protocol exception e log error error in property key value e to string catch file not found exception e log error problem loading properties e to string catch io exception e log error problem loading properties e to string finally j orphan utils close quietly is httpparams inputstream fileinputstream entryset hasnext getkey getvalue typesep indexof typesep typesep typesep setparameter valueof setparameter valueof setparameter valueof httpversion setparameter httpversion setparameter numberformatexception tostring protocolexception tostring filenotfoundexception tostring ioexception tostring jorphanutils closequietly private transient collection saved value public collection property string name collection value super name this value normalize list value savedvalue collectionproperty normalizelist public collection property super value new array list collectionproperty arraylist public boolean equals object o if o instanceof collection property if value null return value equals j meter property o get object value return false collectionproperty jmeterproperty getobjectvalue public int hash code return value null 0 value hash code hashcode hashcode public void remove string prop property iterator iter iterator while iter has next if iter next get name equals prop iter remove propertyiterator hasnext getname public void set int index string prop if value instanceof list list value set index new string property prop prop stringproperty public void set int index j meter property prop if value instanceof list list value set index prop jmeterproperty public j meter property get int row if value instanceof list return j meter property list value get row return null jmeterproperty jmeterproperty public void remove int index if value instanceof list list value remove index public void set object value object v if v instanceof collection set collection collection v setobjectvalue setcollection public property iterator iterator return get iterator value propertyiterator getiterator see j meter property get string value public string get string value return value to string jmeterproperty getstringvalue getstringvalue tostring see j meter property get object value public object get object value return value jmeterproperty getobjectvalue getobjectvalue public int size return value size public object clone collection property prop collection property super clone prop value clone collection return prop collectionproperty collectionproperty clonecollection private collection clone collection try collection new col collection value get class new instance property iterator iter iterator while iter has next new col add iter next clone return new col catch exception e log error couldn t clone collection e return value clonecollection newcol getclass newinstance propertyiterator hasnext newcol newcol public void set collection collection coll value normalize list coll setcollection normalizelist public void clear value clear easy way to add properties to the list param prop public void add property j meter property prop value add prop addproperty jmeterproperty public void add item object item add property convert object item additem addproperty convertobject figures out what kind of properties this collection is holding and returns the class type see abstract property get property type protected class get property type if value size 0 return value iterator next get class return null property class abstractproperty getpropertytype getpropertytype getclass nullproperty public void recover running version test element owner if saved value null value saved value recover running version of sub elements owner recoverrunningversion testelement savedvalue savedvalue recoverrunningversionofsubelements public void set running version boolean running super set running version running if running saved value value else saved value null setrunningversion setrunningversion savedvalue savedvalue constructor for the save object public report save reportsave gets the action names attribute of the save object return the action names value public set get action names return commands actionnames actionnames getactionnames public void do action action event e throws illegal user action exception hash tree sub tree null if commands contains e get action command throw new illegal user action exception invalid user command e get action command if e get action command equals save as sub tree report gui package get instance get current sub tree else sub tree report gui package get instance get tree model get report plan string update file report gui package get instance get report plan file if save equals e get action command update file null j file chooser chooser report file dialoger prompt to save file report gui package get instance get tree listener get current node get name jmr if chooser null return update file chooser get selected file get absolute path if e get action command equals save as report gui package get instance set report plan file update file todo doesn t putting this here mark the tree as saved even though a failure may occur later report action router get instance do action now new action event sub tree e getid report check dirty sub tree saved try convert sub tree sub tree catch exception err file output stream ostream null try ostream new file output stream update file if save service is save test plan format20 old save service save sub tree sub tree ostream log info save sub tree else save service save tree sub tree ostream log info save tree catch throwable ex report gui package get instance set report plan file null log error ex throw new illegal user action exception couldn t save test plan to file update file finally j orphan utils close quietly ostream doaction actionevent illegaluseractionexception hashtree subtree getactioncommand illegaluseractionexception getactioncommand getactioncommand save_as subtree reportguipackage getinstance getcurrentsubtree subtree reportguipackage getinstance gettreemodel getreportplan updatefile reportguipackage getinstance getreportplanfile getactioncommand updatefile jfilechooser reportfiledialoger prompttosavefile reportguipackage getinstance gettreelistener getcurrentnode getname updatefile getselectedfile getabsolutepath getactioncommand save_as reportguipackage getinstance setreportplanfile updatefile reportactionrouter getinstance doactionnow actionevent subtree reportcheckdirty sub_tree_saved convertsubtree subtree fileoutputstream fileoutputstream updatefile saveservice issavetestplanformat20 oldsaveservice savesubtree subtree savesubtree saveservice savetree subtree savetree reportguipackage getinstance setreportplanfile illegaluseractionexception updatefile jorphanutils closequietly private void convert sub tree hash tree tree iterator iter new linked list tree list iterator while iter has next report tree node item report tree node iter next convert sub tree tree get tree item test element test element item get test element tree replace item test element convertsubtree hashtree linkedlist hasnext reporttreenode reporttreenode convertsubtree gettree testelement testelement gettestelement testelement create a new name panel with the default name public comment panel init namepanel commentpanel initialize the gui components and layout private void init set layout new border layout 5 0 comment field new j text area j label comment label new j label j meter utils get res string testplan comments non nls 1 comment label set label for comment field j panel comment panel new j panel comment panel set layout new border layout 0 5 comment panel add comment label border layout west comment panel add comment field border layout center add comment panel setlayout borderlayout commentfield jtextarea jlabel commentlabel jlabel jmeterutils getresstring testplan_comments commentlabel setlabelfor commentfield jpanel commentpanel jpanel commentpanel setlayout borderlayout commentpanel commentlabel borderlayout commentpanel commentfield borderlayout commentpanel public void set text string comment this comment field set text comment settext commentfield settext public string get text return this comment field get text gettext commentfield gettext public void clear gui comment field set text non nls 1 cleargui commentfield settext public static final string report bar chart url report chart bar chart url public bar chart super report_bar_chart_url reportchart barchart public string geturl return get property as string report bar chart url getpropertyasstring report_bar_chart_url public void seturl string url set property report bar chart url url setproperty report_bar_chart_url convert the data from sampling stat calculator to double array of array param data return data values public double convert to double list data double dataset new double 1 data size iterator itr data iterator for int idx 0 idx data size idx sampling stat calculator stat sampling stat calculator data get idx dataset 0 idx get value stat return dataset samplingstatcalculator converttodouble samplingstatcalculator samplingstatcalculator getvalue public j component render chart list data array list dset new array list array list xlabels new array list iterator itr data iterator while itr has next data set item data set itr next sampling stat calculator ss item get statistics this geturl if ss null we add the entry dset add ss if getx label equals x data filename label xlabels add item get data source name else xlabels add item get month day year date double dbset convert to double dset return render graphics dbset string xlabels to array new string xlabels size jcomponent renderchart arraylist arraylist arraylist arraylist hasnext dataset dataset samplingstatcalculator getstatistics getxlabel x_data_filename_label getdatasourcename getmonthdayyeardate converttodouble rendergraphics toarray public j component render graphics double data string x axis labels axis graph panel new axis graph panel set title this get title panel set data data panel setx axis labels x axis labels panel sety axis labels this gety label panel setx axis title this get formattedx axis panel sety axis title this gety axis we should make this configurable eventually int width get width int height get height panel set preferred size new dimension width height panel set size new dimension width height panel set width width panel set height width set buffered image new buffered image width height buffered image type int rgb panel paint component this get buffered image create graphics return panel jcomponent rendergraphics xaxislabels axisgraph axisgraph settitle gettitle setdata setxaxislabels xaxislabels setyaxislabels getylabel setxaxistitle getformattedxaxis setyaxistitle getyaxis getwidth getheight setpreferredsize setsize setwidth setheight setbufferedimage bufferedimage bufferedimage type_int_rgb paintcomponent getbufferedimage creategraphics public abstract report writer super abstractreportwriter subclasses need to implement this method and provide the necessary logic to produce a report summary object and write the report reportsummary the method simply returns the target directory and doesn t validate it the abstract class expects some other class will validate the target directory public string get target directory return get property as string target directory gettargetdirectory getpropertyasstring target_directory set the target directory where the report should be saved public void set target directory string directory set property target directory directory settargetdirectory setproperty target_directory public void make directory file output new file get target directory if output exists output is directory output mkdir makedirectory gettargetdirectory isdirectory if the target output directory already exists archive it public void archive directory file output new file get target directory if output exists output is directory if the directory already exists and is a directory we just renamed to archive date output rename to new file archive get day string archivedirectory gettargetdirectory isdirectory renameto getdaystring return the day in yyyymmdd format return the date public string get day string calendar today calendar get instance string year string value of today get calendar year string month string value of today get calendar month string day string value of today get calendar date return year month day getdaystring getinstance valueof valueof valueof public file row col container string file string delim throws io exception file not found exception log debug frcc file delim file name file delimiter delim next row 0 file data new array list load filerowcolcontainer ioexception filenotfoundexception filename nextrow filedata arraylist public file row col container string file throws io exception file not found exception log debug frcc file delimiter file name file delimiter delimiter next row 0 file data new array list load filerowcolcontainer ioexception filenotfoundexception filename nextrow filedata arraylist private void load throws io exception file not found exception buffered reader my bread null try file reader fis new file reader file name my bread new buffered reader fis string line my bread read line n b stop reading the file if we get a blank line this allows for trailing comments in the file while line null line length 0 file data add split line line delimiter line my bread read line catch file not found exception e file data clear log warn e to string throw e catch io exception e file data clear log warn e to string throw e finally if my bread null my bread close ioexception filenotfoundexception bufferedreader mybread filereader filereader filename mybread bufferedreader mybread readline filedata splitline mybread readline filenotfoundexception filedata tostring ioexception filedata tostring mybread mybread get the string for the column from the current row param row row number from 0 param col column number from 0 return the string empty if out of bounds throws index out of bounds exception if the column number is out of bounds public string get column int row int col throws index out of bounds exception string col data col data string array list file data get row get col log debug file name row col col data return col data indexoutofboundsexception getcolumn indexoutofboundsexception coldata coldata arraylist filedata filename coldata coldata returns the next row to the caller and updates it allowing for wrap round return the first free unread row public int next row int row next row next row if next row file data size 0 based next row 0 log debug row row return row nextrow nextrow nextrow nextrow filedata nextrow splits the line according to the specified delimiter return an array list of strings containing one element for each value in the line private static array list split line string the line string delim array list result new array list string tokenizer tokener new string tokenizer the line delim true the beginning of the line is a delimiter so that a b c returns a b c boolean last was delim true while tokener has more tokens string token tokener next token if token equals delim if last was delim two delimiters in a row add an empty string result add last was delim true else last was delim false result add token if last was delim catch the trailing delimiter result add non nls 1 return result arraylist arraylist splitline theline arraylist arraylist stringtokenizer stringtokenizer theline lastwasdelim hasmoretokens nexttoken lastwasdelim lastwasdelim lastwasdelim lastwasdelim return the file name for this class public string get file name return file name getfilename filename return returns the delimiter final string get delimiter return delimiter getdelimiter added to support external testing public int get size return file data size getsize filedata private j text field switch value public switch controller gui init jtextfield switchvalue switchcontrollergui public test element create test element switch controller ic new switch controller modify test element ic return ic testelement createtestelement switchcontroller switchcontroller modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element ic configure test element ic switch controller ic set selection switch value get text testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement switchcontroller setselection switchvalue gettext implements j metergui component clear gui public void clear gui super clear gui switch value set text non nls 1 jmeterguicomponent cleargui cleargui cleargui switchvalue settext public void configure test element el super configure el switch value set text switch controller el get selection testelement switchvalue settext switchcontroller getselection public string get label resource return switch controller title non nls 1 getlabelresource switch_controller_title private void init set layout new border layout 0 5 set border make border add make title panel border layout north j panel main panel new j panel new border layout main panel add create switch panel border layout north add main panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout jpanel mainpanel jpanel borderlayout mainpanel createswitchpanel borderlayout mainpanel borderlayout private j panel create switch panel j panel switch panel new j panel new border layout 5 0 j label selection label new j label j meter utils get res string switch label switch value new j text field non nls 1 selection label set label for switch value switch panel add selection label border layout west switch panel add switch value border layout center return switch panel jpanel createswitchpanel jpanel switchpanel jpanel borderlayout jlabel selectionlabel jlabel jmeterutils getresstring switch_label switchvalue jtextfield selectionlabel setlabelfor switchvalue switchpanel selectionlabel borderlayout switchpanel switchvalue borderlayout switchpanel constructor for the file panel object public file list panel title non nls 1 init filepanel filelistpanel public file list panel string title this title title init filelistpanel public file list panel string title string filetype this title title this filetype filetype init filelistpanel constructor for the file panel object public file list panel change listener l string title this title title init listeners add l filepanel filelistpanel changelistener public void add change listener change listener l listeners add l addchangelistener changelistener private void init this set layout new border layout 0 5 set border border factory create empty border 5 0 5 5 j label jtitle new j label title horizontal panel buttons new horizontal panel buttons add jtitle buttons add browse buttons add delete buttons add clear add buttons border layout north this initialize table model files new j table table model files set selection mode list selection model multiple interval selection files revalidate j scroll pane scrollpane new j scroll pane files scrollpane set preferred size new dimension 100 80 add scrollpane border layout center browse set action command action browse non nls 1 browse add action listener this clear add action listener this delete add action listener this this set preferred size new dimension 400 150 setlayout borderlayout setborder borderfactory createemptyborder jlabel jlabel horizontalpanel horizontalpanel borderlayout initializetablemodel jtable tablemodel setselectionmode listselectionmodel multiple_interval_selection jscrollpane jscrollpane setpreferredsize borderlayout setactioncommand action_browse addactionlistener addactionlistener addactionlistener setpreferredsize if the gui needs to enable disable the file panel call the method param enable public void enable file boolean enable browse set enabled enable files set enabled false filepanel enablefile setenabled setenabled add a single file to the table param f public void add filename string f table model add row f addfilename tablemodel addrow clear the files from the table public void clear files table model clear data clearfiles tablemodel cleardata public void set files string files this clear files for int idx 0 idx files length idx add filename files idx setfiles clearfiles addfilename public string get files string files new string table model get row count for int idx 0 idx files length idx files idx string table model get value at idx 0 return files getfiles _files tablemodel getrowcount _files _files tablemodel getvalueat _files protected void delete file if a table cell is being edited we must cancel the editing before deleting the row int row selected files get selected row if row selected 0 table model remove row row selected table model fire table data changed deletefile rowselected getselectedrow rowselected tablemodel removerow rowselected tablemodel firetabledatachanged private void fire file changed iterator iter listeners iterator while iter has next change listener iter next state changed new change event this firefilechanged hasnext changelistener statechanged changeevent protected void initialize table model table model new object table model new string j meter utils get res string label library new functor 0 new functor 0 i e bypass the functors new class string class initializetablemodel tablemodel objecttablemodel jmeterutils getresstring label_library public void action performed action event e if e get source clear this clear files else if e get action command equals action browse j file chooser chooser new j file chooser string start j meter utils get prop default user dir non nls 1 non nls 2 chooser set current directory new file start chooser set file filter new j meter file filter new string filetype chooser set file selection mode j file chooser files and directories chooser set multi selection enabled true chooser show open dialog gui package get instance get main frame file cfiles chooser get selected files if cfiles null for int idx 0 idx cfiles length idx this add filename cfiles idx get path fire file changed else if e get source delete this delete file else fire file changed actionperformed actionevent getsource clearfiles getactioncommand action_browse jfilechooser jfilechooser jmeterutils getpropdefault setcurrentdirectory setfilefilter jmeterfilefilter setfileselectionmode jfilechooser files_and_directories setmultiselectionenabled showopendialog guipackage getinstance getmainframe getselectedfiles addfilename getpath firefilechanged getsource deletefile firefilechanged constructor for the save object public save graphics savegraphics gets the action names attribute of the save object return the action names value public set get action names return commands actionnames actionnames getactionnames public void do action action event e throws illegal user action exception j metergui component component null j component comp null if commands contains e get action command throw new illegal user action exception invalid user command e get action command if e get action command equals action names save graphics component gui package get instance get current gui get the j component from the visualizer if component instanceof printable comp printable component get printable component save image comp if e get action command equals action names save graphics all component gui package get instance get current gui comp j component component get root pane save image comp doaction actionevent illegaluseractionexception jmeterguicomponent jcomponent getactioncommand illegaluseractionexception getactioncommand getactioncommand actionnames save_graphics guipackage getinstance getcurrentgui jcomponent getprintablecomponent saveimage getactioncommand actionnames save_graphics_all guipackage getinstance getcurrentgui jcomponent getrootpane saveimage private void save image j component comp string filename j file chooser chooser file dialoger prompt to save file gui package get instance get tree listener get current node get name extensions if chooser null return get the string given from the choose and check the file extension filename chooser get selected file get absolute path if filename null file f new file filename if f exists int response j option pane show confirm dialog gui package get instance get main frame j meter utils get res string save overwrite existing file non nls 1 j meter utils get res string save non nls 1 j option pane yes no option j option pane question message if response j option pane closed option response j option pane no option return do not save user does not want to overwrite save graphics service save new save graphics service string ext filename substring filename length 4 string name filename substring 0 filename length 4 if ext equals save graphics service png extension save savej component name save graphics service png comp else if ext equals save graphics service tiff extension save savej component name save graphics service tiff comp else save savej component filename save graphics service png comp saveimage jcomponent jfilechooser filedialoger prompttosavefile guipackage getinstance gettreelistener getcurrentnode getname getselectedfile getabsolutepath joptionpane showconfirmdialog guipackage getinstance getmainframe jmeterutils getresstring save_overwrite_existing_file jmeterutils getresstring joptionpane yes_no_option joptionpane question_message joptionpane closed_option joptionpane no_option savegraphicsservice savegraphicsservice savegraphicsservice png_extension savejcomponent savegraphicsservice savegraphicsservice tiff_extension savejcomponent savegraphicsservice savejcomponent savegraphicsservice private static final string init file beanshell listener init non nls 1 protected string get init file property return init file init_file getinitfileproperty init_file public void sample occurred sample event se final bean shell interpreter bsh interpreter get bean shell interpreter if bsh interpreter null log error bean shell not found return j meter context jmctx j meter context service get context j meter variables vars jmctx get variables sample result samp se get result try add variables for access to context and variables bsh interpreter set ctx jmctx non nls 1 bsh interpreter set vars vars non nls 1 bsh interpreter set sample event se non nls 1 bsh interpreter set sample result samp non nls 1 process file or script bsh interpreter catch j meter exception e log warn problem in bean shell script e sampleoccurred sampleevent beanshellinterpreter bshinterpreter getbeanshellinterpreter bshinterpreter beanshell jmetercontext jmetercontextservice getcontext jmetervariables getvariables sampleresult getresult bshinterpreter bshinterpreter bshinterpreter sampleevent bshinterpreter sampleresult processfileorscript bshinterpreter jmeterexception beanshell public void sample started sample event e samplestarted sampleevent public void sample stopped sample event e samplestopped sampleevent public void add sample result sample todo auto generated method stub sampleresult public boolean is stats needed by visualizer interface return false isstats public class right align renderer extends default table cell renderer public right align renderer super set horizontal alignment j label right rightalignrenderer defaulttablecellrenderer rightalignrenderer sethorizontalalignment jlabel private static final string inbox inbox non nls 1 public mail reader sampler gui init init gui mailreadersamplergui initgui public string get label resource return mail reader title non nls 1 getlabelresource mail_reader_title public void configure test element element mail reader sampler mrs mail reader sampler element if mrs get server type equals mail reader sampler type pop3 server type box set selected item pop3 label folder box set text inbox else if mrs get server type equals mail reader sampler type pop3s server type box set selected item pop3s label folder box set text inbox else if mrs get server type equals mail reader sampler type imaps server type box set selected item imaps label folder box set text mrs get folder else server type box set selected item imap label folder box set text mrs get folder server box set text mrs get server username box set text mrs get user name password box set text mrs get password if mrs get num messages mail reader sampler all messages all messages button set selected true some messages field set text 0 non nls 1 else some messages button set selected true some messages field set text mrs get num messages string delete box set selected mrs get delete messages store mime message box set selected mrs is store mime message super configure element testelement mailreadersampler mailreadersampler getservertype mailreadersampler type_pop3 servertypebox setselecteditem pop3label folderbox settext getservertype mailreadersampler type_pop3s servertypebox setselecteditem pop3slabel folderbox settext getservertype mailreadersampler type_imaps servertypebox setselecteditem imapslabel folderbox settext getfolder servertypebox setselecteditem imaplabel folderbox settext getfolder serverbox settext getserver usernamebox settext getusername passwordbox settext getpassword getnummessages mailreadersampler all_messages allmessagesbutton setselected somemessagesfield settext somemessagesbutton setselected somemessagesfield settext getnummessagesstring deletebox setselected getdeletemessages storemimemessagebox setselected isstoremimemessage public test element create test element mail reader sampler sampler new mail reader sampler modify test element sampler return sampler testelement createtestelement mailreadersampler mailreadersampler modifytestelement public void modify test element test element te te clear configure test element te mail reader sampler mrs mail reader sampler te final string item string server type box get selected item if item equals pop3 label mrs set server type mail reader sampler type pop3 else if item equals pop3s label mrs set server type mail reader sampler type pop3s else if item equals imaps label mrs set server type mail reader sampler type imaps else mrs set server type mail reader sampler type imap mrs set folder folder box get text mrs set server server box get text mrs set user name username box get text mrs set password password box get text if all messages button is selected mrs set num messages mail reader sampler all messages else mrs set num messages some messages field get text mrs set delete messages delete box is selected mrs set store mime message store mime message box is selected modifytestelement testelement configuretestelement mailreadersampler mailreadersampler servertypebox getselecteditem pop3label setservertype mailreadersampler type_pop3 pop3slabel setservertype mailreadersampler type_pop3s imapslabel setservertype mailreadersampler type_imaps setservertype mailreadersampler type_imap setfolder folderbox gettext setserver serverbox gettext setusername usernamebox gettext setpassword passwordbox gettext allmessagesbutton isselected setnummessages mailreadersampler all_messages setnummessages somemessagesfield gettext setdeletemessages deletebox isselected setstoremimemessage storemimemessagebox isselected private void init set layout new vertical layout 5 vertical layout both vertical layout top set border make border add make title panel j panel server type panel new j panel server type panel add new j label server type label default combo box model server type model new default combo box model server type model add element pop3 label server type model add element pop3s label server type model add element imap label server type model add element imaps label server type box new j combo box server type model server type box add action listener new action listener public void action performed action event e final string item string server type box get selected item if item equals pop3 label item equals pop3s label folder label set enabled false folder box set text inbox folder box set enabled false else folder label set enabled true folder box set enabled true server type panel add server type box add server type panel j panel server panel new j panel server panel add new j label server label server box new j text field 20 server panel add server box add server panel j panel account name panel new j panel account name panel add new j label account label username box new j text field 20 account name panel add username box add account name panel j panel account pass panel new j panel account pass panel add new j label password label password box new j text field 20 account pass panel add password box add account pass panel j panel folder panel new j panel folder label new j label folder label folder box new j text field inbox 10 folder panel add folder label folder panel add folder box add folder panel horizontal panel num messages panel new horizontal panel num messages panel add new j label num messages label button group nmbg new button group all messages button new j radio button all messages label all messages button add change listener new change listener public void state changed change event e if all messages button is selected some messages field set enabled false some messages button new j radio button some messages button add change listener new change listener public void state changed change event e if some messages button is selected some messages field set enabled true nmbg add all messages button nmbg add some messages button some messages field new j text field 5 all messages button set selected true num messages panel add all messages button num messages panel add some messages button num messages panel add some messages field add num messages panel delete box new j check box delete label add delete box store mime message box new j check box storemime add store mime message box setlayout verticallayout verticallayout verticallayout setborder makeborder maketitlepanel jpanel servertypepanel jpanel servertypepanel jlabel servertypelabel defaultcomboboxmodel servertypemodel defaultcomboboxmodel servertypemodel addelement pop3label servertypemodel addelement pop3slabel servertypemodel addelement imaplabel servertypemodel addelement imapslabel servertypebox jcombobox servertypemodel servertypebox addactionlistener actionlistener actionperformed actionevent servertypebox getselecteditem pop3label pop3slabel folderlabel setenabled folderbox settext folderbox setenabled folderlabel setenabled folderbox setenabled servertypepanel servertypebox servertypepanel jpanel serverpanel jpanel serverpanel jlabel serverlabel serverbox jtextfield serverpanel serverbox serverpanel jpanel accountnamepanel jpanel accountnamepanel jlabel accountlabel usernamebox jtextfield accountnamepanel usernamebox accountnamepanel jpanel accountpasspanel jpanel accountpasspanel jlabel passwordlabel passwordbox jtextfield accountpasspanel passwordbox accountpasspanel jpanel folderpanel jpanel folderlabel jlabel folderlabel folderbox jtextfield folderpanel folderlabel folderpanel folderbox folderpanel horizontalpanel nummessagespanel horizontalpanel nummessagespanel jlabel nummessageslabel buttongroup buttongroup allmessagesbutton jradiobutton allmessageslabel allmessagesbutton addchangelistener changelistener statechanged changeevent allmessagesbutton isselected somemessagesfield setenabled somemessagesbutton jradiobutton somemessagesbutton addchangelistener changelistener statechanged changeevent somemessagesbutton isselected somemessagesfield setenabled allmessagesbutton somemessagesbutton somemessagesfield jtextfield allmessagesbutton setselected nummessagespanel allmessagesbutton nummessagespanel somemessagesbutton nummessagespanel somemessagesfield nummessagespanel deletebox jcheckbox deletelabel deletebox storemimemessagebox jcheckbox storemimemessagebox server type box add action listener new action listener public void action performed action event e final string item string server type box get selected item if item equals pop3 label item equals pop3s label folder label set enabled false folder box set text inbox folder box set enabled false else folder label set enabled true folder box set enabled true servertypebox addactionlistener actionlistener actionperformed actionevent servertypebox getselecteditem pop3label pop3slabel folderlabel setenabled folderbox settext folderbox setenabled folderlabel setenabled folderbox setenabled all messages button add change listener new change listener public void state changed change event e if all messages button is selected some messages field set enabled false allmessagesbutton addchangelistener changelistener statechanged changeevent allmessagesbutton isselected somemessagesfield setenabled some messages button add change listener new change listener public void state changed change event e if some messages button is selected some messages field set enabled true somemessagesbutton addchangelistener changelistener statechanged changeevent somemessagesbutton isselected somemessagesfield setenabled public void clear gui super clear gui init gui cleargui cleargui initgui private void init gui all messages button set selected true some messages button set selected false some messages field set text 0 delete box set selected false store mime message box set selected false folder box set text inbox server type box set selected index 0 password box set text non nls 1 server box set text non nls 1 username box set text non nls 1 initgui allmessagesbutton setselected somemessagesbutton setselected somemessagesfield settext deletebox setselected storemimemessagebox setselected folderbox settext servertypebox setselectedindex passwordbox settext serverbox settext usernamebox settext private remote sample listener listener public standard sample sender log warn constructor only intended for use in testing non nls 1 remotesamplelistener standardsamplesender standard sample sender remote sample listener listener log info using standard remote sampler for this test run this listener listener standardsamplesender remotesamplelistener public void test ended log info test ended try listener test ended catch remote exception ex log warn test ended ex testended testended remoteexception testended public void test ended string host log info test ended on host should this be debug try listener test ended host catch remote exception ex log warn test ended host ex testended testended remoteexception testended public void sample occurred sample event e log debug sample occurred try listener sample occurred e catch remote exception err if err get cause instanceof java net connect exception throw new j meter error could not return sample err log error sample occurred err sampleoccurred sampleevent sampleoccurred remoteexception getcause connectexception jmetererror sampleoccurred creates an instance of search by class however without setting the class to search for it will be a useless object public search by class searchbyclass searchbyclass creates an instance of search by class and sets the class to be searched for param search class public search by class class search class this search class search class searchbyclass searchclass searchbyclass searchclass searchclass searchclass after traversing the hash tree call this method to get a collection of the nodes that were found return collection all found nodes of the requested type public collection get search results return objects of class hashtree getsearchresults objectsofclass given a specific found node this method will return the sub tree of that node param root the node for which the sub tree is requested return hash tree public hash tree get sub tree object root return hash tree sub trees get root hashtree hashtree getsubtree hashtree subtrees public void add node object node hash tree sub tree if search class is assignable from node get class objects of class add node listed hash tree tree new listed hash tree node tree set node sub tree sub trees put node tree addnode hashtree subtree searchclass isassignablefrom getclass objectsofclass listedhashtree listedhashtree subtree subtrees public void subtract node subtractnode public void process path processpath public static final string default policy cookie policy browser compatibility public cookie manager clear cookies ensure that there is always a collection available default_policy cookiepolicy browser_compatibility cookiemanager clearcookies ensure that the initial cookies are copied to the per thread instances public object clone cookie manager clone cookie manager super clone clone initial cookies initial cookies clone cookie spec cookie spec return clone cookiemanager cookiemanager initialcookies initialcookies cookiespec cookiespec public string get policy return get property as string policy default policy getpolicy getpropertyasstring default_policy public void set cookie policy string policy set property policy policy default policy setcookiepolicy setproperty default_policy public collection property get cookies return collection property get property cookies collectionproperty getcookies collectionproperty getproperty public int get cookie count used by gui return get cookies size getcookiecount getcookies public boolean get clear each iteration return get property as boolean clear getcleareachiteration getpropertyasboolean public void set clear each iteration boolean clear set property new boolean property clear clear setcleareachiteration setproperty booleanproperty save the static cookie data to a file cookies are only taken from the gui runtime cookies are not included public void save string auth file throws io exception file file new file auth file if file is absolute file new file system get property user dir non nls 1 file separator auth file print writer writer new print writer new file writer file writer println j meter generated cookie file non nls 1 property iterator cookies get cookies iterator long now system current time millis while cookies has next cookie cook cookie cookies next get object value final long expires millis cook get expires millis if expires millis 0 expires millis now only save unexpired cookies writer println cookie to string cook writer flush writer close authfile ioexception authfile isabsolute getproperty authfile printwriter printwriter filewriter jmeter propertyiterator getcookies currenttimemillis hasnext getobjectvalue expiresmillis getexpiresmillis expiresmillis expiresmillis cookietostring add cookie data from a file public void add file string cookie file throws io exception file file new file cookie file if file is absolute file new file system get property user dir non nls 1 file separator cookie file buffered reader reader null if file can read reader new buffered reader new file reader file else throw new io exception the file you specified cannot be read n b this must agree with the save and cookie to string methods string line try final collection property cookies get cookies while line reader read line null try if line starts with line trim length 0 non nls 1 continue string st j orphan utils split line tab false final int domain 0 final int ignored 1 final int path 2 final int secure 3 final int expires 4 final int name 5 final int value 6 final int fields 7 if st length fields throw new io exception expected fields fields found st length in line if st path length 0 st path non nls 1 boolean secure boolean value of st secure boolean value long expires new long st expires long value if expires long max value expires 0 long max was used to represent a non expiring cookie but that caused problems cookie cookie new cookie st name st value st domain st path secure expires cookies add item cookie catch number format exception e throw new io exception error parsing cookie line n t line n t e finally reader close addfile cookiefile ioexception cookiefile isabsolute getproperty cookiefile bufferedreader canread bufferedreader filereader ioexception cookietostring collectionproperty getcookies readline startswith jorphanutils _domain _ignored _path _secure _expires _name _value _fields _fields ioexception _fields _path _path valueof _secure booleanvalue _expires longvalue max_value _name _value _domain _path additem numberformatexception ioexception private string cookie to string cookie c string buffer sb new string buffer 80 sb append c get domain flag if all machines within a given domain can access the variable from http www cookiecentral com faq 3 5 sb append tab append true sb append tab append c get path sb append tab append j orphan utils boolean tostring c get secure sb append tab append c get expires sb append tab append c get name sb append tab append c get value return sb to string cookietostring stringbuffer stringbuffer getdomain getpath jorphanutils booleantostring getsecure getexpires getname getvalue tostring public void recover running version do nothing the cookie manager has to accept changes recoverrunningversion public void set running version boolean running do nothing the cookie manager has to accept changes setrunningversion add a cookie public void add cookie c string cv c get value string cn c get name remove matching cookies c can t have two matching cookies if delete null cookies null cv cv length 0 if log is debug enabled log debug dropping cookie with null value c to string else if log is debug enabled log debug add cookie to store c to string get cookies add item c if save cookies j meter context context get thread context if context is sampling started context get variables put cookie name prefix cn cv getvalue getname removematchingcookies delete_null_cookies isdebugenabled tostring isdebugenabled tostring getcookies additem save_cookies jmetercontext getthreadcontext issamplingstarted getvariables cookie_name_prefix public void clear super clear clear cookies ensure data is set up ok initially clearcookies remove all the cookies private void clear cookies log debug clear all cookies from store set property new collection property cookies new array list clearcookies setproperty collectionproperty arraylist remove a cookie public void remove int index todo not used by gui get cookies remove index getcookies return the cookie at index i public cookie get int i only used by gui return cookie get cookies get i get object value getcookies getobjectvalue private org apache commons httpclient cookie make cookie cookie jmc long exp jmc get expires millis org apache commons httpclient cookie ret new org apache commons httpclient cookie jmc get domain jmc get name jmc get value jmc get path exp 0 new date exp null use null for no expiry jmc get secure ret set path attribute specified jmc is path specified ret set domain attribute specified jmc is domain specified ret set version jmc get version return ret makecookie getexpiresmillis getdomain getname getvalue getpath getsecure setpathattributespecified ispathspecified setdomainattributespecified isdomainspecified setversion getversion get array of valid http client cookies for the url param url the target url return array of http client cookies public org apache commons httpclient cookie get cookies for url url url collection property jar get cookies org apache commons httpclient cookie cookies new org apache commons httpclient cookie jar size int i 0 for property iterator iter get cookies iterator iter has next cookie jmcookie cookie iter next get object value set to running version to allow function evaluation for the cookie values bug 28715 if allow variable cookies jmcookie set running version true cookies i make cookie jmcookie if allow variable cookies jmcookie set running version false string host url get host string protocol url get protocol int port http sampler base get default port protocol url get port string path url get path boolean secure http sampler base is secure protocol return cookie spec match host port path secure cookies httpclient httpclient getcookiesforurl collectionproperty getcookies propertyiterator getcookies hasnext getobjectvalue allow_variable_cookies setrunningversion makecookie allow_variable_cookies setrunningversion gethost getprotocol httpsamplerbase getdefaultport getport getpath httpsamplerbase issecure cookiespec find cookies applicable to the given url and build the cookie header from them param url url of the request to which the returned header will be added return the value string for the cookie header goes after cookie public string get cookie header forurl url url org apache commons httpclient cookie c get cookies for url url int count c length boolean debug enabled log is debug enabled if debug enabled log debug found count cookies for url to external form if count 0 return null string hdr cookie spec format cookie header c get value if debug enabled log debug cookie hdr return hdr getcookieheaderforurl getcookiesforurl debugenabled isdebugenabled debugenabled toexternalform cookiespec formatcookieheader getvalue debugenabled public void add cookie from header string cookie header url url boolean debug enabled log is debug enabled if debug enabled log debug received cookie cookie header from url to external form string protocol url get protocol string host url get host int port http sampler base get default port protocol url get port string path url get path boolean is secure http sampler base is secure protocol org apache commons httpclient cookie cookies null try cookies cookie spec parse host port path is secure cookie header catch malformed cookie exception e log warn cookie header e get localized message catch illegal argument exception e log warn cookie header e get localized message if cookies null return for int i 0 i cookies length i org apache commons httpclient cookie cookie cookies i try if check cookies cookie spec validate host port path is secure cookie date expiry date cookie get expiry date long exp 0 if expiry date null exp expiry date get time cookie new cookie new cookie cookie get name cookie get value cookie get domain cookie get path cookie get secure exp 1000 cookie is path attribute specified cookie is domain attribute specified store session cookies as well as unexpired ones if exp 0 exp system current time millis new cookie set version cookie get version add new cookie has its own debug log removes matching cookies else remove matching cookies new cookie if debug enabled log debug dropping expired cookie new cookie to string catch malformed cookie exception e this means the cookie was wrong for the url log debug not storing invalid cookie cookie header for url url e get localized message catch illegal argument exception e log warn cookie header e get localized message addcookiefromheader cookieheader debugenabled isdebugenabled debugenabled cookieheader toexternalform getprotocol gethost httpsamplerbase getdefaultport getport getpath issecure httpsamplerbase issecure cookiespec issecure cookieheader malformedcookieexception cookieheader getlocalizedmessage illegalargumentexception cookieheader getlocalizedmessage check_cookies cookiespec issecure expirydate getexpirydate expirydate expirydate gettime newcookie getname getvalue getdomain getpath getsecure ispathattributespecified isdomainattributespecified currenttimemillis newcookie setversion getversion newcookie removematchingcookies newcookie debugenabled newcookie tostring malformedcookieexception cookieheader getlocalizedmessage illegalargumentexception cookieheader getlocalizedmessage check if cookies match i e name path and domain are equal br todo should we compare secure too param a param b return true if cookies match private boolean match cookie a cookie b return a get name equals b get name a get path equals b get path a get domain equals b get domain getname getname getpath getpath getdomain getdomain private void remove matching cookies cookie new cookie scan for any matching cookies property iterator iter get cookies iterator while iter has next cookie cookie cookie iter next get object value if cookie null todo is this possible continue if match cookie new cookie if log is debug enabled log debug new cookie new cookie to string removing matching cookie cookie to string iter remove removematchingcookies newcookie propertyiterator getcookies hasnext getobjectvalue newcookie isdebugenabled newcookie tostring tostring public void test started initial cookies get cookies cookie spec cookie policy get cookie spec get policy if log is debug enabled log debug policy get policy clear get clear each iteration teststarted initialcookies getcookies cookiespec cookiepolicy getcookiespec getpolicy isdebugenabled getpolicy getcleareachiteration public void test ended testended public void test started string host test started teststarted teststarted public void test ended string host testended public void test iteration start loop iteration event event if get clear each iteration log debug initialise cookies from pre defined list no need to call clear set property collection property initial cookies clone testiterationstart loopiterationevent getcleareachiteration setproperty collectionproperty initialcookies public static final string skip suffix file saver skipsuffix non nls 1 private synchronized long next number return sequence number skip_suffix filesaver nextnumber sequencenumber public result saver super log debug thread current thread get name system out println me this get name thread current thread get name resultsaver currentthread getname getname currentthread getname of summariser public result saver string name this set name name resultsaver setname public void clear super clear synchronized this sequence number 0 todo is this the right thing to do sequencenumber saves the sample result and any sub results in files see org apache jmeter samplers sample listener sample occurred org apache jmeter samplers sample event public void sample occurred sample event e process sample e get result new counter samplelistener sampleoccurred sampleevent sampleoccurred sampleevent processsample getresult recurse the whole sub result hierarchy param s sample result param c sample counter private void process sample sample result s counter c save sample s c num sample result sr s get sub results for int i 0 i sr length i process sample sr i c processsample sampleresult savesample sampleresult getsubresults processsample param s sample result to save param num number to append to variable if 0 private void save sample sample result s int num should we save the sample if s is successful if get errors only return else if get success only return string file name make file name s get content type get skip auto number get skip suffix log debug saving s get sample label in file name s set result file name file name associate sample with file name string variable get variable name if variable length 0 if num 0 str builder sb new str builder variable sb append num variable sb to string j meter context service get context get variables put variable file name file out new file file name file output stream pw null try pw new file output stream out pw write s get response data catch file not found exception e1 log error error creating sample file for s get sample label e1 catch io exception e1 log error error saving sample s get sample label e1 finally j orphan utils close quietly pw sampleresult savesample sampleresult issuccessful geterrorsonly getsuccessonly filename makefilename getcontenttype getskipautonumber getskipsuffix getsamplelabel filename setresultfilename filename getvariablename strbuilder strbuilder tostring jmetercontextservice getcontext getvariables filename filename fileoutputstream fileoutputstream getresponsedata filenotfoundexception getsamplelabel ioexception getsamplelabel jorphanutils closequietly return file name composed of fixed prefix a number and a suffix derived from the content type e g content type text html charset iso 8859 1 private string make file name string content type boolean skip auto number boolean skip suffix str builder sb new str builder get filename if skip auto number sb append next number if skip suffix sb append if content type null int i content type index of non nls 1 if i 1 int j content type index of non nls 1 if j 1 sb append content type substring i 1 j else sb append content type substring i 1 else sb append unknown else sb append unknown return sb to string filename contenttype makefilename contenttype skipautonumber skipsuffix strbuilder strbuilder getfilename skipautonumber nextnumber skipsuffix contenttype contenttype indexof contenttype indexof contenttype contenttype tostring see org apache jmeter samplers sample listener sample started org apache jmeter samplers sample event public void sample started sample event e not used samplelistener samplestarted sampleevent samplestarted sampleevent see org apache jmeter samplers sample listener sample stopped org apache jmeter samplers sample event public void sample stopped sample event e not used samplelistener samplestopped sampleevent samplestopped sampleevent private string get filename return get property as string filename getfilename getpropertyasstring private string get variable name return get property as string variable name non nls 1 getvariablename getpropertyasstring variable_name private boolean get errors only return get property as boolean errors only geterrorsonly getpropertyasboolean errors_only private boolean get skip auto number return get property as boolean skip auto number getskipautonumber getpropertyasboolean skip_auto_number private boolean get skip suffix return get property as boolean skip suffix getskipsuffix getpropertyasboolean skip_suffix private boolean get success only return get property as boolean success only getsuccessonly getpropertyasboolean success_only private final boolean is remote skip certain processing for remote tests public pre compiler replacer new value replacer is remote false isremote precompiler valuereplacer isremote public pre compiler boolean remote replacer new value replacer is remote remote precompiler valuereplacer isremote public void add node object node hash tree sub tree if is remote node instanceof result collector try replacer replace values test element node catch invalid variable exception e log error invalid variables e if is remote return if node instanceof test element try replacer replace values test element node catch invalid variable exception e log error invalid variables e if node instanceof test plan test plan node prepare for pre compile a hack to make user defined variables in the testplan element more dynamic map args test plan node get user defined variables replacer set user defined variables args j meter variables vars new j meter variables vars put all args j meter context service get context set variables vars if node instanceof arguments arguments node set running version true map args arguments node get arguments as map replacer add variables args j meter context service get context get variables put all args addnode hashtree subtree isremote resultcollector replacevalues testelement invalidvariableexception isremote testelement replacevalues testelement invalidvariableexception testplan testplan prepareforprecompile testplan getuserdefinedvariables setuserdefinedvariables jmetervariables jmetervariables putall jmetercontextservice getcontext setvariables setrunningversion getargumentsasmap addvariables jmetercontextservice getcontext getvariables putall see hash tree traverser subtract node public void subtract node hashtreetraverser subtractnode subtractnode see hash tree traverser process path public void process path hashtreetraverser processpath processpath private j button delete public property control gui super init jbutton propertycontrolgui public string get label resource return property visualiser title non nls 1 getlabelresource property_visualiser_title public collection get menu categories return arrays as list new string menu factory non test elements getmenucategories aslist menufactory non_test_elements public void action performed action event action string command action get action command if add equals command return if delete equals command return if system equals command set up data return if jmeter equals command set up data return actionperformed actionevent getactioncommand setupdata setupdata public void add sample result sample sampleresult public test element create test element test element el new config test element modify test element el return el testelement createtestelement testelement configtestelement modifytestelement return el public void configure test element element super configure element set up data testelement setupdata private void set up data table model clear data properties p null if system button is selected p system get properties if jmeter button is selected p j meter utils getj meter properties if p null return set s p entry set array list al new array list s collections sort al new comparator public int compare object o1 object o2 string m1 m2 m1 string map entry o1 get key m2 string map entry o2 get key return m1 compare to m2 iterator i al iterator while i has next table model add row i next setupdata tablemodel cleardata systembutton isselected getproperties jmeterbutton isselected jmeterutils getjmeterproperties entryset arraylist arraylist getkey getkey compareto hasnext tablemodel addrow collections sort al new comparator public int compare object o1 object o2 string m1 m2 m1 string map entry o1 get key m2 string map entry o2 get key return m1 compare to m2 getkey getkey compareto public void modify test element test element element configure test element element modifytestelement testelement configuretestelement private component make main panel initialize table model table new j table table model table get table header set default renderer new header as property renderer table set selection mode list selection model single selection return make scroll pane table makemainpanel initializetablemodel jtable tablemodel gettableheader setdefaultrenderer headeraspropertyrenderer setselectionmode listselectionmodel single_selection makescrollpane create a panel containing the title label for the table return a panel containing the title label private component make label panel j panel label panel new j panel new flow layout flow layout center button group bg new button group bg add system button bg add jmeter button jmeter button set selected true system button set action command system jmeter button set action command jmeter system button add action listener this jmeter button add action listener this label panel add system button label panel add jmeter button label panel add table label return label panel makelabelpanel jpanel labelpanel jpanel flowlayout flowlayout buttongroup buttongroup systembutton jmeterbutton jmeterbutton setselected systembutton setactioncommand jmeterbutton setactioncommand systembutton addactionlistener jmeterbutton addactionlistener labelpanel systembutton labelpanel jmeterbutton labelpanel tablelabel labelpanel initialize the components and layout of this component private void init j panel p this set layout new border layout 0 5 set border make border add make title panel border layout north p new j panel p set layout new border layout p add make label panel border layout north p add make main panel border layout center force a minimum table height of 70 pixels p add box create vertical strut 70 border layout west p add make button panel border layout south add p border layout center table revalidate jpanel setlayout borderlayout setborder makeborder maketitlepanel borderlayout jpanel setlayout borderlayout makelabelpanel borderlayout makemainpanel borderlayout createverticalstrut borderlayout makebuttonpanel borderlayout borderlayout private void initialize table model table model new object table model new string column names 0 column names 1 new functor new functor map entry class get key non nls 1 new functor map entry class get value non nls 1 new functor null new functor set name non nls 1 new functor map entry class set value new class object class non nls 1 new class string class string class initializetablemodel tablemodel objecttablemodel column_names_0 column_names_1 getkey getvalue setname setvalue see org apache jmeter report gui action command get action names public set get action names return commands getactionnames getactionnames public void do action action event e report tree listener tree listener report gui package get instance get tree listener report tree node nodes tree listener get selected nodes set copied nodes nodes doaction actionevent reporttreelistener treelistener reportguipackage getinstance gettreelistener reporttreenode treelistener getselectednodes setcopiednodes public static report tree node get copied nodes for int i 0 i copied nodes length i if copied nodes i null return null return clone tree nodes copied nodes reporttreenode getcopiednodes copiednodes copiednodes clonetreenodes copiednodes public static report tree node get copied node if copied node null return null return clone tree node copied node reporttreenode getcopiednode copiednode clonetreenode copiednode public static void set copied node report tree node node copied node clone tree node node setcopiednode reporttreenode copiednode clonetreenode public static report tree node clone tree node report tree node node report tree node tree node report tree node node clone tree node set user object test element node get user object clone clone children tree node node return tree node reporttreenode clonetreenode reporttreenode reporttreenode treenode reporttreenode treenode setuserobject testelement getuserobject clonechildren treenode treenode public static void set copied nodes report tree node nodes copied nodes new report tree node nodes length for int i 0 i nodes length i copied nodes i clone tree node nodes i setcopiednodes reporttreenode copiednodes reporttreenode copiednodes clonetreenode public static report tree node clone tree nodes report tree node nodes report tree node tree nodes new report tree node nodes length for int i 0 i nodes length i tree nodes i clone tree node nodes i return tree nodes reporttreenode clonetreenodes reporttreenode reporttreenode treenodes reporttreenode treenodes clonetreenode treenodes private static void clone children report tree node to report tree node from enumeration enum from from children while enum from has more elements report tree node child report tree node enum from next element report tree node child clone report tree node child clone child clone set user object test element child get user object clone to add child clone clone children report tree node to get last child child clonechildren reporttreenode reporttreenode enumfrom enumfrom hasmoreelements reporttreenode reporttreenode enumfrom nextelement reporttreenode childclone reporttreenode childclone setuserobject testelement getuserobject childclone clonechildren reporttreenode getlastchild used for per thread user numbers private transient thread local per thread random new thread local protected object initial value init return new random get random seed as long threadlocal perthreadrandom threadlocal initialvalue getrandomseedaslong private void init final string min as string get minimum value minimum number utils to long min as string final string max as string get maximum value long maximum number utils to long max as string long rangel maximum minimum 1 this can overflow if minimum maximum log error maximum max as string must be minimum min as string n 0 this is used as an error indicator return if rangel integer max value rangel 0 check for overflow too log warn maximum max as string minimum min as string must be integer max value rangel integer max value n int rangel minasstring getminimumvalue numberutils tolong minasstring maxasstring getmaximumvalue numberutils tolong maxasstring maxasstring minasstring max_value maxasstring minasstring max_value max_value public void iteration start loop iteration event iter event random rand gen null if get per thread rand gen random per thread random get else synchronized this if global random null init global random new random get random seed as long rand gen global random if n 0 return long next rand minimum rand gen next int n cannot use get thread context as we are not cloned per thread j meter variables variables j meter context service get context get variables variables put get variable name format number next rand iterationstart loopiterationevent iterevent randgen getperthread randgen perthreadrandom globalrandom globalrandom getrandomseedaslong randgen globalrandom nextrand randgen nextint getthreadcontext jmetervariables jmetercontextservice getcontext getvariables getvariablename formatnumber nextrand use format to create number if it fails use the default private string format number long value string format get output format if format null format length 0 try decimal format my formatter new decimal format format return my formatter format value catch number format exception ignored catch illegal argument exception ignored return long to string value formatnumber getoutputformat decimalformat myformatter decimalformat myformatter numberformatexception illegalargumentexception tostring return the min value public synchronized string get minimum value return minimum value minvalue getminimumvalue minimumvalue param min value the min value to set public synchronized void set minimum value string min value this minimum value min value minvalue minvalue setminimumvalue minvalue minimumvalue minvalue return the maxvalue public synchronized string get maximum value return maximum value getmaximumvalue maximumvalue param maxvalue the maxvalue to set public synchronized void set maximum value string maxvalue this maximum value maxvalue setmaximumvalue maximumvalue return the variable name public synchronized string get variable name return variable name variablename getvariablename variablename param variable name the variable name to set public synchronized void set variable name string variable name this variable name variable name variablename variablename setvariablename variablename variablename variablename return the random seed public synchronized string get random seed return random seed randomseed getrandomseed randomseed return the random seed as a long private synchronized long get random seed as long long seed 0 if random seed length 0 seed system current time millis else try seed long parse long random seed catch number format exception e seed system current time millis log warn cannot parse seed e get localized message return seed randomseed getrandomseedaslong randomseed currenttimemillis parselong randomseed numberformatexception currenttimemillis getlocalizedmessage param random seed the random seed to set public synchronized void set random seed string random seed this random seed random seed randomseed randomseed setrandomseed randomseed randomseed randomseed return the per thread public synchronized boolean get per thread return per thread perthread getperthread perthread param per thread the per thread to set public synchronized void set per thread boolean per thread this per thread per thread perthread perthread setperthread perthread perthread perthread return the output format public synchronized string get output format return output format outputformat getoutputformat outputformat param output format the output format to set public synchronized void set output format string output format this output format output format outputformat outputformat setoutputformat outputformat outputformat outputformat public proxy control gui super log debug creating proxy control gui init proxycontrolgui proxycontrolgui public test element create test element model make proxy control log debug creating configuring model model modify test element model return model testelement createtestelement makeproxycontrol modifytestelement protected proxy control make proxy control proxy control local new proxy control return local proxycontrol makeproxycontrol proxycontrol proxycontrol modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element el if exclude table is editing bug 42948 exclude table get cell editor stop cell editing if include table is editing bug 42948 include table get cell editor stop cell editing configure test element el if el instanceof proxy control model proxy control el model set port port field get text set include list in proxy control model set exclude list in proxy control model model set capture http headers http headers is selected model set grouping mode grouping mode get selected index model set assertions add assertions is selected model set sampler type name sampler type name get selected index model set sampler redirect automatically sampler redirect automatically is selected model set sampler follow redirects sampler follow redirects is selected model set use keep alive use keep alive is selected model set sampler download images sampler download images is selected model set regex match regex match is selected model set https spoof https spoof is selected model set https spoof match https match get text model set content type include content type include get text model set content type exclude content type exclude get text tree node wrapper nw tree node wrapper target nodes get selected item if nw null model set target null else model set target nw get tree node testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement excludetable isediting excludetable getcelleditor stopcellediting includetable isediting includetable getcelleditor stopcellediting configuretestelement proxycontrol proxycontrol setport portfield gettext setincludelistinproxycontrol setexcludelistinproxycontrol setcapturehttpheaders httpheaders isselected setgroupingmode groupingmode getselectedindex setassertions addassertions isselected setsamplertypename samplertypename getselectedindex setsamplerredirectautomatically samplerredirectautomatically isselected setsamplerfollowredirects samplerfollowredirects isselected setusekeepalive usekeepalive isselected setsamplerdownloadimages samplerdownloadimages isselected setregexmatch regexmatch isselected sethttpsspoof httpsspoof isselected sethttpsspoofmatch httpsmatch gettext setcontenttypeinclude contenttypeinclude gettext setcontenttypeexclude contenttypeexclude gettext treenodewrapper treenodewrapper targetnodes getselecteditem settarget settarget gettreenode protected void set include list in proxy control proxy control element list include list get data list include model include col element set include list include list setincludelistinproxycontrol proxycontrol includelist getdatalist includemodel include_col setincludelist includelist protected void set exclude list in proxy control proxy control element list exclude list get data list exclude model exclude col element set exclude list exclude list setexcludelistinproxycontrol proxycontrol excludelist getdatalist excludemodel exclude_col setexcludelist excludelist private list get data list power table model p model string col name string data array p model get data get column col name list list new linked list for int i 0 i data array length i list add data array i return list getdatalist powertablemodel p_model colname dataarray p_model getdata getcolumn colname linkedlist dataarray dataarray public string get label resource return proxy title non nls 1 getlabelresource proxy_title public collection get menu categories return arrays as list new string menu factory non test elements getmenucategories aslist menufactory non_test_elements public void configure test element element log debug configuring gui with element super configure element model proxy control element port field set text model get port string http headers set selected model get capture http headers grouping mode set selected index model get grouping mode add assertions set selected model get assertions sampler type name set selected index model get sampler type name sampler redirect automatically set selected model get sampler redirect automatically sampler follow redirects set selected model get sampler follow redirects use keep alive set selected model get use keepalive sampler download images set selected model get sampler download images regex match set selected model get regex match https spoof set selected model get https spoof https match set text model get https spoof match content type include set text model get content type include content type exclude set text model get content type exclude reinitialize target combo set up list of potential targets and enable listener populate table include model model get include patterns iterator populate table exclude model model get exclude patterns iterator repaint testelement proxycontrol portfield settext getportstring httpheaders setselected getcapturehttpheaders groupingmode setselectedindex getgroupingmode addassertions setselected getassertions samplertypename setselectedindex getsamplertypename samplerredirectautomatically setselected getsamplerredirectautomatically samplerfollowredirects setselected getsamplerfollowredirects usekeepalive setselected getusekeepalive samplerdownloadimages setselected getsamplerdownloadimages regexmatch setselected getregexmatch httpsspoof setselected gethttpsspoof httpsmatch settext gethttpsspoofmatch contenttypeinclude settext getcontenttypeinclude contenttypeexclude settext getcontenttypeexclude reinitializetargetcombo populatetable includemodel getincludepatterns populatetable excludemodel getexcludepatterns private void populate table power table model p model property iterator iter p model clear data while iter has next p model add row new object iter next get string value p model fire table data changed populatetable powertablemodel p_model propertyiterator p_model cleardata hasnext p_model addrow getstringvalue p_model firetabledatachanged also handles sampler type name public void item state changed item event e system err println e param string enable restart samplertypename itemstatechanged itemevent paramstring enablerestart to do method description param action to do parameter description public void action performed action event action string command action get action command system err println action param string command action get modifiers if command equals stop model stop proxy stop set enabled false start set enabled true restart set enabled false else if command equals start start proxy else if command equals restart model stop proxy start proxy else if command equals enable restart enable restart else if command equals add exclude exclude model add new row exclude model fire table data changed enable restart else if command equals add include include model add new row include model fire table data changed enable restart else if command equals delete exclude exclude model remove row exclude table get selected row exclude model fire table data changed enable restart else if command equals delete include include model remove row include table get selected row include model fire table data changed enable restart else if command equals change target log debug change target target nodes get selected item log debug in model model tree node wrapper nw tree node wrapper target nodes get selected item model set target nw get tree node enable restart todo todo actionperformed actionevent getactioncommand paramstring getmodifiers stopproxy setenabled setenabled setenabled startproxy stopproxy startproxy enable_restart enablerestart add_exclude excludemodel addnewrow excludemodel firetabledatachanged enablerestart add_include includemodel addnewrow includemodel firetabledatachanged enablerestart delete_exclude excludemodel removerow excludetable getselectedrow excludemodel firetabledatachanged enablerestart delete_include includemodel removerow includetable getselectedrow includemodel firetabledatachanged enablerestart change_target targetnodes getselecteditem treenodewrapper treenodewrapper targetnodes getselecteditem settarget gettreenode enablerestart private void start proxy value replacer replacer gui package get instance get replacer modify test element model try replacer replace values model model start proxy start set enabled false stop set enabled true restart set enabled false catch invalid variable exception e j option pane show message dialog this j meter utils get res string invalid variables non nls 1 error j option pane error message catch bind exception e j option pane show message dialog this j meter utils get res string proxy daemon bind error non nls 1 error j option pane error message catch io exception e j option pane show message dialog this j meter utils get res string proxy daemon error non nls 1 error j option pane error message startproxy valuereplacer guipackage getinstance getreplacer modifytestelement replacevalues startproxy setenabled setenabled setenabled invalidvariableexception joptionpane showmessagedialog jmeterutils getresstring invalid_variables joptionpane error_message bindexception joptionpane showmessagedialog jmeterutils getresstring proxy_daemon_bind_error joptionpane error_message ioexception joptionpane showmessagedialog jmeterutils getresstring proxy_daemon_error joptionpane error_message private void enable restart if stop is enabled system err println enable restart restart set enabled true enablerestart isenabled setenabled to do method description param e to do parameter description public void key pressed key event e todo todo keypressed keyevent to do method description param e to do parameter description public void key typed key event e todo todo keytyped keyevent to do method description param e to do parameter description public void key released key event e string field name e get component get name if field name equals portfield try integer parse int port field get text catch number format exception nfe int length port field get text length if length 0 j option pane show message dialog this only digits allowed invalid data j option pane warning message drop the last character port field set text port field get text substring 0 length 1 enable restart else if field name equals enable restart enable restart todo todo keyreleased keyevent fieldname getcomponent getname fieldname parseint portfield gettext numberformatexception portfield gettext joptionpane showmessagedialog joptionpane warning_message portfield settext portfield gettext enablerestart fieldname enable_restart enablerestart private void init set layout new border layout 0 5 set border make border add make title panel border layout north j panel main panel new j panel new border layout box my box box create vertical box my box add create port panel my box add box create vertical strut 5 my box add create test plan content panel my box add box create vertical strut 5 my box add createhttp sampler panel my box add box create vertical strut 5 my box add create content type panel my box add box create vertical strut 5 main panel add my box border layout north box include exclude panel box create vertical box include exclude panel add create include panel include exclude panel add create exclude panel main panel add include exclude panel border layout center main panel add create controls border layout south add main panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout jpanel mainpanel jpanel borderlayout mybox createverticalbox mybox createportpanel mybox createverticalstrut mybox createtestplancontentpanel mybox createverticalstrut mybox createhttpsamplerpanel mybox createverticalstrut mybox createcontenttypepanel mybox createverticalstrut mainpanel mybox borderlayout includeexcludepanel createverticalbox includeexcludepanel createincludepanel includeexcludepanel createexcludepanel mainpanel includeexcludepanel borderlayout mainpanel createcontrols borderlayout mainpanel borderlayout private j panel create controls start new j button j meter utils get res string start non nls 1 start add action listener this start set action command start start set enabled true stop new j button j meter utils get res string stop non nls 1 stop add action listener this stop set action command stop stop set enabled false restart new j button j meter utils get res string restart non nls 1 restart add action listener this restart set action command restart restart set enabled false j panel panel new j panel panel add start panel add stop panel add restart return panel jpanel createcontrols jbutton jmeterutils getresstring addactionlistener setactioncommand setenabled jbutton jmeterutils getresstring addactionlistener setactioncommand setenabled jbutton jmeterutils getresstring addactionlistener setactioncommand setenabled jpanel jpanel private j panel create port panel port field new j text field proxy control default port s 5 port field set name portfield port field add key listener this j label label new j label j meter utils get res string port non nls 1 label set label for port field https spoof new j check box j meter utils get res string proxy httpsspoofing non nls 1 https spoof set selected false https spoof add action listener this https spoof set action command enable restart https match new j text field 40 https match add key listener this https match set name enable restart j label matchlabel new j label j meter utils get res string proxy httpsspoofing match non nls 1 matchlabel set label for https match horizontal panel panel new horizontal panel panel add label panel add port field panel add box create horizontal strut 10 panel add https spoof panel add matchlabel panel add https match return panel jpanel createportpanel portfield jtextfield proxycontrol default_port_s portfield setname portfield addkeylistener jlabel jlabel jmeterutils getresstring setlabelfor portfield httpsspoof jcheckbox jmeterutils getresstring proxy_httpsspoofing httpsspoof setselected httpsspoof addactionlistener httpsspoof setactioncommand enable_restart httpsmatch jtextfield httpsmatch addkeylistener httpsmatch setname enable_restart jlabel jlabel jmeterutils getresstring proxy_httpsspoofing_match setlabelfor httpsmatch horizontalpanel horizontalpanel portfield createhorizontalstrut httpsspoof httpsmatch private j panel create test plan content panel http headers new j check box j meter utils get res string proxy headers non nls 1 http headers set selected true maintain original default http headers add action listener this http headers set action command enable restart add assertions new j check box j meter utils get res string proxy assertions non nls 1 add assertions set selected false add assertions add action listener this add assertions set action command enable restart regex match new j check box j meter utils get res string proxy regex non nls 1 regex match set selected false regex match add action listener this regex match set action command enable restart vertical panel main panel new vertical panel main panel set border border factory create titled border border factory create etched border j meter utils get res string proxy test plan content non nls 1 horizontal panel node creation panel new horizontal panel node creation panel add http headers node creation panel add add assertions node creation panel add regex match horizontal panel target panel new horizontal panel target panel add create target panel target panel add create grouping panel main panel add target panel main panel add node creation panel return main panel jpanel createtestplancontentpanel httpheaders jcheckbox jmeterutils getresstring proxy_headers httpheaders setselected httpheaders addactionlistener httpheaders setactioncommand enable_restart addassertions jcheckbox jmeterutils getresstring proxy_assertions addassertions setselected addassertions addactionlistener addassertions setactioncommand enable_restart regexmatch jcheckbox jmeterutils getresstring proxy_regex regexmatch setselected regexmatch addactionlistener regexmatch setactioncommand enable_restart verticalpanel mainpanel verticalpanel mainpanel setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring proxy_test_plan_content horizontalpanel nodecreationpanel horizontalpanel nodecreationpanel httpheaders nodecreationpanel addassertions nodecreationpanel regexmatch horizontalpanel targetpanel horizontalpanel targetpanel createtargetpanel targetpanel creategroupingpanel mainpanel targetpanel mainpanel nodecreationpanel mainpanel private j panel createhttp sampler panel default combo box model m new default combo box model note position of these elements in the menu must match the corresponding proxy control sampler type values m add element j meter utils get res string web testing title non nls 1 m add element j meter utils get res string web testing2 title non nls 1 sampler type name new j combo box m sampler type name set selected index 0 sampler type name add item listener this j label label2 new j label j meter utils get res string proxy sampler type non nls 1 label2 set label for sampler type name sampler redirect automatically new j check box j meter utils get res string follow redirects auto non nls 1 sampler redirect automatically set selected false sampler redirect automatically add action listener this sampler redirect automatically set action command enable restart sampler follow redirects new j check box j meter utils get res string follow redirects non nls 1 sampler follow redirects set selected true sampler follow redirects add action listener this sampler follow redirects set action command enable restart use keep alive new j check box j meter utils get res string use keepalive non nls 1 use keep alive set selected true use keep alive add action listener this use keep alive set action command enable restart sampler download images new j check box j meter utils get res string web testing retrieve images non nls 1 sampler download images set selected false sampler download images add action listener this sampler download images set action command enable restart horizontal panel panel new horizontal panel panel set border border factory create titled border border factory create etched border j meter utils get res string proxy sampler settings non nls 1 panel add label2 panel add sampler type name panel add sampler redirect automatically panel add sampler follow redirects panel add use keep alive panel add sampler download images return panel jpanel createhttpsamplerpanel defaultcomboboxmodel defaultcomboboxmodel proxycontrol sampler_type_ addelement jmeterutils getresstring web_testing_title addelement jmeterutils getresstring web_testing2_title samplertypename jcombobox samplertypename setselectedindex samplertypename additemlistener jlabel jlabel jmeterutils getresstring proxy_sampler_type setlabelfor samplertypename samplerredirectautomatically jcheckbox jmeterutils getresstring follow_redirects_auto samplerredirectautomatically setselected samplerredirectautomatically addactionlistener samplerredirectautomatically setactioncommand enable_restart samplerfollowredirects jcheckbox jmeterutils getresstring follow_redirects samplerfollowredirects setselected samplerfollowredirects addactionlistener samplerfollowredirects setactioncommand enable_restart usekeepalive jcheckbox jmeterutils getresstring use_keepalive usekeepalive setselected usekeepalive addactionlistener usekeepalive setactioncommand enable_restart samplerdownloadimages jcheckbox jmeterutils getresstring web_testing_retrieve_images samplerdownloadimages setselected samplerdownloadimages addactionlistener samplerdownloadimages setactioncommand enable_restart horizontalpanel horizontalpanel setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring proxy_sampler_settings samplertypename samplerredirectautomatically samplerfollowredirects usekeepalive samplerdownloadimages private j panel create target panel target nodes model new default combo box model target nodes new j combo box target nodes model target nodes set action command change target action listener will be added later j label label new j label j meter utils get res string proxy target non nls 1 label set label for target nodes horizontal panel panel new horizontal panel panel add label panel add target nodes return panel jpanel createtargetpanel targetnodesmodel defaultcomboboxmodel targetnodes jcombobox targetnodesmodel targetnodes setactioncommand change_target jlabel jlabel jmeterutils getresstring proxy_target setlabelfor targetnodes horizontalpanel horizontalpanel targetnodes private j panel create grouping panel default combo box model m new default combo box model note position of these elements in the menu must match the corresponding proxy control grouping values m add element j meter utils get res string grouping no groups non nls 1 m add element j meter utils get res string grouping add separators non nls 1 m add element j meter utils get res string grouping in controllers non nls 1 m add element j meter utils get res string grouping store first only non nls 1 grouping mode new j combo box m grouping mode set selected index 0 grouping mode add item listener this j label label2 new j label j meter utils get res string grouping mode non nls 1 label2 set label for grouping mode horizontal panel panel new horizontal panel panel add label2 panel add grouping mode return panel jpanel creategroupingpanel defaultcomboboxmodel defaultcomboboxmodel proxycontrol grouping_ addelement jmeterutils getresstring grouping_no_groups addelement jmeterutils getresstring grouping_add_separators addelement jmeterutils getresstring grouping_in_controllers addelement jmeterutils getresstring grouping_store_first_only groupingmode jcombobox groupingmode setselectedindex groupingmode additemlistener jlabel jlabel jmeterutils getresstring grouping_mode setlabelfor groupingmode horizontalpanel horizontalpanel groupingmode private j panel create content type panel content type include new j text field 35 content type include add key listener this content type include set name enable restart j label label include new j label j meter utils get res string proxy content type include non nls 1 label include set label for content type include default value content type include set text j meter utils get property proxy content type include non nls 1 content type exclude new j text field 35 content type exclude add key listener this content type exclude set name enable restart j label label exclude new j label j meter utils get res string proxy content type exclude non nls 1 label exclude set label for content type exclude default value content type exclude set text j meter utils get property proxy content type exclude non nls 1 horizontal panel panel new horizontal panel panel set border border factory create titled border border factory create etched border j meter utils get res string proxy content type filter non nls 1 panel add label include panel add content type include panel add label exclude panel add content type exclude return panel jpanel createcontenttypepanel contenttypeinclude jtextfield contenttypeinclude addkeylistener contenttypeinclude setname enable_restart jlabel labelinclude jlabel jmeterutils getresstring proxy_content_type_include labelinclude setlabelfor contenttypeinclude contenttypeinclude settext jmeterutils getproperty content_type_include contenttypeexclude jtextfield contenttypeexclude addkeylistener contenttypeexclude setname enable_restart jlabel labelexclude jlabel jmeterutils getresstring proxy_content_type_exclude labelexclude setlabelfor contenttypeexclude contenttypeexclude settext jmeterutils getproperty content_type_exclude horizontalpanel horizontalpanel setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring proxy_content_type_filter labelinclude contenttypeinclude labelexclude contenttypeexclude private j panel create include panel include model new power table model new string include col new class string class include table new j table include model include table get table header set default renderer new header as property renderer include table set preferred scrollable viewport size new dimension 100 30 j panel panel new j panel new border layout panel set border border factory create titled border border factory create etched border j meter utils get res string patterns to include non nls 1 panel add new j scroll pane include table border layout center panel add create table button panel add include delete include border layout south return panel jpanel createincludepanel includemodel powertablemodel include_col includetable jtable includemodel includetable gettableheader setdefaultrenderer headeraspropertyrenderer includetable setpreferredscrollableviewportsize jpanel jpanel borderlayout setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring patterns_to_include jscrollpane includetable borderlayout createtablebuttonpanel add_include delete_include borderlayout private j panel create exclude panel exclude model new power table model new string exclude col new class string class exclude table new j table exclude model exclude table get table header set default renderer new header as property renderer exclude table set preferred scrollable viewport size new dimension 100 30 j panel panel new j panel new border layout panel set border border factory create titled border border factory create etched border j meter utils get res string patterns to exclude non nls 1 panel add new j scroll pane exclude table border layout center panel add create table button panel add exclude delete exclude border layout south return panel jpanel createexcludepanel excludemodel powertablemodel exclude_col excludetable jtable excludemodel excludetable gettableheader setdefaultrenderer headeraspropertyrenderer excludetable setpreferredscrollableviewportsize jpanel jpanel borderlayout setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring patterns_to_exclude jscrollpane excludetable borderlayout createtablebuttonpanel add_exclude delete_exclude borderlayout private j panel create table button panel string add command string delete command j panel button panel new j panel j button add button new j button j meter utils get res string add non nls 1 add button set action command add command add button add action listener this button panel add add button j button delete button new j button j meter utils get res string delete non nls 1 delete button set action command delete command delete button add action listener this button panel add delete button return button panel jpanel createtablebuttonpanel addcommand deletecommand jpanel buttonpanel jpanel jbutton addbutton jbutton jmeterutils getresstring addbutton setactioncommand addcommand addbutton addactionlistener buttonpanel addbutton jbutton deletebutton jbutton jmeterutils getresstring deletebutton setactioncommand deletecommand deletebutton addactionlistener buttonpanel deletebutton buttonpanel private void reinitialize target combo log debug reinitializing target combo stop action notifications while we shuffle this around target nodes remove action listener this target nodes model remove all elements gui package gp gui package get instance j meter tree node root if gp null root j meter tree node gui package get instance get tree model get root target nodes model add element new tree node wrapper null j meter utils get res string use recording controller non nls 1 build nodes model root 0 tree node wrapper choice null for int i 0 i target nodes model get size i choice tree node wrapper target nodes model get element at i log debug selecting item choice for model model in this if choice get tree node model get target equals caused npe break reinstate action notifications target nodes add action listener this set the current value target nodes model set selected item choice log debug reinitialization complete reinitializetargetcombo targetnodes removeactionlistener targetnodesmodel removeallelements guipackage guipackage getinstance jmetertreenode jmetertreenode guipackage getinstance gettreemodel getroot targetnodesmodel addelement treenodewrapper jmeterutils getresstring use_recording_controller buildnodesmodel treenodewrapper targetnodesmodel getsize treenodewrapper targetnodesmodel getelementat gettreenode gettarget targetnodes addactionlistener targetnodesmodel setselecteditem private void build nodes model j meter tree node node string parent name int level string seperator if node null for int i 0 i node get child count i string buffer name new string buffer j meter tree node cur j meter tree node node get child at i test element te cur get test element will never be true probably intended to use org apache jmeter threads thread group rather than java lang thread group however that does not work correctly whereas treating it as a controller does if te instanceof thread group name append parent name name append cur get name name append seperator build nodes model cur name to string level else if te instanceof controller name append spaces level name append parent name name append cur get name tree node wrapper tnw new tree node wrapper cur name to string target nodes model add element tnw name new string buffer name append cur get name name append seperator build nodes model cur name to string level 1 else if te instanceof test plan te instanceof work bench name append cur get name name append seperator build nodes model cur name to string 0 ignore everything else buildnodesmodel jmetertreenode parent_name getchildcount stringbuffer stringbuffer jmetertreenode jmetertreenode getchildat testelement gettestelement threadgroup threadgroup threadgroup parent_name getname buildnodesmodel tostring parent_name getname treenodewrapper treenodewrapper tostring targetnodesmodel addelement stringbuffer getname buildnodesmodel tostring testplan workbench getname buildnodesmodel tostring private string spaces int level int multi 4 string buffer spaces new string buffer level multi for int i 0 i level multi i spaces append non nls 1 return spaces to string stringbuffer stringbuffer tostring public void set node j meter tree node node get name panel set node node setnode jmetertreenode getnamepanel setnode private final string label public tree node wrapper j meter tree node tn string label this tn tn this label label treenodewrapper jmetertreenode public j meter tree node get tree node return tn jmetertreenode gettreenode public string to string return label tostring report table url public abstract table super report_table_url abstracttable public boolean get mean return get property as boolean report table mean getmean getpropertyasboolean report_table_mean public void set mean string set set property report table mean set setmean setproperty report_table_mean public boolean get median return get property as boolean report table median getmedian getpropertyasboolean report_table_median public void set median string set set property report table median set setmedian setproperty report_table_median public boolean get max return get property as boolean report table max getmax getpropertyasboolean report_table_max public void set max string set set property report table max set setmax setproperty report_table_max public boolean get min return get property as boolean report table min getmin getpropertyasboolean report_table_min public void set min string set set property report table min set setmin setproperty report_table_min public boolean get response rate return get property as boolean report table response rate getresponserate getpropertyasboolean report_table_response_rate public void set response rate string set set property report table response rate set setresponserate setproperty report_table_response_rate public boolean get transfer rate return get property as boolean report table transfer rate gettransferrate getpropertyasboolean report_table_transfer_rate public void set transfer rate string set set property report table transfer rate set settransferrate setproperty report_table_transfer_rate public boolean get50 percent return get property as boolean report table 50 percent get50percent getpropertyasboolean report_table_50_percent public void set50 percent string set set property report table 50 percent set set50percent setproperty report_table_50_percent public boolean get90 percent return get property as boolean report table 90 percent get90percent getpropertyasboolean report_table_90_percent public void set90 percent string set set property report table 90 percent set set90percent setproperty report_table_90_percent public boolean get error rate return get property as boolean report table error rate geterrorrate getpropertyasboolean report_table_error_rate public void set error rate string set set property report table error rate set seterrorrate setproperty report_table_error_rate public void add test element test element el if el null super add test element el log info test element el get class get name addtestelement testelement addtestelement testelement getclass getname method isn t implemented and is left abstract subclasses need to filter the data in the list and return statistics the statistics should be like the aggregate listener public test switch controller string name super name testswitchcontroller get next sample and its name private string next name generic controller c sampler s c next string n if s null return null n s get name return n nextname genericcontroller getname public void test throws exception run simple tests zero runsimpletests public void test0 throws exception run simple tests 0 zero runsimpletests public void test1 throws exception run simple tests 1 one run simple tests one one match by name runsimpletests runsimpletests public void test2 throws exception run simple tests 2 two run simple tests two two match by name runsimpletests runsimpletests public void test3 throws exception run simple tests 3 three run simple tests three three match by name runsimpletests runsimpletests public void test4 throws exception run simple tests 4 zero runsimpletests public void testx throws exception run simple tests x null should not run any children run simple test2 x one default should match the default entry runsimpletests runsimpletest2 private void run simple tests string cond string exp throws exception run simple test cond exp run simple test2 cond exp one runsimpletests runsimpletest runsimpletest2 private void run simple test string cond string exp throws exception generic controller controller new generic controller switch controller switch cont new switch controller switch cont set selection cond controller add test element new test sampler before controller add test element switch cont switch cont add test element new test sampler zero switch cont add test element new test sampler one switch cont add test element new test sampler two switch cont add test element new test sampler three controller add test element new test sampler after controller initialize for int i 1 i 3 i assert equals loop i before next name controller if exp null assert equals loop i exp next name controller assert equals loop i after next name controller assert null next name controller runsimpletest genericcontroller genericcontroller switchcontroller switch_cont switchcontroller switch_cont setselection addtestelement testsampler addtestelement switch_cont switch_cont addtestelement testsampler switch_cont addtestelement testsampler switch_cont addtestelement testsampler switch_cont addtestelement testsampler addtestelement testsampler assertequals nextname assertequals nextname assertequals nextname assertnull nextname private void run simple test2 string cond string exp string sub1 name throws exception generic controller controller new generic controller generic controller sub 1 new generic controller generic controller sub 2 new generic controller switch controller switch cont new switch controller switch cont set selection cond switch cont add test element new test sampler zero switch cont add test element sub 1 sub 1 add test element new test sampler one sub 1 set name sub1 name switch cont add test element new test sampler two switch cont add test element sub 2 sub 2 add test element new test sampler three sub 2 set name three controller add test element new test sampler before controller add test element switch cont controller add test element new test sampler after controller initialize for int i 1 i 3 i assert equals loop i before next name controller if exp null assert equals loop i exp next name controller assert equals loop i after next name controller assert null loop i next name controller runsimpletest2 sub1name genericcontroller genericcontroller genericcontroller sub_1 genericcontroller genericcontroller sub_2 genericcontroller switchcontroller switch_cont switchcontroller switch_cont setselection switch_cont addtestelement testsampler switch_cont addtestelement sub_1 sub_1 addtestelement testsampler sub_1 setname sub1name switch_cont addtestelement testsampler switch_cont addtestelement sub_2 sub_2 addtestelement testsampler sub_2 setname addtestelement testsampler addtestelement switch_cont addtestelement testsampler assertequals nextname assertequals nextname assertequals nextname assertnull nextname public void test test2 throws exception run test2 new string zero run test2 0 new string zero run test2 7 new string zero run test2 5 new string zero run test2 4 new string six run test2 3 new string five run test2 1 new string one two run test2 2 new string three four testtest2 runtest2 runtest2 runtest2 runtest2 runtest2 runtest2 runtest2 runtest2 private void run test2 string cond string exp throws exception int loops 3 loop controller controller new loop controller controller set loops loops controller set continue forever false generic controller sub 1 new generic controller generic controller sub 2 new generic controller switch controller switch cont new switch controller switch cont set selection cond switch cont add test element new test sampler zero switch cont add test element sub 1 sub 1 add test element new test sampler one sub 1 add test element new test sampler two switch cont add test element sub 2 sub 2 add test element new test sampler three sub 2 add test element new test sampler four switch cont add test element new test sampler five switch cont add test element new test sampler six controller add test element new test sampler before controller add test element switch cont controller add test element new test sampler after controller set running version true sub 1 set running version true sub 2 set running version true switch cont set running version true controller initialize for int i 1 i 3 i assert equals loop i before next name controller for int j 0 j exp length j assert equals loop i exp j next name controller assert equals loop i after next name controller assert null loops loops next name controller runtest2 loopcontroller loopcontroller setloops setcontinueforever genericcontroller sub_1 genericcontroller genericcontroller sub_2 genericcontroller switchcontroller switch_cont switchcontroller switch_cont setselection switch_cont addtestelement testsampler switch_cont addtestelement sub_1 sub_1 addtestelement testsampler sub_1 addtestelement testsampler switch_cont addtestelement sub_2 sub_2 addtestelement testsampler sub_2 addtestelement testsampler switch_cont addtestelement testsampler switch_cont addtestelement testsampler addtestelement testsampler addtestelement switch_cont addtestelement testsampler setrunningversion sub_1 setrunningversion sub_2 setrunningversion switch_cont setrunningversion assertequals nextname assertequals nextname assertequals nextname assertnull nextname public void test function throws exception j meter context jmctx j meter context service get context map variables new hash map replace string with functions transformer new replace string with functions new compound variable variables jmctx set variables new j meter variables j meter variables jmvars jmctx get variables jmvars put var 100 string property prop new string property switch controller switch value counter true var j meter property new prop transformer transform value prop new prop set running version true generic controller controller new generic controller switch controller switch cont new switch controller switch cont set property new prop controller add test element new test sampler before controller add test element switch cont switch cont add test element new test sampler 0 switch cont add test element new test sampler 1 switch cont add test element new test sampler 2 switch cont add test element new test sampler 3 controller add test element new test sampler after controller initialize assert equals 100 jmvars get var for int i 1 i 3 i assert equals loop i before next name controller assert equals loop i i next name controller assert equals loop i i jmvars get var assert equals loop i after next name controller assert null next name controller int i 4 assert equals loop i before next name controller assert equals loop i 0 next name controller assert equals loop i i jmvars get var assert equals loop i after next name controller assert null next name controller assert equals 4 jmvars get var testfunction jmetercontext jmetercontextservice getcontext hashmap replacestringwithfunctions replacestringwithfunctions compoundvariable setvariables jmetervariables jmetervariables getvariables stringproperty stringproperty switchcontroller switch_value __counter jmeterproperty newprop transformvalue newprop setrunningversion genericcontroller genericcontroller switchcontroller switch_cont switchcontroller switch_cont setproperty newprop addtestelement testsampler addtestelement switch_cont switch_cont addtestelement testsampler switch_cont addtestelement testsampler switch_cont addtestelement testsampler switch_cont addtestelement testsampler addtestelement testsampler assertequals assertequals nextname assertequals nextname assertequals assertequals nextname assertnull nextname assertequals nextname assertequals nextname assertequals assertequals nextname assertnull nextname assertequals private j check box per iteration check public user parameters gui super init jcheckbox periterationcheck userparametersgui public string get label resource return user parameters title non nls 1 getlabelresource user_parameters_title public void configure test element el init table model param table set model table model user parameters params user parameters el collection property names params get names collection property thread values params get thread lists table model set column data 0 list names get object value property iterator iter thread values iterator if iter has next table model set column data 1 list iter next get object value int count 2 while iter has next string col name get user col name count table model add new column col name string class table model set column data count list iter next get object value count per iteration check set selected params is per iteration super configure el testelement inittablemodel paramtable setmodel tablemodel userparameters userparameters collectionproperty getnames collectionproperty threadvalues getthreadlists tablemodel setcolumndata getobjectvalue propertyiterator threadvalues hasnext tablemodel setcolumndata getobjectvalue hasnext colname getusercolname tablemodel addnewcolumn colname tablemodel setcolumndata getobjectvalue periterationcheck setselected isperiteration see org apache jmeter gui j metergui component create test element public test element create test element user parameters params new user parameters modify test element params return params jmeterguicomponent createtestelement testelement createtestelement userparameters userparameters modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element params if param table is editing param table get cell editor stop cell editing user parameters user params user parameters params user params set names new collection property user parameters names table model get column data name col resource collection property thread lists new collection property user parameters thread values new array list log debug making threadlists from gui for int col 1 col table model get column count col thread lists add item table model get column data get user col name col log debug adding column to threadlist table model get column data get user col name col log debug threadlists now thread lists log debug in the end threadlists thread lists user params set thread lists thread lists user params set per iteration per iteration check is selected super configure test element params testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement paramtable isediting paramtable getcelleditor stopcellediting userparameters userparams userparameters userparams setnames collectionproperty userparameters tablemodel getcolumndata name_col_resource collectionproperty threadlists collectionproperty userparameters thread_values arraylist tablemodel getcolumncount threadlists additem tablemodel getcolumndata getusercolname tablemodel getcolumndata getusercolname threadlists threadlists userparams setthreadlists threadlists userparams setperiteration periterationcheck isselected configuretestelement implements j metergui component clear gui public void clear gui super clear gui init table model param table set model table model header as property renderer default renderer new header as property renderer protected string get text object value int row int column if column 1 don t process the name column string val value to string if val starts with user col resource underscore return j meter utils get res string user col resource val substring val index of underscore return super get text value row column param table get table header set default renderer default renderer per iteration check set selected false jmeterguicomponent cleargui cleargui cleargui inittablemodel paramtable setmodel tablemodel headeraspropertyrenderer defaultrenderer headeraspropertyrenderer gettext tostring startswith user_col_resource jmeterutils getresstring user_col_resource indexof gettext paramtable gettableheader setdefaultrenderer defaultrenderer periterationcheck setselected header as property renderer default renderer new header as property renderer protected string get text object value int row int column if column 1 don t process the name column string val value to string if val starts with user col resource underscore return j meter utils get res string user col resource val substring val index of underscore return super get text value row column headeraspropertyrenderer defaultrenderer headeraspropertyrenderer gettext tostring startswith user_col_resource jmeterutils getresstring user_col_resource indexof gettext private string get user col name int user return user col resource underscore user getusercolname user_col_resource private void init set border make border set layout new border layout j panel vert panel new vertical panel vert panel add make title panel per iteration check new j check box j meter utils get res string update per iter true non nls 1 box per iteration panel box create horizontal box per iteration panel add per iteration check per iteration panel add box create horizontal glue vert panel add per iteration panel add vert panel border layout north add make parameter panel border layout center setborder makeborder setlayout borderlayout jpanel vertpanel verticalpanel vertpanel maketitlepanel periterationcheck jcheckbox jmeterutils getresstring update_per_iter periterationpanel createhorizontalbox periterationpanel periterationcheck periterationpanel createhorizontalglue vertpanel periterationpanel vertpanel borderlayout makeparameterpanel borderlayout private j panel make parameter panel j label table label new j label j meter utils get res string user parameters table non nls 1 init table model param table new j table table model param table set row selection allowed true param table set column selection allowed true param table set selection mode list selection model single selection param table set cell selection enabled true param table set preferred scrollable viewport size new dimension 100 70 j panel param panel new j panel new border layout param panel add table label border layout north j scroll pane scroll new j scroll pane param table scroll set preferred size scroll get minimum size param panel add scroll border layout center param panel add make button panel border layout south return param panel jpanel makeparameterpanel jlabel tablelabel jlabel jmeterutils getresstring user_parameters_table inittablemodel paramtable jtable tablemodel paramtable setrowselectionallowed paramtable setcolumnselectionallowed paramtable setselectionmode listselectionmodel single_selection paramtable setcellselectionenabled paramtable setpreferredscrollableviewportsize jpanel parampanel jpanel borderlayout parampanel tablelabel borderlayout jscrollpane jscrollpane paramtable setpreferredsize getminimumsize parampanel borderlayout parampanel makebuttonpanel borderlayout parampanel protected void init table model table model new power table model new string name col resource non nls 1 get user col name num user columns new class string class string class inittablemodel tablemodel powertablemodel name_col_resource getusercolname numusercolumns private j panel make button panel j panel button panel new j panel button panel set layout new grid layout 2 2 add parameter button new j button j meter utils get res string add parameter non nls 1 add user button new j button j meter utils get res string add user non nls 1 delete row button new j button j meter utils get res string delete parameter non nls 1 delete column button new j button j meter utils get res string delete user non nls 1 button panel add add parameter button button panel add delete row button button panel add add user button button panel add delete column button add parameter button add action listener new add param action add user button add action listener new add user action delete row button add action listener new delete row action delete column button add action listener new delete column action return button panel jpanel makebuttonpanel jpanel buttonpanel jpanel buttonpanel setlayout gridlayout addparameterbutton jbutton jmeterutils getresstring add_parameter adduserbutton jbutton jmeterutils getresstring add_user deleterowbutton jbutton jmeterutils getresstring delete_parameter deletecolumnbutton jbutton jmeterutils getresstring delete_user buttonpanel addparameterbutton buttonpanel deleterowbutton buttonpanel adduserbutton buttonpanel deletecolumnbutton addparameterbutton addactionlistener addparamaction adduserbutton addactionlistener adduseraction deleterowbutton addactionlistener deleterowaction deletecolumnbutton addactionlistener deletecolumnaction buttonpanel private class add param action implements action listener public void action performed action event e if param table is editing table cell editor cell editor param table get cell editor param table get editing row param table get editing column cell editor stop cell editing table model add new row table model fire table data changed enable delete which may already be enabled but it won t hurt delete row button set enabled true highlight select the appropriate row int row to select table model get row count 1 param table set row selection interval row to select row to select addparamaction actionlistener actionperformed actionevent paramtable isediting tablecelleditor celleditor paramtable getcelleditor paramtable geteditingrow paramtable geteditingcolumn celleditor stopcellediting tablemodel addnewrow tablemodel firetabledatachanged deleterowbutton setenabled rowtoselect tablemodel getrowcount paramtable setrowselectioninterval rowtoselect rowtoselect private class add user action implements action listener public void action performed action event e if param table is editing table cell editor cell editor param table get cell editor param table get editing row param table get editing column cell editor stop cell editing table model add new column get user col name table model get column count string class table model fire table data changed enable delete which may already be enabled but it won t hurt delete column button set enabled true highlight select the appropriate row int col to select table model get column count 1 param table set column selection interval col to select col to select adduseraction actionlistener actionperformed actionevent paramtable isediting tablecelleditor celleditor paramtable getcelleditor paramtable geteditingrow paramtable geteditingcolumn celleditor stopcellediting tablemodel addnewcolumn getusercolname tablemodel getcolumncount tablemodel firetabledatachanged deletecolumnbutton setenabled coltoselect tablemodel getcolumncount paramtable setcolumnselectioninterval coltoselect coltoselect private class delete row action implements action listener public void action performed action event e if param table is editing table cell editor cell editor param table get cell editor param table get editing row param table get editing column cell editor cancel cell editing int row selected param table get selected row if row selected 0 table model remove row row selected table model fire table data changed disable delete if there are no rows in the table to delete if table model get row count 0 delete row button set enabled false table still contains one or more rows so highlight select the appropriate one else int row to select row selected if row selected table model get row count row to select row selected 1 param table set row selection interval row to select row to select deleterowaction actionlistener actionperformed actionevent paramtable isediting tablecelleditor celleditor paramtable getcelleditor paramtable geteditingrow paramtable geteditingcolumn celleditor cancelcellediting rowselected paramtable getselectedrow rowselected tablemodel removerow rowselected tablemodel firetabledatachanged tablemodel getrowcount deleterowbutton setenabled rowtoselect rowselected rowselected tablemodel getrowcount rowtoselect rowselected paramtable setrowselectioninterval rowtoselect rowtoselect private class delete column action implements action listener public void action performed action event e if param table is editing table cell editor cell editor param table get cell editor param table get editing row param table get editing column cell editor cancel cell editing int col selected param table get selected column if col selected 0 col selected 1 j option pane show message dialog null j meter utils get res string column delete disallowed non nls 1 error j option pane error message return if col selected 0 table model remove column col selected table model fire table data changed disable delete if there are no rows in the table to delete if table model get column count 0 delete column button set enabled false table still contains one or more rows so highlight select the appropriate one else if col selected table model get column count col selected col selected 1 param table set column selection interval col selected col selected deletecolumnaction actionlistener actionperformed actionevent paramtable isediting tablecelleditor celleditor paramtable getcelleditor paramtable geteditingrow paramtable geteditingcolumn celleditor cancelcellediting colselected paramtable getselectedcolumn colselected colselected joptionpane showmessagedialog jmeterutils getresstring column_delete_disallowed joptionpane error_message colselected tablemodel removecolumn colselected tablemodel firetabledatachanged tablemodel getcolumncount deletecolumnbutton setenabled colselected tablemodel getcolumncount colselected colselected paramtable setcolumnselectioninterval colselected colselected public class testcsv save service extends j meter test case public testcsv save service string name super name testcsvsaveservice jmetertestcase testcsvsaveservice private void check split string string input char delim string expected throws exception string out csv save service csv split string input delim check strings expected out checksplitstring csvsaveservice csvsplitstring checkstrings private void check strings string expected string out assert equals incorrect number of strings returned expected length out length for int i 0 i out length i assert equals incorrect entry returned expected i out i checkstrings assertequals assertequals this is what j orphan utils split does public void test split empty throws exception check split string new string jorphanutils testsplitempty checksplitstring public void test split unquoted throws exception check split string a new string a check split string a bc d e new string a bc d e check split string bc d e new string bc d e check split string a d e new string a d e check split string a bc e new string a bc e check split string a bc d new string a bc d check split string a bc d new string a bc d check split string a bc new string a bc check split string a new string a check split string a bc d n new string a bc d testsplitunquoted checksplitstring checksplitstring checksplitstring checksplitstring checksplitstring checksplitstring checksplitstring checksplitstring checksplitstring checksplitstring public void test split quoted throws exception check split string a bc d e new string a bc d e check split string bc d e new string bc d e check split string bc d e new string bc d e check split string a d e new string a d e check split string a d e new string a d e check split string a bc e new string a bc e check split string a bc e new string a bc e check split string a bc d new string a bc d check split string a bc d new string a bc d check split string a bc d new string a bc d check split string a bc d new string a bc d check split string a bc d n new string a bc d testsplitquoted checksplitstring checksplitstring checksplitstring checksplitstring checksplitstring checksplitstring checksplitstring checksplitstring checksplitstring checksplitstring checksplitstring checksplitstring public void test split bad quote throws exception try check split string a b null fail should have generated io exception catch io exception e testsplitbadquote checksplitstring ioexception ioexception public void test split multi line throws exception string line a c nd e n f g string out buffered reader br new buffered reader new string reader line out csv save service csv read file br check strings new string a c nd e out out csv save service csv read file br check strings new string f g out assert equals expected to be at eof 1 br read empty strings at eof out csv save service csv read file br check strings new string out out csv save service csv read file br check strings new string out testsplitmultiline bufferedreader bufferedreader stringreader csvsaveservice csvreadfile checkstrings csvsaveservice csvreadfile checkstrings assertequals csvsaveservice csvreadfile checkstrings csvsaveservice csvreadfile checkstrings private file wrapper file row col container fdc super container fdc current row 1 filewrapper filerowcolcontainer currentrow the cache of file packs used to improve thread access private static final thread local file packs new thread local protected object initial value return new hash map threadlocal filepacks threadlocal initialvalue hashmap private static string check default string file if file length 0 if file containers size 1 default file length 0 log warn using default default file file default file else log error cannot determine default file name return file checkdefault filecontainers defaultfile defaultfile defaultfile public static synchronized void open string file string alias log info opening file as alias file check default file if alias length 0 log error alias cannot be empty return map m map file packs get if m get alias null file row col container frcc try frcc get file file alias log info stored file as alias m put alias new file wrapper frcc catch file not found exception e already logged catch io exception e already logged checkdefault filepacks filerowcolcontainer getfile filewrapper filenotfoundexception ioexception private static file row col container get file string file string alias throws file not found exception io exception file row col container frcc if frcc file row col container file containers get alias null frcc new file row col container file file containers put alias frcc log info saved file as alias delimiter frcc get delimiter if default file length 0 default file file save in case needed later return frcc filerowcolcontainer getfile filenotfoundexception ioexception filerowcolcontainer filerowcolcontainer filecontainers filerowcolcontainer filecontainers getdelimiter defaultfile defaultfile public static void end row string file file check default file map my map file packs get file wrapper fw file wrapper my get file if fw null log warn end row no entry for file else fw end row endrow checkdefault filepacks filewrapper filewrapper endrow endrow private void end row if current row no line log warn end row called twice in succession current row no line endrow currentrow no_line endrow currentrow no_line public static string get column string file int col map my map file packs get file wrapper fw file wrapper my get file if fw null first call if file starts with non nls 1 log warn cannot perform initial open using alias file else file check default file log info attaching file open file file fw file wrapper my get file todo improve the error handling if fw null return non nls 1 return fw get column col getcolumn filepacks filewrapper filewrapper startswith checkdefault filewrapper getcolumn private string get column int col if current row no line current row container next row return container get column current row col getcolumn currentrow no_line currentrow nextrow getcolumn currentrow gets the current row number mainly for error reporting param file return the current row number for this thread public static int get current row string file map my map file packs get file wrapper fw file wrapper my get file if fw null not yet open return 1 return fw current row getcurrentrow filepacks filewrapper filewrapper currentrow public static void clear all log debug clear all map my map file packs get for iterator i my entry set iterator i has next object fw i next log info removing fw to string i remove file containers clear default file non nls 1 clearall clearall filepacks entryset hasnext tostring filecontainers defaultfile public abstract class abstract sampler gui extends abstractj meter gui component when a user right clicks on the component in the test tree or selects the edit menu when the component is selected the component will be asked to return a j popup menu that provides all the options available to the user from this component p this implementation returns menu items appropriate for most sampler components return a j popup menu appropriate for the component public j popup menu create popup menu return menu factory get default sampler menu abstractsamplergui abstractjmeterguicomponent jpopupmenu jpopupmenu jpopupmenu createpopupmenu menufactory getdefaultsamplermenu this is the list of menu categories this gui component will be available under this implementation returns link org apache jmeter gui util menu factory samplers which is appropriate for most sampler components return a collection of strings where each element is one of the constants defined in menu factory public collection get menu categories return arrays as list new string menu factory samplers menufactory menufactory getmenucategories aslist menufactory j meter utils get prop default assertion equals diff delta end public response assertion set property new collection property test strings new array list jmeterutils getpropdefault equals_diff_delta_end responseassertion setproperty collectionproperty test_strings arraylist public void clear super clear set property new collection property test strings new array list setproperty collectionproperty test_strings arraylist private void set test field string test field set property test field test field settestfield testfield setproperty test_field testfield public void set test fieldurl set test field sample url settestfieldurl settestfield sample_url public void set test field response code set test field response code settestfieldresponsecode settestfield response_code public void set test field response data set test field response data settestfieldresponsedata settestfield response_data public void set test field response message set test field response message settestfieldresponsemessage settestfield response_message public void set test field response headers set test field response headers settestfieldresponseheaders settestfield response_headers public boolean is test fieldurl return sample url equals get test field istestfieldurl sample_url gettestfield public boolean is test field response code return response code equals get test field istestfieldresponsecode response_code gettestfield public boolean is test field response data return response data equals get test field istestfieldresponsedata response_data gettestfield public boolean is test field response message return response message equals get test field istestfieldresponsemessage response_message gettestfield public boolean is test field response headers return response headers equals get test field istestfieldresponseheaders response_headers gettestfield private void set test type int test type set property new integer property test type test type settesttype testtype setproperty integerproperty test_type testtype private void set test type masked int test type int value get test type type mask test type set property new integer property test type value settesttypemasked testtype gettesttype type_mask testtype setproperty integerproperty test_type public void add test string string test string get test strings add property new string property string value of test string hash code test string addteststring teststring getteststrings addproperty stringproperty valueof teststring hashcode teststring public void clear test strings get test strings clear clearteststrings getteststrings public assertion result get result sample result response assertion result result none of the other assertions check the response status so remove this check for the time being at least if response is successful result new assertion result result set error true byte ba response get response data result set failure message ba null unknown error response data is empty new string ba return result result evaluate response response return result assertionresult getresult sampleresult assertionresult issuccessful assertionresult seterror getresponsedata setfailuremessage responsedata evaluateresponse to doo method description return to do return description public string get test field return get property as string test field todoo todo gettestfield getpropertyasstring test_field to doo method description return to do return description public int get test type j meter property type get property test type if type instanceof null property return contains return type get int value todoo todo gettesttype jmeterproperty getproperty test_type nullproperty getintvalue to doo method description return to do return description public collection property get test strings return collection property get property test strings todoo todo collectionproperty getteststrings collectionproperty getproperty test_strings public boolean is equals type return get test type equals 0 isequalstype gettesttype public boolean is substring type return get test type substring 0 issubstringtype gettesttype public boolean is contains type return get test type contains 0 iscontainstype gettesttype public boolean is match type return get test type match 0 ismatchtype gettesttype public boolean is not type return get test type not 0 isnottype gettesttype public void set to contains type set test type masked contains settocontainstype settesttypemasked public void set to match type set test type masked match settomatchtype settesttypemasked public void set to equals type set test type masked equals settoequalstype settesttypemasked public void set to substring type set test type masked substring settosubstringtype settesttypemasked public void set to not type set test type get test type not settonottype settesttype gettesttype public void unset not type set test type get test type not unsetnottype settesttype gettesttype public boolean get assume success return get property as boolean assume success false getassumesuccess getpropertyasboolean assume_success public void set assume success boolean b set property assume success b setassumesuccess setproperty assume_success make sure the response satisfies the specified assertion requirements param response an instance of sample result return an instance of assertion result private assertion result evaluate response sample result response boolean pass true boolean not test not get test type 0 assertion result result new assertion result get name string to check the string to check url or data if get assume success response set successful true allow testing of failure codes what are we testing against if is test field response data to check response get response data as string bug25052 else if is test field response code to check response get response code else if is test field response message to check response get response message else if is test field response headers to check response get response headers else assume it is the url to check final url url response geturl if url null to check url to string result set failure false result set error false if to check length 0 if not test return result return result set result for null boolean contains is contains type do it once outside loop boolean equals is equals type boolean substring is substring type boolean matches is match type boolean debug enabled log is debug enabled if debug enabled log debug type contains contains match not test not try get the matcher for this thread perl5 matcher local matcher j meter utils get matcher property iterator iter get test strings iterator while iter has next string string pattern iter next get string value pattern pattern null if contains matches pattern j meter utils get pattern cache get pattern string pattern perl5 compiler read only mask boolean found if contains found local matcher contains to check pattern else if equals found to check equals string pattern else if substring found to check index of string pattern 1 else found local matcher matches to check pattern pass not test found found if pass if debug enabled log debug failed string pattern result set failure true result set failure message get fail text string pattern to check break if debug enabled log debug passed string pattern catch malformed cache pattern exception e result set error true result set failure false result set failure message bad test configuration e return result sampleresult assertionresult assertionresult evaluateresponse sampleresult nottest gettesttype assertionresult assertionresult getname tocheck getassumesuccess setsuccessful istestfieldresponsedata tocheck getresponsedataasstring istestfieldresponsecode tocheck getresponsecode istestfieldresponsemessage tocheck getresponsemessage istestfieldresponseheaders tocheck getresponseheaders tocheck tocheck tostring setfailure seterror tocheck nottest setresultfornull iscontainstype isequalstype issubstringtype ismatchtype debugenabled isdebugenabled debugenabled nottest perl5matcher localmatcher jmeterutils getmatcher propertyiterator getteststrings hasnext stringpattern getstringvalue jmeterutils getpatterncache getpattern stringpattern perl5compiler read_only_mask localmatcher tocheck tocheck stringpattern tocheck indexof stringpattern localmatcher tocheck nottest debugenabled stringpattern setfailure setfailuremessage getfailtext stringpattern tocheck debugenabled stringpattern malformedcachepatternexception seterror setfailure setfailuremessage generate the failure reason from the test type param string pattern return the message for the assertion report todo strings should be resources private string get fail text string string pattern string to check string buffer sb new string buffer 200 sb append test failed if is test field response data sb append text else if is test field response code sb append code else if is test field response message sb append message else if is test field response headers sb append headers else assume it is the url sb append url switch get test type case contains case substring sb append expected to contain break case not contains case not substring sb append expected not to contain break case match sb append expected to match break case not match sb append expected not to match break case equals sb append expected to equal break case not equals sb append expected not to equal break default should never happen sb append expected something using sb append if is equals type sb append equals comparison text to check string pattern else sb append string pattern sb append return sb to string testtype stringpattern getfailtext stringpattern tocheck stringbuffer stringbuffer istestfieldresponsedata istestfieldresponsecode istestfieldresponsemessage istestfieldresponseheaders gettesttype isequalstype equalscomparisontext tocheck stringpattern stringpattern tostring private static string trunc final boolean right final string str if str length equals section diff len return str else if right return str substring 0 equals section diff len equals diff trunc else return equals diff trunc str substring str length equals section diff len str length equals_section_diff_len equals_section_diff_len equals_diff_trunc equals_diff_trunc equals_section_diff_len returns some helpful logging text to determine where equality between two strings is broken with one pointer working from the front of the strings and another working backwards from the end param received string received from sampler param comparison string specified for equals response assertion return two lines of text separated by newlines and then forward and backward pointers denoting first position of difference private static string buffer equals comparison text final string received final string comparison final string buffer text int first diff int last rec diff 1 int last comp diff 1 final int rec length received length final int comp length comparison length final int min length math min rec length comp length final string starting eq seq string rec delta seq string comp delta seq string ending eq seq final string buffer pad text new string buffer math max rec length comp length 2 for first diff 0 first diff min length first diff if received char at first diff comparison char at first diff break if first diff 0 starting eq seq else starting eq seq trunc false received substring 0 first diff last rec diff rec length 1 last comp diff comp length 1 while last rec diff first diff last comp diff first diff received char at last rec diff comparison char at last comp diff last rec diff last comp diff ending eq seq trunc true received substring last rec diff 1 rec length if ending eq seq length 0 rec delta seq trunc true received substring first diff rec length comp delta seq trunc true comparison substring first diff comp length else rec delta seq trunc true received substring first diff last rec diff 1 comp delta seq trunc true comparison substring first diff last comp diff 1 pad new string buffer math abs rec delta seq length comp delta seq length for int i 0 i pad capacity i pad append if rec delta seq length comp delta seq length comp delta seq pad to string else rec delta seq pad to string text append n n text append received str text append starting eq seq text append diff delta start text append rec delta seq text append diff delta end text append ending eq seq text append n n text append comparison str text append starting eq seq text append diff delta start text append comp delta seq text append diff delta end text append ending eq seq text append n n return text stringbuffer equalscomparisontext stringbuffer firstdiff lastrecdiff lastcompdiff reclength complength minlength reclength complength startingeqseq recdeltaseq compdeltaseq endingeqseq stringbuffer stringbuffer reclength complength firstdiff firstdiff minlength firstdiff charat firstdiff charat firstdiff firstdiff startingeqseq startingeqseq firstdiff lastrecdiff reclength lastcompdiff complength lastrecdiff firstdiff lastcompdiff firstdiff charat lastrecdiff charat lastcompdiff lastrecdiff lastcompdiff endingeqseq lastrecdiff reclength endingeqseq recdeltaseq firstdiff reclength compdeltaseq firstdiff complength recdeltaseq firstdiff lastrecdiff compdeltaseq firstdiff lastcompdiff stringbuffer recdeltaseq compdeltaseq recdeltaseq compdeltaseq compdeltaseq tostring recdeltaseq tostring received_str startingeqseq diff_delta_start recdeltaseq diff_delta_end endingeqseq comparison_str startingeqseq diff_delta_start compdeltaseq diff_delta_end endingeqseq public random variable config bean info super random variable config class property descriptor p create property group variable group new string variable name output format p property variable name p set value not undefined boolean true p set value default non nls 1 p property output format p set value not undefined boolean true p set value default non nls 1 create property group random group new string minimum value maximum value random seed p property minimum value p set value not undefined boolean true p set value default 1 non nls 1 p property maximum value p set value not undefined boolean true p set value default non nls 1 p property random seed p set value not undefined boolean true p set value default non nls 1 create property group options group new string per thread p property per thread p set value not undefined boolean true p set value not expression boolean true p set value not other boolean true p set value default boolean false randomvariableconfigbeaninfo randomvariableconfig propertydescriptor createpropertygroup variable_group variable_name output_format variable_name setvalue not_undefined setvalue output_format setvalue not_undefined setvalue createpropertygroup random_group minimum_value maximum_value random_seed minimum_value setvalue not_undefined setvalue maximum_value setvalue not_undefined setvalue random_seed setvalue not_undefined setvalue createpropertygroup options_group per_thread per_thread setvalue not_undefined setvalue not_expression setvalue not_other setvalue public static final string port http mirror control gui port non nls 1 public http mirror control init port default port httpmirrorcontrolgui httpmirrorcontrol initport default_port public http mirror control int port init port port httpmirrorcontrol initport private void init port int port set property new integer property port port initport setproperty integerproperty public void set port int port init port port setport initport public void set port string port set property port port setport setproperty public int get port return get property as int port getport getpropertyasint public string get port string return get property as string port getportstring getpropertyasstring public int get default port return default port getdefaultport default_port public class get gui class return org apache jmeter protocol http control gui http mirror control gui class getguiclass httpmirrorcontrolgui public void start http mirror server new http mirror server get port server start starthttpmirror httpmirrorserver getport public void stop http mirror if server null server stop server try server join 1000 wait for server to stop catch interrupted exception e server null stophttpmirror stopserver interruptedexception public boolean can remove return null server canremove public boolean is server alive return server null server is alive isserveralive isalive constructs the mailer visualizer and initializes its gui public mailer visualizer super set model new mailer result collector initialize gui init gui mailervisualizer mailervisualizer setmodel mailerresultcollector initgui public j panel get control panel return this jpanel getcontrolpanel clears any stored sampling informations public synchronized void clear data if get model null mailer model model mailer result collector get model get mailer model model clear update visualizer model cleardata getmodel mailermodel mailerresultcollector getmodel getmailermodel updatevisualizer public synchronized void add sample result res if get model null mailer model model mailer result collector get model get mailer model model add res this is a different model from the one used by the result collector update visualizer model sampleresult getmodel mailermodel mailerresultcollector getmodel getmailermodel updatevisualizer public string to string return e mail notification tostring initializes the gui lays out components and adds them to the container private void init gui this set layout new border layout main panel j panel main panel new vertical panel border margin new empty border 10 10 5 10 this set border margin name main panel add make title panel mailer panel j panel mailer panel new j panel mailer panel set border border factory create titled border border factory create etched border get attributes title grid bag layout g new grid bag layout mailer panel set layout g grid bag constraints c new grid bag constraints c anchor grid bag constraints northwest c insets new insets 0 0 0 0 c gridwidth 1 mailer panel add new j label from from field new j text field 25 from field set editable true c gridwidth grid bag constraints remainder g set constraints from field c mailer panel add from field c anchor grid bag constraints northwest c insets new insets 0 0 0 0 c gridwidth 1 mailer panel add new j label addressee s address field new j text field 25 address field set editable true c gridwidth grid bag constraints remainder g set constraints address field c mailer panel add address field c gridwidth 1 mailer panel add new j label smtp host smtp host field new j text field 25 smtp host field set editable true c gridwidth grid bag constraints remainder g set constraints smtp host field c mailer panel add smtp host field c gridwidth 1 mailer panel add new j label failure subject failure subject field new j text field 25 failure subject field set editable true c gridwidth grid bag constraints remainder g set constraints failure subject field c mailer panel add failure subject field c gridwidth 1 mailer panel add new j label success subject success subject field new j text field 25 success subject field set editable true c gridwidth grid bag constraints remainder g set constraints success subject field c mailer panel add success subject field c gridwidth 1 mailer panel add new j label failure limit failure limit field new j text field 2 25 failure limit field set editable true c gridwidth grid bag constraints remainder g set constraints failure limit field c mailer panel add failure limit field c gridwidth 1 mailer panel add new j label success limit success limit field new j text field 2 25 success limit field set editable true c gridwidth grid bag constraints remainder g set constraints success limit field c mailer panel add success limit field tester button new j button test mail tester button add action listener this tester button set enabled true c gridwidth 1 g set constraints tester button c mailer panel add tester button c gridwidth 1 mailer panel add new j label failures failure field new j text field 6 failure field set editable false c gridwidth grid bag constraints remainder g set constraints failure field c mailer panel add failure field main panel add mailer panel this add main panel border layout west initgui setlayout borderlayout jpanel mainpanel verticalpanel emptyborder setborder mainpanel maketitlepanel jpanel mailerpanel jpanel mailerpanel setborder borderfactory createtitledborder borderfactory createetchedborder getattributestitle gridbaglayout gridbaglayout mailerpanel setlayout gridbagconstraints gridbagconstraints gridbagconstraints mailerpanel jlabel fromfield jtextfield fromfield seteditable gridbagconstraints setconstraints fromfield mailerpanel fromfield gridbagconstraints mailerpanel jlabel addressfield jtextfield addressfield seteditable gridbagconstraints setconstraints addressfield mailerpanel addressfield mailerpanel jlabel smtphostfield jtextfield smtphostfield seteditable gridbagconstraints setconstraints smtphostfield mailerpanel smtphostfield mailerpanel jlabel failuresubjectfield jtextfield failuresubjectfield seteditable gridbagconstraints setconstraints failuresubjectfield mailerpanel failuresubjectfield mailerpanel jlabel successsubjectfield jtextfield successsubjectfield seteditable gridbagconstraints setconstraints successsubjectfield mailerpanel successsubjectfield mailerpanel jlabel failurelimitfield jtextfield failurelimitfield seteditable gridbagconstraints setconstraints failurelimitfield mailerpanel failurelimitfield mailerpanel jlabel successlimitfield jtextfield successlimitfield seteditable gridbagconstraints setconstraints successlimitfield mailerpanel successlimitfield testerbutton jbutton testerbutton addactionlistener testerbutton setenabled setconstraints testerbutton mailerpanel testerbutton mailerpanel jlabel failurefield jtextfield failurefield seteditable gridbagconstraints setconstraints failurefield mailerpanel failurefield mainpanel mailerpanel mainpanel borderlayout public string get label resource return mailer visualizer title non nls 1 getlabelresource mailer_visualizer_title returns a string for the title of the attributes panel as set up in the properties file using the lookup constant mailer attributes panel return the title of the component public string get attributes title return j meter utils get res string mailer attributes panel non nls 1 mailer_attributes_panel getattributestitle jmeterutils getresstring mailer_attributes_panel reacts on an action event like pressing a button param e the action event with information about the event and its source public void action performed action event e if e get source tester button result collector test element get model modify test element test element try mailer model model mailer result collector test element get mailer model model send test mail display message j meter utils get res string mail sent false non nls 1 catch address exception ex log error invalid mail address ex display message j meter utils get res string invalid mail address non nls 1 n ex get message true non nls 1 catch messaging exception ex log error couldn t send mail ex display message j meter utils get res string invalid mail non nls 1 n ex get message true non nls 1 actionevent actionevent actionperformed actionevent getsource testerbutton resultcollector testelement getmodel modifytestelement testelement mailermodel mailerresultcollector testelement getmailermodel sendtestmail displaymessage jmeterutils getresstring mail_sent addressexception displaymessage jmeterutils getresstring invalid_mail_address getmessage messagingexception displaymessage jmeterutils getresstring invalid_mail getmessage restores mailer visualizer public void configure test element el super configure el update visualizer mailer result collector el get mailer model mailervisualizer testelement updatevisualizer mailerresultcollector getmailermodel makes mailer visualizer storable public test element create test element if get model null set model new mailer result collector modify test element get model return get model mailervisualizer testelement createtestelement getmodel setmodel mailerresultcollector modifytestelement getmodel getmodel public void modify test element test element c super modify test element c mailer model mailer model mailer result collector c get mailer model mailer model set failure limit failure limit field get text mailer model set failure subject failure subject field get text mailer model set from address from field get text mailer model set smtp host smtp host field get text mailer model set success limit success limit field get text mailer model set success subject success subject field get text mailer model set to address address field get text modifytestelement testelement modifytestelement mailermodel mailermodel mailerresultcollector getmailermodel mailermodel setfailurelimit failurelimitfield gettext mailermodel setfailuresubject failuresubjectfield gettext mailermodel setfromaddress fromfield gettext mailermodel setsmtphost smtphostfield gettext mailermodel setsuccesslimit successlimitfield gettext mailermodel setsuccesssubject successsubjectfield gettext mailermodel settoaddress addressfield gettext notifies this visualizer about model changes causes the visualizer to query the model about its new state private void update visualizer mailer model model address field set text model get to address from field set text model get from address smtp host field set text model get smtp host success subject field set text model get success subject failure subject field set text model get failure subject failure limit field set text string value of model get failure limit failure field set text string value of model get failure count success limit field set text string value of model get success limit repaint updatevisualizer mailermodel addressfield settext gettoaddress fromfield settext getfromaddress smtphostfield settext getsmtphost successsubjectfield settext getsuccesssubject failuresubjectfield settext getfailuresubject failurelimitfield settext valueof getfailurelimit failurefield settext valueof getfailurecount successlimitfield settext valueof getsuccesslimit shows a message using a dialog box private void display message string message boolean is error int type 0 if is error type j option pane error message else type j option pane information message j option pane show message dialog null message is error error information type dialogbox displaymessage iserror iserror joptionpane error_message joptionpane information_message joptionpane showmessagedialog iserror public void state changed change event e if e get source instanceof mailer model mailer model test model mailer model e get source update visualizer test model else super state changed e statechanged changeevent getsource mailermodel mailermodel testmodel mailermodel getsource updatevisualizer testmodel statechanged public class test run time extends j meter test case public test run time string name super name testruntime jmetertestcase testruntime public void test processing throws exception run time controller new run time controller set runtime 10 test sampler samp1 new test sampler sample 1 500 test sampler samp2 new test sampler sample 2 490 loop controller sub1 new loop controller sub1 set loops 2 sub1 set continue forever false sub1 add test element samp1 loop controller sub2 new loop controller sub2 set loops 40 sub2 set continue forever false sub2 add test element samp2 controller add test element sub1 controller add test element sub2 controller set running version true sub1 set running version true sub2 set running version true controller initialize sampler sampler null int loops 0 long now system current time millis while sampler controller next null loops sampler sample null long elapsed system current time millis now assert true should be at least 20 loops loops loops 20 assert true should be fewer than 30 loops loops loops 30 assert true should take at least 10 seconds elapsed elapsed 10000 assert true should take less than 12 seconds elapsed elapsed 12000 assert equals sampler 1 should run 2 times 2 samp1 get samples assert true sampler 2 should run 18 times samp2 get samples 18 testprocessing runtime runtime setruntime testsampler testsampler testsampler testsampler loopcontroller loopcontroller setloops setcontinueforever addtestelement loopcontroller loopcontroller setloops setcontinueforever addtestelement addtestelement addtestelement setrunningversion setrunningversion setrunningversion currenttimemillis currenttimemillis asserttrue asserttrue asserttrue asserttrue assertequals getsamples asserttrue getsamples private map var map new hash map public void addj meter variables j meter variables jm vars var map put thread current thread get name jm vars varmap hashmap addjmetervariables jmetervariables jmvars varmap currentthread getname jmvars public j meter variables get variables return j meter variables var map get thread current thread get name jmetervariables getvariables jmetervariables varmap currentthread getname private constructor to prevent instantiation private csv save service csvsaveservice read samples from a file handles quoted strings param filename input file param visualizer where to send the results param result collector the parent collector throws io exception public static void process samples string filename visualizer visualizer result collector result collector throws io exception buffered reader data reader null final boolean errors only result collector is error logging final boolean success only result collector is success only logging try data reader new buffered reader new file reader filename data reader mark 400 enough to read the header column names get the first line and see if it is the header string line data reader read line if line null throw new io exception filename unable to read header line long line number 1 sample save configuration save config csv save service get sample save configuration line filename if save config null not a valid header log info filename does not appear to have a valid header using default configuration save config sample save configuration result collector get save config clone may change the format later data reader reset restart from beginning line number 0 string parts final char delim save config get delimiter char at 0 todo does it matter that an empty line will terminate the loop csv output files should never contain empty lines so probably not if so then need to check whether the reader is at eof while parts csv read file data reader delim length 0 line number sample event event csv save service make result from delimited string parts save config line number if event null final sample result result event get result if result collector is sample wanted result is successful errors only success only visualizer add result finally j orphan utils close quietly data reader resultcollector ioexception processsamples resultcollector resultcollector ioexception bufferedreader datareader errorsonly resultcollector iserrorlogging successonly resultcollector issuccessonlylogging datareader bufferedreader filereader datareader datareader readline ioexception linenumber samplesaveconfiguration saveconfig csvsaveservice getsamplesaveconfiguration saveconfig saveconfig samplesaveconfiguration resultcollector getsaveconfig datareader linenumber saveconfig getdelimiter charat csvreadfile datareader linenumber sampleevent csvsaveservice makeresultfromdelimitedstring saveconfig linenumber sampleresult getresult resultcollector issamplewanted issuccessful errorsonly successonly jorphanutils closequietly datareader make a sample result given a delimited string param input line line from csv file param save config configuration param line number line number for error reporting return sample result deprecated does not handle quoted strings use link process samples string visualizer result collector instead throws j meter error public static sample event make result from delimited string final string input line final sample save configuration save config may be updated final long line number bug 40772 replaced string tokenizer with string split as the former does not return empty tokens the q prefix is needed to ensure that meta characters e g work string parts input line split q save config get delimiter non nls 1 return make result from delimited string parts save config line number sampleresult inputline saveconfig linenumber sampleresult processsamples resultcollector jmetererror sampleevent makeresultfromdelimitedstring inputline samplesaveconfiguration saveconfig linenumber stringtokenizer inputline saveconfig getdelimiter makeresultfromdelimitedstring saveconfig linenumber make a sample result given a set of tokens param parts tokens parsed from the input param save config the save configuration may be updated param line number return the sample result throws j meter error private static sample event make result from delimited string final string parts final sample save configuration save config may be updated final long line number sample result result null string hostname non nls 1 long time stamp 0 long elapsed 0 string text null string field null save the name for error reporting int i 0 try if save config save timestamp field time stamp text parts i if save config print milliseconds try time stamp long parse long text catch number format exception e see if this works log warn e to string method is only ever called from one thread at a time so it s ok to use a static date format date stamp default date format parse text time stamp stamp get time log warn setting date format to default date format string save config set formatter default date format else if save config formatter null date stamp save config formatter parse text time stamp stamp get time else can this happen final string msg unknown timestamp format log warn msg throw new j meter error msg if save config save time field csv elapsed text parts i elapsed long parse long text if save config save sample count result new statistical sample result time stamp elapsed else result new sample result time stamp elapsed if save config save label field label text parts i result set sample label text if save config save code field response code text parts i result set response code text if save config save message field response message text parts i result set response message text if save config save thread name field thread name text parts i result set thread name text if save config save data type field data type text parts i result set data type text if save config save success field successful text parts i result set successful boolean value of text boolean value if save config save assertion results failure message i todo should this be restored if save config save bytes field csv bytes text parts i result set bytes integer parse int text if save config save thread counts field csv thread count1 text parts i result set group threads integer parse int text field csv thread count2 text parts i result set all threads integer parse int text if save config save url i todo should this be restored if save config save file name field csv filename text parts i result set result file name text if save config save latency field csv latency text parts i result set latency long parse long text if save config save encoding field csv encoding text parts i result set encoding and type text if save config save sample count field csv sample count text parts i result set sample count integer parse int text field csv error count text parts i result set error count integer parse int text if save config save hostname field csv hostname hostname parts i if i save config get var count parts length log warn line line number found parts length fields expected i extra fields have been ignored catch number format exception e log warn error parsing field field at line line number e throw new j meter error e catch parse exception e log warn error parsing field field at line line number e throw new j meter error e catch array index out of bounds exception e log warn insufficient columns to parse field field at line line number throw new j meter error e return new sample event result hostname sampleresult saveconfig linenumber jmetererror sampleevent makeresultfromdelimitedstring samplesaveconfiguration saveconfig linenumber sampleresult timestamp saveconfig savetimestamp time_stamp saveconfig printmilliseconds timestamp parselong numberformatexception tostring dateformat default_date_format timestamp gettime default_date_format_string saveconfig setformatter default_date_format saveconfig saveconfig timestamp gettime jmetererror saveconfig savetime csv_elapsed parselong saveconfig savesamplecount statisticalsampleresult timestamp sampleresult timestamp saveconfig savelabel setsamplelabel saveconfig savecode response_code setresponsecode saveconfig savemessage response_message setresponsemessage saveconfig savethreadname thread_name setthreadname saveconfig savedatatype data_type setdatatype saveconfig savesuccess setsuccessful valueof booleanvalue saveconfig saveassertionresultsfailuremessage saveconfig savebytes csv_bytes setbytes parseint saveconfig savethreadcounts csv_thread_count1 setgroupthreads parseint csv_thread_count2 setallthreads parseint saveconfig saveurl saveconfig savefilename csv_filename setresultfilename saveconfig savelatency csv_latency setlatency parselong saveconfig saveencoding csv_encoding setencodingandtype saveconfig savesamplecount csv_sample_count setsamplecount parseint csv_error_count seterrorcount parseint saveconfig savehostname csv_hostname saveconfig getvarcount linenumber numberformatexception linenumber jmetererror parseexception linenumber jmetererror arrayindexoutofboundsexception linenumber jmetererror sampleevent generates the field names for the output file return the field names as a string public static string printable field names to string return printable field names to string saveconfig printablefieldnamestostring printablefieldnamestostring _saveconfig generates the field names for the output file return the field names as a string public static string printable field names to string sample save configuration save config string buffer text new string buffer string delim save config get delimiter if save config save timestamp text append time stamp text append delim if save config save time text append csv elapsed text append delim if save config save label text append label text append delim if save config save code text append response code text append delim if save config save message text append response message text append delim if save config save thread name text append thread name text append delim if save config save data type text append data type text append delim if save config save success text append successful text append delim if save config save assertion results failure message text append failure message text append delim if save config save bytes text append csv bytes text append delim if save config save thread counts text append csv thread count1 text append delim text append csv thread count2 text append delim if save config save url text append csv url text append delim if save config save file name text append csv filename text append delim if save config save latency text append csv latency text append delim if save config save encoding text append csv encoding text append delim if save config save sample count text append csv sample count text append delim text append csv error count text append delim if save config save hostname text append csv hostname text append delim for int i 0 i sample event get var count i text append variable name quote char text append sample event get var name i text append variable name quote char text append delim string result string null int size text length int del size delim length strip off the trailing delimiter if size del size result string text substring 0 size del size else result string text to string return result string printablefieldnamestostring samplesaveconfiguration saveconfig stringbuffer stringbuffer saveconfig getdelimiter saveconfig savetimestamp time_stamp saveconfig savetime csv_elapsed saveconfig savelabel saveconfig savecode response_code saveconfig savemessage response_message saveconfig savethreadname thread_name saveconfig savedatatype data_type saveconfig savesuccess saveconfig saveassertionresultsfailuremessage failure_message saveconfig savebytes csv_bytes saveconfig savethreadcounts csv_thread_count1 csv_thread_count2 saveconfig saveurl csv_url saveconfig savefilename csv_filename saveconfig savelatency csv_latency saveconfig saveencoding csv_encoding saveconfig savesamplecount csv_sample_count csv_error_count saveconfig savehostname csv_hostname sampleevent getvarcount variable_name_quote_char sampleevent getvarname variable_name_quote_char resultstring delsize delsize resultstring delsize resultstring tostring resultstring parse a csv header line param header line from csv file param filename name of file for log message only return config corresponding to the header items found or null if not a header line public static sample save configuration get sample save configuration string header line string filename string parts split header header line saveconfig get delimiter try default delimiter string delim null if parts null perl5 matcher matcher j meter utils get matcher pattern matcher input input new pattern matcher input header line pattern pattern j meter utils get pattern cache this assumes the header names are all single words with no spaces word followed by 0 or more repeats of non word char word where the non word char 2 is the same e g abc def ghi but not abd def ghi get pattern w w w 2 w 2 w non nls 1 last entries may be quoted strings perl5 compiler read only mask if matcher matches input pattern delim matcher get match group 2 parts split header header line delim now validate the result if parts null return null failed to recognise the header we know the column names all exist so create the config sample save configuration save config new sample save configuration false int var count 0 for int i 0 i parts length i string label parts i if is variable name label var count else functor set functor header label methods get label set invoke save config new boolean boolean true if delim null log warn default delimiter saveconfig get delimiter did not work using alternate delim for reading filename save config set delimiter delim save config set var count var count return save config headerline samplesaveconfiguration getsamplesaveconfiguration headerline splitheader headerline _saveconfig getdelimiter perl5matcher jmeterutils getmatcher patternmatcherinput patternmatcherinput headerline jmeterutils getpatterncache getpattern perl5compiler read_only_mask getmatch splitheader headerline samplesaveconfiguration saveconfig samplesaveconfiguration varcount isvariablename varcount headerlabelmethods saveconfig _saveconfig getdelimiter saveconfig setdelimiter saveconfig setvarcount varcount saveconfig private static string split header string header line string delim string parts header line split q delim non nls 1 int previous 1 check if the line is a header for int i 0 i parts length i final string label parts i check for quoted variable names if is variable name label previous integer max value they are always last continue int current header label methods index of label if current 1 return null unknown column name if current previous log warn column header number i 1 name label is out of order return null out of order previous current return parts splitheader headerline headerline isvariablename max_value headerlabelmethods indexof check if the label is a variable name i e is it enclosed in double quotes param label column name from csv file return if the label is enclosed in double quotes private static boolean is variable name final string label return label length 2 label starts with variable name quote char label ends with variable name quote char isvariablename startswith variable_name_quote_char endswith variable_name_quote_char method will save aggregate statistics as csv for now i put it here not sure if it should go in the newer save service instead of here if we ever decide to get rid of this class we ll need to move this method to the new save service param data vector of data rows param writer output file throws io exception public static void savecsv stats vector data file writer writer throws io exception savecsv stats data writer null saveservice ioexception savecsvstats filewriter ioexception savecsvstats method will save aggregate statistics as csv for now i put it here not sure if it should go in the newer save service instead of here if we ever decide to get rid of this class we ll need to move this method to the new save service param data vector of data rows param writer output file param headers header names if non null throws io exception public static void savecsv stats vector data file writer writer string headers throws io exception final char delim final string line sep system get property line separator non nls 1 final char specials new char delim quoting char if headers null for int i 0 i headers length i if i 0 writer write delim writer write quote delimiters headers i specials writer write line sep for int idx 0 idx data size idx vector row vector data element at idx for int idy 0 idy row size idy if idy 0 writer write delim object item row element at idy writer write quote delimiters string value of item specials writer write line sep saveservice ioexception savecsvstats filewriter ioexception line_sep getproperty quoting_char quotedelimiters line_sep elementat elementat quotedelimiters valueof line_sep method saves aggregate statistics as csv from a table model same as link savecsv stats vector file writer string except that there is no need to create a vector containing the data param model table model containing the data param writer output file throws io exception public static void savecsv stats default table model model file writer writer throws io exception final char delim final string line sep system get property line separator non nls 1 final char specials new char delim quoting char final int columns model get column count final int rows model get row count for int i 0 i columns i if i 0 writer write delim writer write quote delimiters model get column name i specials writer write line sep for int row 0 row rows row for int column 0 column columns column if column 0 writer write delim object item model get value at row column writer write quote delimiters string value of item specials writer write line sep savecsvstats filewriter ioexception savecsvstats defaulttablemodel filewriter ioexception line_sep getproperty quoting_char getcolumncount getrowcount quotedelimiters getcolumnname line_sep getvalueat quotedelimiters valueof line_sep convert a result into a string where the fields of the result are separated by the default delimiter param event the sample event to be converted return the separated value representation of the result public static string result to delimited string sample event event return result to delimited string event event get result get save config get delimiter resulttodelimitedstring sampleevent resulttodelimitedstring getresult getsaveconfig getdelimiter convert a result into a string where the fields of the result are separated by a specified string param event the sample event to be converted param delimiter the separation string return the separated value representation of the result public static string result to delimited string sample event event final string delimiter class to handle generating the delimited string adds the delimiter if not the first call quotes any strings that require it final class string quoter final string buffer sb new string buffer private final char specials private boolean add delim public string quoter char delim specials new char delim quoting char char utils cr char utils lf add delim false don t add delimiter first time round private void add delim if add delim sb append specials 0 else add delim true these methods handle parameters that could contain delimiters or quotes public void append string s add delim if s null return sb append quote delimiters s specials public void append object obj append string value of obj these methods handle parameters that cannot contain delimiters or quotes public void append int i add delim sb append i public void append long l add delim sb append l public void append boolean b add delim sb append b public string to string return sb to string string quoter text new string quoter delimiter char at 0 sample result sample event get result sample save configuration save config sample get save config if save config save timestamp if save config print milliseconds text append sample get time stamp else if save config formatter null string stamp save config formatter format new date sample get time stamp text append stamp if save config save time text append sample get time if save config save label text append sample get sample label if save config save code text append sample get response code if save config save message text append sample get response message if save config save thread name text append sample get thread name if save config save data type text append sample get data type if save config save success text append sample is successful if save config save assertion results failure message string message null assertion result results sample get assertion results if results null find the first non null message for int i 0 i results length i message results i get failure message if message null break if message null text append message else text append need to append something so delimiter is added if save config save bytes text append sample get bytes if save config save thread counts text append sample get group threads text append sample get all threads if save config save url text append sample geturl if save config save file name text append sample get result file name if save config save latency text append sample get latency if save config save encoding text append sample get data encoding with default if save config save sample count need both sample and error count to be any use text append sample get sample count text append sample get error count if save config save hostname text append event get hostname for int i 0 i sample event get var count i text append event get var value i return text to string resulttodelimitedstring sampleevent stringquoter stringbuffer stringbuffer adddelim stringquoter quoting_char charutils charutils adddelim adddelim adddelim adddelim adddelim quotedelimiters valueof adddelim adddelim adddelim tostring tostring stringquoter stringquoter charat sampleresult getresult samplesaveconfiguration saveconfig getsaveconfig saveconfig savetimestamp saveconfig printmilliseconds gettimestamp saveconfig saveconfig gettimestamp saveconfig savetime gettime saveconfig savelabel getsamplelabel saveconfig savecode getresponsecode saveconfig savemessage getresponsemessage saveconfig savethreadname getthreadname saveconfig savedatatype getdatatype saveconfig savesuccess issuccessful saveconfig saveassertionresultsfailuremessage assertionresult getassertionresults getfailuremessage saveconfig savebytes getbytes saveconfig savethreadcounts getgroupthreads getallthreads saveconfig saveurl saveconfig savefilename getresultfilename saveconfig savelatency getlatency saveconfig saveencoding getdataencodingwithdefault saveconfig savesamplecount getsamplecount geterrorcount saveconfig savehostname gethostname sampleevent getvarcount getvarvalue tostring private final char specials private boolean add delim public string quoter char delim specials new char delim quoting char char utils cr char utils lf add delim false don t add delimiter first time round adddelim stringquoter quoting_char charutils charutils adddelim private void add delim if add delim sb append specials 0 else add delim true adddelim adddelim adddelim these methods handle parameters that could contain delimiters or quotes public void append string s add delim if s null return sb append quote delimiters s specials adddelim quotedelimiters sb append quote delimiters s specials public void append object obj append string value of obj quotedelimiters valueof these methods handle parameters that cannot contain delimiters or quotes public void append int i add delim sb append i adddelim sb append i public void append long l add delim sb append l adddelim sb append l public void append boolean b add delim sb append b adddelim public string to string return sb to string tostring tostring private static string quote delimiters string input char special chars if string utils contains none input special chars return input string buffer buffer new string buffer input length 10 final char quote special chars 1 buffer append quote for int i 0 i input length i char c input char at i if c quote buffer append quote double the quote char buffer append c buffer append quote return buffer to string quotedelimiters specialchars stringutils containsnone specialchars stringbuffer stringbuffer specialchars charat tostring public static final char quoting char reads from file and splits input into strings according to the delimiter taking note of quoted strings p handles dos crlf unix lf and mac cr line endings equally p n b a blank line is returned as a zero length array whereas is returned as an empty string this is inconsistent param infile input file must support mark 1 param delim delimiter e g comma return array of strings throws io exception also for unexpected quote characters public static string csv read file buffered reader infile char delim throws io exception int ch int state initial list list new array list byte array output stream baos new byte array output stream 200 boolean push false while 1 ch infile read push false switch state case initial if ch quoting char state quoted else if is delim oreol delim ch push true else baos write ch state plain break case plain if ch quoting char baos write ch throw new io exception cannot have quote char in plain field baos to string else if is delim oreol delim ch push true state initial else baos write ch break case quoted if ch quoting char state embeddedquote else baos write ch break case embeddedquote if ch quoting char baos write quoting char doubled quote quote state quoted else if is delim oreol delim ch push true state initial else baos write quoting char throw new io exception cannot have single quote char in quoted field baos to string break switch state if push if ch r remove following n if present infile mark 1 if infile read n infile reset did not find n put the character back string s baos to string list add s baos reset if ch n ch r state quoted break while not eof if ch 1 eof or end of string so collect any remaining data if state quoted throw new io exception state missing trailing quote char in quoted field baos to string do we have some data or a trailing empty field if baos size 0 we have some data push we ve started a field state embeddedquote just seen list add baos to string return string list to array new string list size quoting_char ioexception csvreadfile bufferedreader ioexception arraylist bytearrayoutputstream bytearrayoutputstream quoting_char isdelimoreol quoting_char ioexception tostring isdelimoreol quoting_char quoting_char quoting_char isdelimoreol quoting_char ioexception tostring tostring ioexception tostring tostring toarray private static boolean is delim oreol char delim int ch return ch delim ch n ch r isdelimoreol reads from string and splits into strings according to the delimiter taking note of quoted strings handles dos crlf unix lf and mac cr line endings equally param line input line param delim delimiter e g comma return array of strings throws io exception also for unexpected quote characters public static string csv split string string line char delim throws io exception return csv read file new buffered reader new string reader line delim ioexception csvsplitstring ioexception csvreadfile bufferedreader stringreader constructor for the interleave control object public interleave control interleavecontrol interleavecontrol public void re initialize set first true current returned at least one false search start null still same true skip next false increment iter count recover running version reinitialize setfirst currentreturnedatleastone searchstart stillsame skipnext incrementitercount recoverrunningversion public void set style int style set property new integer property style style setstyle setproperty integerproperty public int get style return get property as int style getstyle getpropertyasint public sampler next if is skip next re initialize return null return super next isskipnext reinitialize protected sampler next isa controller controller controller throws next is null exception sampler sampler controller next if sampler null current returned null controller return next current returned at least one true if get style ignore sub controllers increment current skip next true else search start null return sampler nextisacontroller nextisnullexception currentreturnednull currentreturnedatleastone getstyle ignore_sub_controllers incrementcurrent skipnext searchstart protected sampler next isa sampler sampler element throws next is null exception skip next true increment current return element nextisasampler nextisnullexception skipnext incrementcurrent if the current is null reset and continue searching the search start attribute will break us off when we start a repeat see org apache jmeter control generic controller next is null protected sampler next is null reset current return next searchstart genericcontroller nextisnull nextisnull resetcurrent protected void set current element test element current element throws next is null exception set the position when next is first called and don t overwrite until re initialize is called if search start null search start current element else if search start current element still same we ve gone through the whole list and are now back at the start point of our search re initialize throw new next is null exception setcurrentelement testelement currentelement nextisnullexception reinitialize searchstart searchstart currentelement searchstart currentelement stillsame reinitialize nextisnullexception protected void current returned null controller c if c is done remove current element else if get style use sub controllers increment current currentreturnednull isdone removecurrentelement getstyle use_sub_controllers incrementcurrent return skip next protected boolean is skip next return skip next skipnext isskipnext skipnext param skip next protected void set skip next boolean skip next this skip next skip next skipnext setskipnext skipnext skipnext skipnext protected void increment current if current returned at least one skip next true still same false super increment current incrementcurrent currentreturnedatleastone skipnext stillsame incrementcurrent prevent instantiation since this is a static utility class private gui factory guifactory get an icon which has previously been registered for this class object param element class the class object which we want to get an icon for return the associated icon or null if this class or its superclass has not been registered public static image icon get icon class element class return get icon element class true elementclass imageicon geticon elementclass geticon elementclass get icon disabledicon which has previously been registered for this class object param element class the class object which we want to get an icon for param enabled is icon enabled return the associated icon or null if this class or its superclass has not been registered public static image icon get icon class element class boolean enabled string key element class get name image icon icon image icon enabled icon map get key disabled icon map get key if icon null return icon if element class get superclass null return get icon element class get superclass enabled return null elementclass imageicon geticon elementclass elementclass getname imageicon imageicon icon_map disabled_icon_map elementclass getsuperclass geticon elementclass getsuperclass get a component instance which has previously been registered for this class object param element class the class object which we want to get an instance of return an instance of the class or null if this class or its superclass has not been registered public static j component getgui class element class todo this method doesn t appear to be used string key element class get name j component gui j component gui map get key if gui null return gui if element class get superclass null return getgui element class get superclass return null elementclass jcomponent elementclass elementclass getname jcomponent jcomponent gui_map elementclass getsuperclass elementclass getsuperclass register an icon so that it can later be retrieved via link get icon class the key should match the fully qualified class name for the class used as the parameter when retrieving the icon param key the name which can be used to retrieve this icon later param icon the icon to store public static void register icon string key image icon icon icon map put key icon geticon registericon imageicon icon_map register an icon so that it can later be retrieved via link get icon class the key should match the fully qualified class name for the class used as the parameter when retrieving the icon param key the name which can be used to retrieve this icon later param icon the icon to store public static void register disabled icon string key image icon icon disabled icon map put key icon geticon registerdisabledicon imageicon disabled_icon_map register a gui class so that it can later be retrieved via link getgui class the key should match the fully qualified class name for the class used as the parameter when retrieving the gui param key the name which can be used to retrieve this gui later param gui class the class object for the gui component param test class the class of the objects edited by this gui throws instantiation exception if an instance of the gui class can not be instantiated throws illegal access exception if access rights do not permit an instance of the gui class to be created public static void registergui string key class gui class class test class throws instantiation exception illegal access exception todo this method doesn t appear to be used j metergui component gui if gui class test beangui class gui new test beangui test class else gui j metergui component gui class new instance gui map put key gui guiclass testclass instantiationexception illegalaccessexception guiclass testclass instantiationexception illegalaccessexception jmeterguicomponent guiclass testbeangui testbeangui testclass jmeterguicomponent guiclass newinstance gui_map public url string url u url u url as string u to external form todo improve string version to better match browser behaviour e g do browsers regard http host and http host 80 as the same if so it would be better to reflect this in the string hash code url as string hash code urlstring urlasstring toexternalform hashcode urlasstring hashcode public url string string s url null url as string s hash code url as string hash code urlstring urlasstring hashcode urlasstring hashcode public string to string return url as string tostring urlasstring public url geturl return url public int compare to object o return url as string compare to o to string compareto urlasstring compareto tostring public boolean equals object o return o instanceof url string url as string equals o to string urlstring urlasstring tostring public int hash code return hash code hashcode hashcode private object values public un escape unescape public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception string raw string compound variable values 0 execute return string escape utils unescape java raw string sampleresult previousresult currentsampler invalidvariableexception rawstring compoundvariable stringescapeutils unescapejava rawstring public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters 1 values parameters to array setparameters invalidvariableexception checkparametercount toarray public string get reference key return key getreferencekey public list get argument desc return desc getargumentdesc public object clone try test element cloned element test element this get class new instance property iterator iter property iterator while iter has next cloned element set property j meter property iter next clone cloned element set running version running version return cloned element catch instantiation exception e throw new assertion error e clone should never return null catch illegal access exception e throw new assertion error e clone should never return null testelement clonedelement testelement getclass newinstance propertyiterator propertyiterator hasnext clonedelement setproperty jmeterproperty clonedelement setrunningversion runningversion clonedelement instantiationexception assertionerror illegalaccessexception assertionerror public void clear prop map clear propmap public void remove property string key prop map remove key removeproperty propmap public boolean equals object o if o instanceof abstract test element return abstract test element o prop map equals prop map else return false abstracttestelement abstracttestelement propmap propmap todo temporary hack to avoid unnecessary bug reports for subclasses public int hash code return system identity hash code this hashcode identityhashcode return prop map hash code public void add test element test element el merge in el propmap hashcode addtestelement testelement mergein public void set name string name set property test element name name setname setproperty testelement public string get name return get property as string test element name getname getpropertyasstring testelement public void set comment string comment set property new string property test element comments comment setcomment setproperty stringproperty testelement public string get comment return get property test element comments get string value getcomment getproperty testelement getstringvalue get the named property if it doesn t exist a new null property object is created with the same name and returned public j meter property get property string key j meter property prop j meter property prop map get key if prop null prop new null property key return prop nullproperty jmeterproperty getproperty jmeterproperty jmeterproperty propmap nullproperty public void traverse test element traverser traverser property iterator iter property iterator traverser start test element this while iter has next traverse property traverser iter next traverser end test element this testelementtraverser propertyiterator propertyiterator starttestelement hasnext traverseproperty endtestelement protected void traverse property test element traverser traverser j meter property value traverser start property value if value instanceof test element property test element value get object value traverse traverser else if value instanceof collection property traverse collection collection property value traverser else if value instanceof map property traverse map map property value traverser traverser end property value traverseproperty testelementtraverser jmeterproperty startproperty testelementproperty testelement getobjectvalue collectionproperty traversecollection collectionproperty mapproperty traversemap mapproperty endproperty protected void traverse map map property map test element traverser traverser property iterator iter map value iterator while iter has next traverse property traverser iter next traversemap mapproperty testelementtraverser propertyiterator valueiterator hasnext traverseproperty protected void traverse collection collection property col test element traverser traverser property iterator iter col iterator while iter has next traverse property traverser iter next traversecollection collectionproperty testelementtraverser propertyiterator hasnext traverseproperty public int get property as int string key return get property key get int value getpropertyasint getproperty getintvalue public int get property as int string key int default value j meter property jmp get property key return jmp instanceof null property default value jmp get int value getpropertyasint defaultvalue jmeterproperty getproperty nullproperty defaultvalue getintvalue public boolean get property as boolean string key return get property key get boolean value getpropertyasboolean getproperty getbooleanvalue public boolean get property as boolean string key boolean default val j meter property jmp get property key return jmp instanceof null property default val jmp get boolean value getpropertyasboolean defaultval jmeterproperty getproperty nullproperty defaultval getbooleanvalue public float get property as float string key return get property key get float value getpropertyasfloat getproperty getfloatvalue public long get property as long string key return get property key get long value getpropertyaslong getproperty getlongvalue public double get property as double string key return get property key get double value getpropertyasdouble getproperty getdoublevalue public string get property as string string key return get property key get string value getpropertyasstring getproperty getstringvalue public string get property as string string key string default value j meter property jmp get property key return jmp instanceof null property default value jmp get string value getpropertyasstring defaultvalue jmeterproperty getproperty nullproperty defaultvalue getstringvalue protected void add property j meter property property if is running version set temporary property else clear temporary property j meter property prop get property property get name if prop instanceof null property prop instanceof string property prop get string value equals prop map put property get name property else prop merge in property addproperty jmeterproperty isrunningversion settemporary cleartemporary jmeterproperty getproperty getname nullproperty stringproperty getstringvalue propmap getname mergein protected void clear temporary j meter property property if temporary properties null temporary properties remove property cleartemporary jmeterproperty temporaryproperties temporaryproperties log the properties of the test element see test element set property j meter property protected void log properties if log is debug enabled property iterator iter property iterator while iter has next j meter property prop iter next log debug property prop get name is temp is temporary prop and is a prop get object value testelement setproperty jmeterproperty logproperties isdebugenabled propertyiterator propertyiterator hasnext jmeterproperty getname istemporary getobjectvalue public void set property j meter property property if is running version if get property property get name instanceof null property add property property else get property property get name set object value property get object value else prop map put property get name property setproperty jmeterproperty isrunningversion getproperty getname nullproperty addproperty getproperty getname setobjectvalue getobjectvalue propmap getname public void set property string name string value set property new string property name value setproperty setproperty stringproperty create a string property but only if it is not the default this is intended for use when adding new properties to j meter so that jmx files are not expanded unnecessarily n b must agree with the default applied when reading the property param name property name param value current value param dflt default public void set property string name string value string dflt if dflt equals value remove property name else set property new string property name value jmeter setproperty removeproperty setproperty stringproperty public void set property string name boolean value set property new boolean property name value setproperty setproperty booleanproperty create a boolean property but only if it is not the default this is intended for use when adding new properties to j meter so that jmx files are not expanded unnecessarily n b must agree with the default applied when reading the property param name property name param value current value param dflt default public void set property string name boolean value boolean dflt if value dflt remove property name else set property new boolean property name value jmeter setproperty removeproperty setproperty booleanproperty public void set property string name int value set property new integer property name value setproperty setproperty integerproperty create a boolean property but only if it is not the default this is intended for use when adding new properties to j meter so that jmx files are not expanded unnecessarily n b must agree with the default applied when reading the property param name property name param value current value param dflt default public void set property string name int value int dflt if value dflt remove property name else set property new integer property name value jmeter setproperty removeproperty setproperty integerproperty public property iterator property iterator return new property iterator impl prop map values propertyiterator propertyiterator propertyiteratorimpl propmap protected void merge in test element element property iterator iter element property iterator while iter has next j meter property prop iter next add property prop mergein testelement propertyiterator propertyiterator hasnext jmeterproperty addproperty returns the running version public boolean is running version return running version runningversion isrunningversion runningversion sets the running version param running version the running version to set public void set running version boolean running version this running version running version property iterator iter property iterator while iter has next iter next set running version running version runningversion runningversion runningversion setrunningversion runningversion runningversion runningversion propertyiterator propertyiterator hasnext setrunningversion runningversion public void recover running version iterator iter prop map entry set iterator while iter has next map entry entry map entry iter next j meter property prop j meter property entry get value if is temporary prop iter remove clear temporary prop else prop recover running version this empty temporary recoverrunningversion propmap entryset hasnext jmeterproperty jmeterproperty getvalue istemporary cleartemporary recoverrunningversion emptytemporary protected void empty temporary if temporary properties null temporary properties clear emptytemporary temporaryproperties temporaryproperties public boolean is temporary j meter property property if temporary properties null return false else return temporary properties contains property istemporary jmeterproperty temporaryproperties temporaryproperties public void set temporary j meter property property if temporary properties null temporary properties new linked hash set temporary properties add property if property instanceof multi property property iterator iter multi property property iterator while iter has next set temporary iter next settemporary jmeterproperty temporaryproperties temporaryproperties linkedhashset temporaryproperties multiproperty propertyiterator multiproperty hasnext settemporary return returns the thread context public j meter context get thread context if thread context null only samplers have the thread context set up by j meter thread at present so suppress the warning for now log warn thread context was not set up should only happen in j unit testing new throwable debug thread context j meter context service get context return thread context threadcontext jmetercontext getthreadcontext threadcontext jmeterthread threadcontext junit threadcontext jmetercontextservice getcontext threadcontext param inthread context the thread context to set public void set thread context j meter context inthread context if thread context null if inthread context thread context throw new runtime exception attempting to reset the thread context this thread context inthread context inthreadcontext threadcontext setthreadcontext jmetercontext inthreadcontext threadcontext inthreadcontext threadcontext runtimeexception threadcontext inthreadcontext return returns the thread name public string get thread name return thread name threadname getthreadname threadname param inthread name the thread name to set public void set thread name string inthread name if thread name null if thread name equals inthread name throw new runtime exception attempting to reset the thread name this thread name inthread name inthreadname threadname setthreadname inthreadname threadname threadname inthreadname runtimeexception threadname inthreadname public abstract test element super abstracttestelement default implementation public boolean can remove return true canremove moved from j meter class public boolean is enabled return get property test element enabled instanceof null property get property as boolean test element enabled jmeter isenabled getproperty testelement nullproperty getpropertyasboolean testelement public bean shell server int port string file super serverfile file can be the empty string serverport port beanshellserver for use by the server script static string getprop string s return j meter utils get prop default s s jmeterutils getpropdefault for use by the server script static void setprop string s string v j meter utils getj meter properties set property s v jmeterutils getjmeterproperties setproperty public void run class loader loader thread current thread get context class loader try class interpreter loader load class bsh interpreter non nls 1 object instance interpreter new instance class string string class class object object class method eval interpreter get method eval new class string non nls 1 method set obj interpreter get method set new class string object non nls 1 method set int interpreter get method set new class string int class non nls 1 method source interpreter get method source new class string non nls 1 set obj invoke instance new object t this non nls 1 set int invoke instance new object portnum new integer serverport non nls 1 if serverfile length 0 try source invoke instance new object serverfile catch invocation target exception e1 log warn could not source serverfile throwable t e1 get cause if t null log warn t to string eval invoke instance new object set accessibility true non nls 1 eval invoke instance new object server portnum non nls 1 catch class not found exception e log error beanshell interpreter not found catch exception e log error problem starting bean shell server e classloader currentthread getcontextclassloader loadclass newinstance getmethod setobj getmethod setint getmethod getmethod setobj setint invocationtargetexception getcause tostring setaccessibility classnotfoundexception beanshell default constructor used by new instance call in daemon public proxy newinstance create and configure a new proxy object param client socket the socket connection to the client param target the proxy control which will receive the generated sampler proxy socket client socket proxy control target configure client socket target clientsocket proxycontrol clientsocket proxycontrol clientsocket configure the proxy param client socket the socket connection to the client param target the proxy control which will receive the generated sampler void configure socket clientsocket proxy control target configure clientsocket target null null clientsocket proxycontrol _clientsocket proxycontrol _target _clientsocket _target configure the proxy param clientsocket the socket connection to the client param target the proxy control which will receive the generated sampler param pageencodings reference to the map of deamon with mappings from page urls to encoding used param form encodings encodings reference to the map of deamon with mappings from form action urls to encoding used void configure socket clientsocket proxy control target map pageencodings map formencodings this target target this client socket clientsocket this capture http headers target get capture http headers this https spoof target get https spoof this https spoof match target get https spoof match this page encodings pageencodings this form encodings formencodings _clientsocket _target proxycontrol _pageencodings formencodingsencodings _clientsocket proxycontrol _target _pageencodings _formencodings _target clientsocket _clientsocket capturehttpheaders _target getcapturehttpheaders httpsspoof _target gethttpsspoof httpsspoofmatch _target gethttpsspoofmatch pageencodings _pageencodings formencodings _formencodings main processing method for the proxy object public void run check which http sampler class we should use string http sampler name http sampler factory default classname if target get sampler type name proxy control sampler type http sampler http sampler name http sampler factory http sampler java else if target get sampler type name proxy control sampler type http sampler2 http sampler name http sampler factory http sampler apache instantiate the sampler http sampler base sampler http sampler factory new instance http sampler name http request hdr request new http request hdr sampler sample result result null header manager headers null try request parse new buffered input stream client socket get input stream populate the sampler it is the same sampler as we sent into the constructor of the http request hdr instance above request get sampler page encodings form encodings create a header manager to ensure that the browsers headers are captured and sent to the server headers request get header manager sampler set header manager headers if we are trying to spoof https change the protocol boolean forcedhttps false so we know when to revert if https spoof if https spoof match length 0 string url request get url if url matches https spoof match sampler set protocol http constants protocol https forcedhttps true else sampler set protocol http constants protocol https forcedhttps true sampler thread started needed for http sampler2 result sampler sample if we re dealing with text data and if we re spoofing https replace all occurences of https with http for the client todo also check the match string to restrict the changes further if https spoof sample result text equals result get data type final string enc result get data encoding with default string no https result new string result get response data enc final string https host match https host port and drop default port if present https http constants default https port string non nls 1 non nls 2 no https result no https result replace all https host http 1 non nls 1 result set response data no https result get bytes enc find the page encoding and possibly encodings for forms in the page in the response from the web server string page encoding add page encoding result add form encodings result page encoding write to client result new buffered output stream client socket get output stream forcedhttps catch unknown host exception uhe log warn server not found uhe write error to client http reply hdr form server not found result generate error result result uhe generate result if nec and populate it catch illegal argument exception e log error not implemented probably used https e write error to client http reply hdr form not implemented probably used https instead of http to record https requests see a href http jakarta apache org jmeter usermanual component reference html http proxy server http proxy server documentation a result generate error result result e generate result if nec and populate it catch exception e log error exception when processing sample e write error to client http reply hdr form timeout result generate error result result e generate result if nec and populate it finally if log is debug enabled log debug will deliver sample sampler get name we don t want to store any cookies in the generated test plan if headers null headers remove header named http constants header cookie always remove cookies headers remove header named http constants header authorization always remove authorization remove additional headers for int i 0 i headers to remove length i headers remove header named headers to remove i target deliver sampler sampler new test element capture http headers headers null result try client socket close catch exception e log error e sampler thread finished needed for http sampler2 httpsampler httpsamplername httpsamplerfactory default_classname getsamplertypename proxycontrol sampler_type_http_sampler httpsamplername httpsamplerfactory http_sampler_java getsamplertypename proxycontrol sampler_type_http_sampler2 httpsamplername httpsamplerfactory http_sampler_apache httpsamplerbase httpsamplerfactory newinstance httpsamplername httprequesthdr httprequesthdr sampleresult headermanager bufferedinputstream clientsocket getinputstream httprequesthdr getsampler pageencodings formencodings getheadermanager setheadermanager httpsspoof httpsspoofmatch geturl httpsspoofmatch setprotocol httpconstants protocol_https setprotocol httpconstants protocol_https threadstarted httpsampler2 httpsspoof sampleresult getdatatype getdataencodingwithdefault nohttpsresult getresponsedata https_host httpconstants default_https_port_string nohttpsresult nohttpsresult replaceall https_host setresponsedata nohttpsresult getbytes pageencoding addpageencoding addformencodings pageencoding writetoclient bufferedoutputstream clientsocket getoutputstream unknownhostexception writeerrortoclient httpreplyhdr formservernotfound generateerrorresult illegalargumentexception writeerrortoclient httpreplyhdr formnotimplemented component_reference http_proxy_server generateerrorresult writeerrortoclient httpreplyhdr formtimeout generateerrorresult isdebugenabled getname removeheadernamed httpconstants header_cookie removeheadernamed httpconstants header_authorization headerstoremove removeheadernamed headerstoremove deliversampler testelement capturehttpheaders clientsocket threadfinished httpsampler2 private sample result generate error result sample result result exception e if result null result new sample result result set sample label sample failed result set response message e get message return result sampleresult generateerrorresult sampleresult sampleresult setsamplelabel setresponsemessage getmessage write output to the output stream then flush and close the stream param in bytes the bytes to write param out the output stream to write to param forcedhttps if we changed the protocol to https throws io exception if an io exception occurs while writing private void write to client sample result res output stream out boolean forcedhttps throws io exception try string response headers massage response headers res forcedhttps out write response headers get bytes out write crlf bytes out write res get response data out flush log debug done writing to client catch io exception e log error e throw e finally try out close catch exception ex log warn error while closing socket ex inbytes ioexception ioexception writetoclient sampleresult outputstream ioexception responseheaders massageresponseheaders responseheaders getbytes crlf_bytes getresponsedata ioexception in the event the content was gzipped and unpacked the content encoding header must be removed and the content length header should be corrected the transfer encoding header is also removed if the protocol was changed to https then change any location header back to http param res response param forcedhttps if we changed the protocol to https return updated headers to be sent to client private string massage response headers sample result res boolean forcedhttps string headers res get response headers string header lines headers split new line 0 drop empty trailing content int content length index 1 boolean fix content length forcedhttps for int i 0 i header lines length i string line header lines i string parts line split s 2 non nls 1 if parts length 2 if http constants transfer encoding equals ignore case parts 0 header lines i null we don t want this passed on to browser continue if http constants header content encoding equals ignore case parts 0 http constants encoding gzip equals ignore case parts 1 header lines i null we don t want this passed on to browser fix content length true continue if http constants header content length equals ignore case parts 0 content length index i continue final string https prefix https if forcedhttps http constants header location equals ignore case parts 0 parts 1 substring 0 https prefix length equals ignore case https prefix header lines i header lines i replace first https prefix http continue if fix content length content length index 0 fix the content length header lines content length index http constants header content length res get response data length string buffer sb new string buffer headers length for int i 0 i header lines length i string line header lines i if line null sb append line append crlf string return sb to string massageresponseheaders sampleresult getresponseheaders headerlines new_line contentlengthindex fixcontentlength headerlines headerlines httpconstants transfer_encoding equalsignorecase headerlines httpconstants header_content_encoding equalsignorecase httpconstants encoding_gzip equalsignorecase headerlines fixcontentlength httpconstants header_content_length equalsignorecase contentlengthindex https_prefix httpconstants header_location equalsignorecase https_prefix equalsignorecase https_prefix headerlines headerlines replacefirst https_prefix fixcontentlength contentlengthindex headerlines contentlengthindex httpconstants header_content_length getresponsedata stringbuffer stringbuffer headerlines headerlines crlf_string tostring write an error message to the client the message should be the full http response param message the message to write private void write error to client string message try output stream sock out client socket get output stream data output stream out new data output stream sock out out write bytes message out flush catch exception e log warn exception while writing error e writeerrortoclient outputstream sockout clientsocket getoutputstream dataoutputstream dataoutputstream sockout writebytes add the page encoding of the sample result to the map with page encodings param result the sample result to check return the page encoding found for the sample result or null private string add page encoding sample result result string page encoding conversion utils get encoding from content type result get content type if page encoding null string url without query get url without query result geturl synchronized page encodings page encodings put url without query page encoding return page encoding addpageencoding sampleresult pageencoding conversionutils getencodingfromcontenttype getcontenttype pageencoding urlwithoutquery geturlwithoutquery pageencodings pageencodings urlwithoutquery pageencoding pageencoding add the form encodings for all forms in the sample result param result the sample result to check param page encoding the encoding used for the sample result page private void add form encodings sample result result string page encoding form char set finder finder new form char set finder if result get content type starts with text todo perhaps make more specific than this return no point parsing anything else e g gif try finder add form actions and char set result get response data as string form encodings page encoding catch html parse exception parse exception log debug unable to parse response could not find any form character set encodings pageencoding addformencodings sampleresult pageencoding formcharsetfinder formcharsetfinder getcontenttype startswith addformactionsandcharset getresponsedataasstring formencodings pageencoding htmlparseexception parseexception private string get url without query url url string full url url to string string url without query full url string query url get query if query null get rid of the query and the url without query url without query substring 0 url without query length query length 1 return url without query geturlwithoutquery fullurl tostring urlwithoutquery fullurl getquery urlwithoutquery urlwithoutquery urlwithoutquery urlwithoutquery resets the ssl manager so that we can create a new one with a new keystore public static synchronized void reset ssl manager manager null sslmanager sslmanager public abstract void set context httpurl connection conn setcontext httpurlconnection default implementation of setting the provider protected void set provider provider provider if null provider security add provider provider setprovider addprovider opens and initializes the key store if the password for the key store is not set this method will prompt you to enter it unfortunately there is no password entry field available from j option pane protected jmeter key store get key store if null this key store string default name j meter utils getj meter properties get property user home non nls 1 file separator keystore non nls 1 string file name system get property javax net ssl key store default name log info jmeter key store location file name try if file name ends with p12 file name ends with p12 non nls 1 non nls 2 this key store jmeter key store get instance pkcs12 log info key store created ok type pkcs 12 system set property javax net ssl key store type pkcs12 non nls 1 else this key store jmeter key store get instance jks non nls 1 log info key store created ok type jks catch exception e this key store null throw new runtime exception could not create keystore e get message file input stream file input stream null try file init store new file file name if init store exists file input stream new file input stream init store this key store load file input stream get password log info keystore loaded ok from file found alias key store get alias else log warn keystore file not found loading empty keystore this defaultpw ensure not null this key store load null catch exception e log error problem loading keystore e get message finally j orphan utils close quietly file input stream log debug jmeter key store type this key store get class to string return this key store keystore keystore passwordentryfield joptionpane jmeterkeystore getkeystore keystore defaultname jmeterutils getjmeterproperties getproperty filename getproperty javax_net_ssl_key_store defaultname jmeterkeystore filename filename endswith filename endswith keystore jmeterkeystore getinstance keystore setproperty keystoretype keystore jmeterkeystore getinstance keystore keystore runtimeexception getmessage fileinputstream fileinputstream initstore filename initstore fileinputstream fileinputstream initstore keystore fileinputstream getpassword keystore getalias keystore getmessage jorphanutils closequietly fileinputstream jmeterkeystore keystore getclass tostring keystore private string get password string password this defaultpw if null password if null defaultpw this defaultpw system get property key store password if null defaultpw synchronized this this defaultpw j option pane show input dialog gui package get instance get main frame j meter utils get res string ssl pass prompt non nls 1 j meter utils get res string ssl pass title non nls 1 j option pane question message system set property key store password this defaultpw password this defaultpw system set property key store password password return password getpassword getproperty key_store_password joptionpane showinputdialog guipackage getinstance getmainframe jmeterutils getresstring ssl_pass_prompt jmeterutils getresstring ssl_pass_title joptionpane question_message setproperty key_store_password setproperty key_store_password opens and initializes the trust store there are 3 possibilities no truststore name provided in which case the default java truststore should be used truststore name is provided and loads ok truststore name is provided but is not found or does not load ok in which case an empty truststore is created if the key store object cannot be created then this is currently treated the same as if no truststore name was provided return truststore null use java truststore otherwise the truststore which may be empty if the file could not be loaded protected key store get trust store if truststore loaded truststore loaded true we ve tried string file name system get property ssl trust store if file name null return null log info trust store location file name try this trust store key store get instance jks log info trust store created ok type jks catch exception e this trust store null throw new runtime exception problem creating truststore e get message file input stream file input stream null try file init store new file file name if init store exists file input stream new file input stream init store this trust store load file input stream null log info truststore loaded ok from file else log info truststore file not found loading empty truststore this trust store load null null catch exception e throw new runtime exception can t load trust store e to string finally j orphan utils close quietly file input stream return this trust store truststore keystore keystore gettruststore truststore_loaded truststore_loaded filename getproperty ssl_trust_store filename truststore filename truststore keystore getinstance truststore truststore runtimeexception getmessage fileinputstream fileinputstream initstore filename initstore fileinputstream fileinputstream initstore truststore fileinputstream truststore runtimeexception truststore tostring jorphanutils closequietly fileinputstream truststore protected constructor to remove the possibility of directly instantiating this object create the ssl context and wrap all the x509 key managers with our x509 key manager so that we can choose our alias protected ssl manager sslcontext x509keymanagers x509keymanager sslmanager static accessor for the ssl manager object the ssl manager is a singleton public static final synchronized ssl manager get instance if null ssl manager manager ssl manager manager new jssessl manager ssl manager ssl provider if ssl manager isssl supported string classname null classname org apache jmeter util jssessl manager non nls 1 try class clazz class for name classname constructor con clazz get constructor new class provider class ssl manager manager ssl manager con new instance new object ssl manager ssl provider catch exception e log error could not create ssl manager instance e non nls 1 ssl manager isssl supported false return null return ssl manager manager sslmanager sslmanager sslmanager getinstance sslmanager sslmanager jssesslmanager sslmanager sslprovider sslmanager issslsupported jssesslmanager forname getconstructor sslmanager sslmanager newinstance sslmanager sslprovider sslmanager sslmanager issslsupported sslmanager test whether ssl is supported or not public static final boolean isssl supported return ssl manager isssl supported issslsupported sslmanager issslsupported returns the converter version used to check for possible incompatibilities public static string get version return revision 674365 non nls 1 getversion param arg0 public http result converter mapper arg0 super arg0 httpresultconverter see com thoughtworks xstream converters converter can convert java lang class public boolean can convert class arg0 return http sample result class equals arg0 canconvert canconvert httpsampleresult public void marshal object obj hierarchical stream writer writer marshalling context context http sample result res http sample result obj sample save configuration save res get save config set attributes writer context res save save assertions writer context res save save sub results writer context res save save response headers writer context res save save request headers writer context res save save response data writer context res save save sampler data writer context res save hierarchicalstreamwriter marshallingcontext httpsampleresult httpsampleresult samplesaveconfiguration getsaveconfig setattributes saveassertions savesubresults saveresponseheaders saverequestheaders saveresponsedata savesamplerdata protected void save sampler data hierarchical stream writer writer marshalling context context http sample result res sample save configuration save if save save sampler data res write string writer tag cookies res get cookies write string writer tag method res gethttp method write string writer tag query string res get query string write string writer tag redirect location res get redirect location if save save url write item res geturl context writer savesamplerdata hierarchicalstreamwriter marshallingcontext httpsampleresult samplesaveconfiguration savesamplerdata writestring tag_cookies getcookies writestring tag_method gethttpmethod writestring tag_query_string getquerystring writestring tag_redirect_location getredirectlocation saveurl writeitem public object unmarshal hierarchical stream reader reader unmarshalling context context http sample result res http sample result create collection context get required type retrieve attributes reader context res while reader has more children reader move down object sub item read item reader context res if retrieve item reader context res sub item retrievehttp item reader context res sub item reader move up if we have a file but no data then read the file string result file name res get result file name if result file name length 0 res get response data length 0 read file result file name res return res hierarchicalstreamreader unmarshallingcontext httpsampleresult httpsampleresult createcollection getrequiredtype retrieveattributes hasmorechildren movedown subitem readitem retrieveitem subitem retrievehttpitem subitem moveup resultfilename getresultfilename resultfilename getresponsedata readfile resultfilename protected void retrievehttp item hierarchical stream reader reader unmarshalling context context http sample result res object sub item if sub item instanceof url res seturl url sub item else if reader get node name equals tag cookies res set cookies string sub item else if reader get node name equals tag method res sethttp method string sub item else if reader get node name equals tag query string res set query string string sub item else if reader get node name equals tag redirect location res set redirect location string sub item retrievehttpitem hierarchicalstreamreader unmarshallingcontext httpsampleresult subitem subitem subitem getnodename tag_cookies setcookies subitem getnodename tag_method sethttpmethod subitem getnodename tag_query_string setquerystring subitem getnodename tag_redirect_location setredirectlocation subitem create a new java sampler with the specified initialization parameters param args the initialization parameters public java sampler context arguments args this params args get arguments as map javasampler javasamplercontext getargumentsasmap determine whether or not a value has been specified for the parameter with this name param name the name of the parameter to test return true if the parameter value has been specified false otherwise public boolean contains parameter string name return params contains key name containsparameter containskey get an iterator of the parameter names each entry in the iterator is a string return an iterator of strings listing the names of the parameters which have been specified for this test public iterator get parameter names iterator return params key set iterator getparameternamesiterator keyset get the value of a specific parameter as a string or null if the value was not specified param name the name of the parameter whose value should be retrieved return the value of the parameter or null if the value was not specified public string get parameter string name return get parameter name null getparameter getparameter get the value of a specified parameter as a string or return the specified default value if the value was not specified param name the name of the parameter whose value should be retrieved param default value the default value to return if the value of this parameter was not specified return the value of the parameter or the default value if the parameter was not specified public string get parameter string name string default value if params null params contains key name return default value return string params get name defaultvalue getparameter defaultvalue containskey defaultvalue get the value of a specified parameter as an integer an exception will be thrown if the parameter is not specified or if it is not an integer the value may be specified in decimal hexadecimal or octal as defined by integer decode param name the name of the parameter whose value should be retrieved return the value of the parameter throws number format exception if the parameter is not specified or is not an integer see java lang integer decode java lang string public int get int parameter string name throws number format exception if params null params contains key name throw new number format exception no value for parameter named name return integer decode string params get name int value numberformatexception getintparameter numberformatexception containskey numberformatexception intvalue get the value of a specified parameter as an integer or return the specified default value if the value was not specified or is not an integer a warning will be logged if the value is not an integer the value may be specified in decimal hexadecimal or octal as defined by integer decode param name the name of the parameter whose value should be retrieved param default value the default value to return if the value of this parameter was not specified return the value of the parameter or the default value if the parameter was not specified see java lang integer decode java lang string public int get int parameter string name int default value if params null params contains key name return default value try return integer decode string params get name int value catch number format exception e log warn value for parameter name not an integer params get name using default default value e return default value defaultvalue getintparameter defaultvalue containskey defaultvalue intvalue numberformatexception defaultvalue defaultvalue get the value of a specified parameter as a long an exception will be thrown if the parameter is not specified or if it is not a long the value may be specified in decimal hexadecimal or octal as defined by long decode param name the name of the parameter whose value should be retrieved return the value of the parameter throws number format exception if the parameter is not specified or is not a long see long decode string public long get long parameter string name throws number format exception if params null params contains key name throw new number format exception no value for parameter named name return long decode string params get name long value numberformatexception getlongparameter numberformatexception containskey numberformatexception longvalue get the value of a specified parameter as along or return the specified default value if the value was not specified or is not a long a warning will be logged if the value is not a long the value may be specified in decimal hexadecimal or octal as defined by long decode param name the name of the parameter whose value should be retrieved param default value the default value to return if the value of this parameter was not specified return the value of the parameter or the default value if the parameter was not specified see long decode string public long get long parameter string name long default value if params null params contains key name return default value try return long decode string params get name long value catch number format exception e log warn value for parameter name not a long params get name using default default value e return default value defaultvalue getlongparameter defaultvalue containskey defaultvalue longvalue numberformatexception defaultvalue defaultvalue private static final logger log logging manager get logger for class private x path util super loggingmanager getloggerforclass xpathutil returns a suitable document builder factory caches the factory in case the next caller wants the same options param validate should the parser validate documents param whitespace should the parser eliminate whitespace in element content param namespace should the parser be namespace aware return javax xml parsers document builder factory private static synchronized document builder factory make document builder factory boolean validate boolean whitespace boolean namespace if x path util document builder factory null document builder factory is validating validate document builder factory is namespace aware namespace document builder factory is ignoring element content whitespace whitespace configure the document builder factory document builder factory document builder factory new instance document builder factory set validating validate document builder factory set namespace aware namespace document builder factory set ignoring element content whitespace whitespace return x path util document builder factory documentbuilderfactory documentbuilderfactory makedocumentbuilderfactory xpathutil documentbuilderfactory documentbuilderfactory isvalidating documentbuilderfactory isnamespaceaware documentbuilderfactory isignoringelementcontentwhitespace documentbuilderfactory documentbuilderfactory newinstance documentbuilderfactory setvalidating documentbuilderfactory setnamespaceaware documentbuilderfactory setignoringelementcontentwhitespace xpathutil documentbuilderfactory create a document builder using the make document factory func param validate should the parser validate documents param whitespace should the parser eliminate whitespace in element content param namespace should the parser be namespace aware return document builder throws parser configuration exception public static synchronized document builder make document builder boolean validate boolean whitespace boolean namespace throws parser configuration exception n b the factory is re usable but not necessarily thread safe so the method is synchronized to protect the creation of the builder document builder builder make document builder factory validate whitespace namespace new document builder builder set error handler new my error handler validate false return builder documentbuilder makedocumentfactory parserconfigurationexception documentbuilder makedocumentbuilder parserconfigurationexception documentbuilder makedocumentbuilderfactory newdocumentbuilder seterrorhandler myerrorhandler utility function to get new document param stream document input stream param validate validate document not tidy param whitespace element whitespace not tidy param namespace is namespace aware param tolerant is tolerant i e use the tidy parser return document throws parser configuration exception throws io exception throws sax exception throws tidy exception public static document make document input stream stream boolean validate boolean whitespace boolean namespace boolean tolerant throws parser configuration exception sax exception io exception tidy exception return make document stream validate whitespace namespace tolerant true false false false parserconfigurationexception ioexception saxexception tidyexception makedocument inputstream parserconfigurationexception saxexception ioexception tidyexception makedocument utility function to get new document param stream document input stream param validate validate document not tidy param whitespace element whitespace not tidy param namespace is namespace aware not tidy param tolerant is tolerant i e use the tidy parser param quiet set tidy quiet param show warnings set tidy warnings param report errors throw tidy exception if tidy detects an error return document throws parser configuration exception throws sax exception throws io exception throws tidy exception public static document make document input stream stream boolean validate boolean whitespace boolean namespace boolean tolerant boolean quiet boolean show warnings boolean report errors throws parser configuration exception sax exception io exception tidy exception return make document stream validate whitespace namespace tolerant quiet show warnings report errors false showwarnings report_errors tidyexception parserconfigurationexception saxexception ioexception tidyexception makedocument inputstream showwarnings report_errors parserconfigurationexception saxexception ioexception tidyexception makedocument showwarnings report_errors utility function to get new document param stream document input stream param validate validate document not tidy param whitespace element whitespace not tidy param namespace is namespace aware not tidy param tolerant is tolerant i e use the tidy parser param quiet set tidy quiet param show warnings set tidy warnings param report errors throw tidy exception if tidy detects an error param is xml is document already xml tidy only return document throws parser configuration exception throws sax exception throws io exception throws tidy exception public static document make document input stream stream boolean validate boolean whitespace boolean namespace boolean tolerant boolean quiet boolean show warnings boolean report errors boolean is xml throws parser configuration exception sax exception io exception tidy exception document doc if tolerant doc tidy doc stream quiet show warnings report errors is xml else doc make document builder validate whitespace namespace parse stream return doc showwarnings report_errors tidyexception isxml parserconfigurationexception saxexception ioexception tidyexception makedocument inputstream showwarnings report_errors isxml parserconfigurationexception saxexception ioexception tidyexception tidydoc showwarnings report_errors isxml makedocumentbuilder create a document using tidy param stream input param quiet set tidy quiet param show warnings show tidy warnings param report errors log errors and throw tidy exception param isxml treat document as xml return the document throws tidy exception if a parse error is detected and report errors is true private static document tidy doc input stream stream boolean quiet boolean show warnings boolean report errors boolean isxml throws tidy exception string writer sw new string writer tidy tidy make tidy parser quiet show warnings isxml sw document doc tidy parsedom stream null doc normalize if tidy get parse errors 0 if report errors log error tidy exception sw to string throw new tidy exception tidy get parse errors tidy get parse warnings log warn tidy errors sw to string return doc showwarnings report_errors tidyexception tidyexception parseerror report_errors tidydoc inputstream showwarnings report_errors tidyexception stringwriter stringwriter maketidyparser showwarnings getparseerrors report_errors tidyexception tostring tidyexception getparseerrors getparsewarnings tostring create a tidy parser with the specified settings param quiet set the tidy quiet flag param show warnings show tidy warnings param is xml treat the content as xml param string writer if non null use this for tidy error output return the tidy parser public static tidy make tidy parser boolean quiet boolean show warnings boolean is xml string writer string writer tidy tidy new tidy tidy set char encoding org w3c tidy configuration utf8 tidy set quiet quiet tidy set show warnings show warnings tidy set make clean true tidy set xml tags is xml if string writer null tidy set errout new print writer string writer return tidy showwarnings isxml stringwriter erroroutput maketidyparser showwarnings isxml stringwriter stringwriter setcharencoding setquiet setshowwarnings showwarnings setmakeclean setxmltags isxml stringwriter seterrout printwriter stringwriter my error handler boolean validate boolean tolerate val validate tol tolerate type val val tol tol myerrorhandler public void warning sax parse exception ex throws sax exception log info type type ex if val tol throw new sax exception ex saxparseexception saxexception saxexception public void error sax parse exception ex throws sax exception log warn type type ex if val tol throw new sax exception ex saxparseexception saxexception saxexception public void fatal error sax parse exception ex throws sax exception log error type type ex if val tol throw new sax exception ex fatalerror saxparseexception saxexception saxexception returns the converter version used to check for possible incompatibilities public static string get version return revision 712377 non nls 1 getversion private final mapper class mapper public script wrapper converter mapper class mapper this class mapper class mapper classmapper scriptwrapperconverter classmapper classmapper classmapper see com thoughtworks xstream converters converter can convert java lang class public boolean can convert class arg0 return arg0 equals script wrapper class canconvert canconvert scriptwrapper public void marshal object arg0 hierarchical stream writer writer marshalling context context script wrapper wrap script wrapper arg0 string version save service getversion conversion help set out version version ensure output follows version writer add attribute att version version writer add attribute att properties save service get properties version writer start node class mapper serialized class wrap test plan get class context convert another wrap test plan writer end node hierarchicalstreamwriter marshallingcontext scriptwrapper scriptwrapper saveservice conversionhelp setoutversion addattribute att_version addattribute att_properties saveservice getpropertiesversion startnode classmapper serializedclass testplan getclass convertanother testplan endnode public object unmarshal hierarchical stream reader reader unmarshalling context context script wrapper wrap new script wrapper wrap version reader get attribute att version conversion help set in version wrap version make sure decoding follows input file reader move down catch errors and rethrow as conversion exception so we get location details try wrap test plan hash tree context convert another wrap get next type reader catch no class def found error e throw create conversion exception e catch exception e throw create conversion exception e return wrap hierarchicalstreamreader unmarshallingcontext scriptwrapper scriptwrapper getattribute att_version conversionhelp setinversion movedown conversionexception testplan hashtree convertanother getnexttype noclassdeffounderror createconversionexception createconversionexception private conversion exception create conversion exception throwable e final conversion exception conversion exception new conversion exception e stack trace element ste e get stack trace if ste null for int i 0 i ste length i stack trace element top ste i string class name top get class name if class name starts with org apache jmeter conversion exception add first jmeter class top to string break return conversion exception conversionexception createconversionexception conversionexception conversionexception conversionexception stacktraceelement getstacktrace stacktraceelement classname getclassname classname startswith conversionexception tostring conversionexception protected class get next type hierarchical stream reader reader string class attribute reader get attribute conversion help att class class type if class attribute null type class mapper real class reader get node name else type class mapper real class class attribute return type getnexttype hierarchicalstreamreader classattribute getattribute conversionhelp att_class classattribute classmapper realclass getnodename classmapper realclass classattribute public abstract class jmeter key store process the input stream public abstract void load input stream is string password throws exception jmeterkeystore inputstream public abstract void load input stream is string password throws exception get the ordered certificate chain public abstract x509 certificate get certificate chain inputstream x509certificate getcertificatechain public abstract x509 certificate get certificate chain public abstract string get alias x509certificate getcertificatechain getalias public abstract string get alias return the private key public abstract private key get private key getalias privatekey getprivatekey public abstract private key get private key public static final jmeter key store get instance string type throws exception java 1 4 now handles all keystore types so just use default return new default key store type privatekey getprivatekey jmeterkeystore getinstance defaultkeystore when constructing a new component this takes care of basic tasks like setting up the name panel and assigning the class s static label as the name to start public abstractj meter gui component name panel new name panel comment panel new comment panel init gui abstractjmeterguicomponent namepanel namepanel commentpanel commentpanel initgui provides a default implementation for setting the name property it s unlikely developers will need to override public void set name string name name panel set name name setname namepanel setname provides a default implementation for setting the comment property it s unlikely developers will need to override public void set comment string comment comment panel set text comment setcomment commentpanel settext provides a default implementation for the enabled property it s unlikely developers will need to override public boolean is enabled return enabled isenabled provides a default implementation for the enabled property it s unlikely developers will need to override public void set enabled boolean e log debug setting enabled e enabled e setenabled provides a default implementation for the name property it s unlikely developers will need to override public string get name if get name panel null return get name panel get name return non nls 1 getname getnamepanel getnamepanel getname provides a default implementation for the comment property it s unlikely developers will need to override public string get comment if get comment panel null return get comment panel get text return non nls 1 getcomment getcommentpanel getcommentpanel gettext provides the name panel for extending classes extending classes are free to place it as desired within the component or not at all most components place the name panel automatically by calling link make title panel instead of directly calling this method return a name panel containing the name of this component protected name panel get name panel return name panel namepanel maketitlepanel namepanel namepanel getnamepanel namepanel private comment panel get comment panel return comment panel commentpanel getcommentpanel commentpanel provides a label containing the title for the component subclasses typically place this label at the top of their gui the title is set to the name returned from the component s link j metergui component get static label get static label method most components place this label automatically by calling link make title panel instead of directly calling this method return a j label which subclasses can add to their gui protected component create title label j label title label new j label get static label font cur font title label get font title label set font cur font derive font float cur font get size 4 return title label jmeterguicomponent getstaticlabel getstaticlabel maketitlepanel jlabel createtitlelabel jlabel titlelabel jlabel getstaticlabel curfont titlelabel getfont titlelabel setfont curfont derivefont curfont getsize titlelabel a newly created gui component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui p abstractj meter gui component provides a partial implementation of this method setting the name of the component and its enabled status subclasses should override this method performing their own configuration as needed but also calling this super implementation param element the test element to configure public void configure test element element set name element get name if element get property test element enabled instanceof null property enabled true else enabled element get property as boolean test element enabled get comment panel set text element get comment abstractjmeterguicomponent testelement testelement setname getname getproperty testelement nullproperty getpropertyasboolean testelement getcommentpanel settext getcomment provides a default implementation that resets the name field to the value of get static label reset comment and sets enabled to true your gui may need more things cleared in which case you should override clear the extra fields and still call super clear gui public void clear gui init gui enabled true getstaticlabel cleargui cleargui initgui helper method also used by constructor private void init gui set name get static label comment panel clear gui initgui setname getstaticlabel commentpanel cleargui this provides a convenience for extenders when they implement the link j metergui component modify test element test element method this method will set the name gui class and test class for the created test element it should be called by every extending class when creating modifying test elements as that will best assure consistent behavior param mc the test element being created protected void configure test element test element mc mc set name get name mc set property new string property test element gui class this get class get name mc set property new string property test element test class mc get class get name this stores the state of the test element log debug setting element to enabled enabled mc set property new boolean property test element enabled enabled mc set comment get comment jmeterguicomponent modifytestelement testelement testelement configuretestelement testelement setname getname setproperty stringproperty testelement gui_class getclass getname setproperty stringproperty testelement test_class getclass getname testelement setproperty booleanproperty testelement setcomment getcomment provides a default implementation for the node property it is unlikely developers would need to override this method public void set node tree node node this node node get name panel set node node setnode treenode getnamepanel setnode provides a default implementation for the node property it is unlikely developers would need to override this method protected tree node get node return node treenode getnode create a standard title section for j meter components this includes the title for the component and the name panel allowing the user to change the name for the component this method is typically added to the top of the component at the beginning of the component s init method return a panel containing the component title and name panel protected container make title panel vertical panel title panel new vertical panel title panel add create title label vertical panel content panel new vertical panel content panel set border border factory create etched border content panel add get name panel content panel add get comment panel title panel add content panel return title panel jmeter maketitlepanel verticalpanel titlepanel verticalpanel titlepanel createtitlelabel verticalpanel contentpanel verticalpanel contentpanel setborder borderfactory createetchedborder contentpanel getnamepanel contentpanel getcommentpanel titlepanel contentpanel titlepanel create a top level border which can be added to j meter components components typically set this as their border in their init method it simply provides a nice spacing between the gui components used and the edges of the window in which they appear return a border for j meter components protected border make border return border factory create empty border 10 10 5 10 jmeter jmeter makeborder borderfactory createemptyborder create a scroll panel that sets it s preferred size to it s minimum size explicitly for scroll panes that live inside other scroll panes or within containers that stretch components to fill the area they exist in use this for any component you would put in a scroll pane such as text areas tables j lists etc it is here for convenience and to avoid duplicate code j meter displays best if you follow this custom param comp the component which should be placed inside the scroll pane return a j scroll pane containing the specified component protected j scroll pane make scroll pane component comp j scroll pane pane new j scroll pane comp pane set preferred size pane get minimum size return pane textareas jlists jmeter jscrollpane jscrollpane makescrollpane jscrollpane jscrollpane setpreferredsize getminimumsize create a scroll panel that sets it s preferred size to it s minimum size explicitly for scroll panes that live inside other scroll panes or within containers that stretch components to fill the area they exist in use this for any component you would put in a scroll pane such as text areas tables j lists etc it is here for convenience and to avoid duplicate code j meter displays best if you follow this custom see javax swing scroll pane constants param comp the component which should be placed inside the scroll pane param vertical policy the vertical scroll policy param horizontal policy the horizontal scroll policy return a j scroll pane containing the specified component protected j scroll pane make scroll pane component comp int vertical policy int horizontal policy j scroll pane pane new j scroll pane comp vertical policy horizontal policy pane set preferred size pane get minimum size return pane textareas jlists jmeter scrollpaneconstants verticalpolicy horizontalpolicy jscrollpane jscrollpane makescrollpane verticalpolicy horizontalpolicy jscrollpane jscrollpane verticalpolicy horizontalpolicy setpreferredsize getminimumsize public string get static label return j meter utils get res string get label resource getstaticlabel jmeterutils getresstring getlabelresource public string get doc anchor return get static label replace getdocanchor getstaticlabel _ subclasses need to over ride this method if they wish to return something other than the visualizer itself return this object public j component get printable component return this jcomponent getprintablecomponent create a text file object to handle the named file with the given encoding param filename file to be read written through this object param encoding encoding to be used when reading writing this file public text file file filename string encoding super filename to string set encoding encoding textfile textfile tostring setencoding create a text file object to handle the named file with the platform default encoding param filename file to be read written through this object public text file file filename super filename to string textfile textfile tostring create a text file object to handle the named file with the platform default encoding param filename name of the file to be read written through this object public text file string filename super filename textfile textfile create a text file object to handle the named file with the given encoding param filename name of the file to be read written through this object param encoding encoding to be used when reading writing this file public text file string filename string encoding super filename textfile textfile create the file with the given string as content or replace it s content with the given string if the file already existed param body new content for the file public void set text string body writer writer null try if encoding null writer new file writer this else writer new output stream writer new file output stream this encoding writer write body writer flush catch io exception ioe log error ioe finally j orphan utils close quietly writer settext filewriter outputstreamwriter fileoutputstream ioexception jorphanutils closequietly read the whole file content and return it as a string return the content of the file public string get text string line end system get property line separator non nls 1 string buffer sb new string buffer reader reader null buffered reader br null try if encoding null reader new file reader this else reader new input stream reader new file input stream this encoding br new buffered reader reader string line notnull non nls 1 while line null line br read line if line null sb append line line end catch io exception ioe log error ioe non nls 1 finally j orphan utils close quietly br closes reader as well return sb to string gettext lineend getproperty stringbuffer stringbuffer bufferedreader filereader inputstreamreader fileinputstream bufferedreader readline lineend ioexception jorphanutils closequietly tostring return encoding being used to read write this file public string get encoding return encoding getencoding param string encoding to be used to read write this file public void set encoding string string encoding string setencoding create a new arguments panel as a standalone component public arguments panel table label new j label j meter utils get res string user defined variables non nls 1 standalone true init argumentspanel argumentspanel tablelabel jlabel jmeterutils getresstring user_defined_variables create a new arguments panel as an embedded component using the specified title param label the title for the component public arguments panel string label table label new j label label standalone false init argumentspanel argumentspanel tablelabel jlabel create a new arguments panel with a border and color background param label text for label param bkg background colour public arguments panel string label color bkg table label new j label label this background bkg standalone false init argumentspanel argumentspanel tablelabel jlabel this is the list of menu categories this gui component will be available under return a collection of strings where each element is one of the constants defined in menu factory public collection get menu categories if standalone return super get menu categories return null menufactory getmenucategories getmenucategories public string get label resource return user defined variables non nls 1 getlabelresource user_defined_variables implements j metergui component create test element public test element create test element arguments args new arguments modify test element args return args jmeterguicomponent createtestelement testelement createtestelement modifytestelement implements j metergui component modify test element test element public void modify test element test element args stop table editing iterator model data table model iterator arguments arguments null if args instanceof arguments arguments arguments args arguments clear while model data has next argument arg argument model data next arg set meta data non nls 1 arguments add argument arg this configure test element args jmeterguicomponent modifytestelement testelement modifytestelement testelement stoptableediting modeldata tablemodel modeldata hasnext modeldata setmetadata addargument configuretestelement a newly created component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui param el the test element to configure public void configure test element el super configure el if el instanceof arguments table model clear data property iterator iter arguments el iterator while iter has next argument arg argument iter next get object value table model add row arg check delete status testelement testelement tablemodel cleardata propertyiterator hasnext getobjectvalue tablemodel addrow checkdeletestatus get the table used to enter arguments return the table used to enter arguments protected j table get table return table jtable gettable get the title label for this component return the title label displayed with the table protected j label get table label return table label jlabel gettablelabel tablelabel get the button used to delete rows from the table return the button used to delete rows from the table protected j button get delete button return delete jbutton getdeletebutton get the button used to add rows to the table return the button used to add rows to the table protected j button get add button return add jbutton getaddbutton enable or disable the delete button depending on whether or not there is a row to be deleted protected void check delete status disable delete if there are no rows in the table to delete if table model get row count 0 delete set enabled false else delete set enabled true checkdeletestatus tablemodel getrowcount setenabled setenabled public void clear gui super clear gui clear cleargui cleargui clear all rows from the table t elanjchezhiyan chezhiyan siptech co in public void clear stop table editing table model clear data stoptableediting tablemodel cleardata invoked when an action occurs this implementation supports the add and delete buttons param e the event that has occurred public void action performed action event e string action e get action command if action equals delete delete argument else if action equals add add argument actionperformed actionevent getactioncommand deleteargument addargument remove the currently selected argument from the table protected void delete argument if a table cell is being edited we must cancel the editing before deleting the row if table is editing table cell editor cell editor table get cell editor table get editing row table get editing column cell editor cancel cell editing int row selected table get selected row if row selected 0 table model remove row row selected table model fire table data changed disable delete if there are no rows in the table to delete if table model get row count 0 delete set enabled false table still contains one or more rows so highlight select the appropriate one else int row to select row selected if row selected table model get row count row to select row selected 1 table set row selection interval row to select row to select deleteargument isediting tablecelleditor celleditor getcelleditor geteditingrow geteditingcolumn celleditor cancelcellediting rowselected getselectedrow rowselected tablemodel removerow rowselected tablemodel firetabledatachanged tablemodel getrowcount setenabled rowtoselect rowselected rowselected tablemodel getrowcount rowtoselect rowselected setrowselectioninterval rowtoselect rowtoselect add a new argument row to the table protected void add argument if a table cell is being edited we should accept the current value and stop the editing before adding a new row stop table editing table model add row make new argument enable delete which may already be enabled but it won t hurt delete set enabled true highlight select the appropriate row int row to select table model get row count 1 table set row selection interval row to select row to select addargument stoptableediting tablemodel addrow makenewargument setenabled rowtoselect tablemodel getrowcount setrowselectioninterval rowtoselect rowtoselect create a new argument object return a new argument object protected object make new argument return new argument non nls 1 non nls 2 makenewargument stop any editing that is currently being done on the table this will save any changes that have already been made protected void stop table editing if table is editing table cell editor cell editor table get cell editor table get editing row table get editing column cell editor stop cell editing stoptableediting isediting tablecelleditor celleditor getcelleditor geteditingrow geteditingcolumn celleditor stopcellediting initialize the table model used for the arguments table protected void initialize table model table model new object table model new string column resource names 0 column resource names 1 argument class new functor new functor get name non nls 1 new functor get value non nls 1 new functor new functor set name non nls 1 new functor set value non nls 1 new class string class string class initializetablemodel tablemodel objecttablemodel column_resource_names_0 column_resource_names_1 getname getvalue setname setvalue public static boolean test functors arguments panel instance new arguments panel instance initialize table model return instance table model check functors null instance get class testfunctors argumentspanel argumentspanel initializetablemodel tablemodel checkfunctors getclass resize the table columns to appropriate widths param table the table to resize columns for protected void size columns j table table _table sizecolumns jtable _table create the main gui panel which contains the argument table return the main gui panel private component make main panel initialize table model table new j table table model table get table header set default renderer new header as property renderer table set selection mode list selection model single selection if this background null table set background this background return make scroll pane table makemainpanel initializetablemodel jtable tablemodel gettableheader setdefaultrenderer headeraspropertyrenderer setselectionmode listselectionmodel single_selection setbackground makescrollpane create a panel containing the title label for the table return a panel containing the title label protected component make label panel j panel label panel new j panel new flow layout flow layout center label panel add table label if this background null label panel set background this background return label panel makelabelpanel jpanel labelpanel jpanel flowlayout flowlayout labelpanel tablelabel labelpanel setbackground labelpanel create a panel containing the add and delete buttons return a gui panel containing the buttons private j panel make button panel add new j button j meter utils get res string add non nls 1 add set action command add add set enabled true delete new j button j meter utils get res string delete non nls 1 delete set action command delete check delete status j panel button panel new j panel button panel set border border factory create empty border 0 10 0 10 if this background null button panel set background this background add add action listener this delete add action listener this button panel add add button panel add delete return button panel jpanel makebuttonpanel jbutton jmeterutils getresstring setactioncommand setenabled jbutton jmeterutils getresstring setactioncommand checkdeletestatus jpanel buttonpanel jpanel buttonpanel setborder borderfactory createemptyborder buttonpanel setbackground addactionlistener addactionlistener buttonpanel buttonpanel buttonpanel initialize the components and layout of this component private void init j panel p this if standalone set layout new border layout 0 5 set border make border add make title panel border layout north p new j panel p set layout new border layout p add make label panel border layout north p add make main panel border layout center force a minimum table height of 70 pixels p add box create vertical strut 70 border layout west p add make button panel border layout south if standalone add p border layout center table revalidate size columns table jpanel setlayout borderlayout setborder makeborder maketitlepanel borderlayout jpanel setlayout borderlayout makelabelpanel borderlayout makemainpanel borderlayout createverticalstrut borderlayout makebuttonpanel borderlayout borderlayout sizecolumns string cache value public function property string name compound variable func super name function func cachevalue functionproperty compoundvariable public function property super functionproperty public void set object value object v if v instanceof compound variable is running version function compound variable v else cache value v to string setobjectvalue compoundvariable isrunningversion compoundvariable cachevalue tostring public boolean equals object o if o instanceof function property if function null return function equals j meter property o get object value return false functionproperty jmeterproperty getobjectvalue executes the function and caches the value for the duration of the test iteration if the property is a running version otherwise the raw string representation of the function is provided see j meter property get string value public string get string value j meter context ctx j meter context service get context expensive so do once if is running version ctx is sampling started log debug not running version return raw function string return function get raw parameters if ctx is sampling started return function execute log debug running version executing function int iter ctx get variables null ctx get variables get iteration 1 if iter test iteration test iteration 1 if iter test iteration cache value null test iteration iter cache value function execute return cache value jmeterproperty getstringvalue getstringvalue jmetercontext jmetercontextservice getcontext isrunningversion issamplingstarted getrawparameters issamplingstarted getvariables getvariables getiteration testiteration testiteration testiteration cachevalue testiteration cachevalue cachevalue see j meter property get object value public object get object value return function jmeterproperty getobjectvalue getobjectvalue public object clone function property prop function property super clone prop cache value cache value prop test iteration test iteration prop function function return prop functionproperty functionproperty cachevalue cachevalue testiteration testiteration see j meter property recover running version test element public void recover running version test element owner cache value null jmeterproperty recoverrunningversion testelement recoverrunningversion testelement cachevalue see org apache jmeter gui action command do action action event public void do action action event e string locale component e get source get name locale loc int sep locale index of if sep 0 loc new locale locale substring 0 sep locale substring sep 1 else loc new locale locale log debug changing locale to loc to string try j meter utils set locale loc catch j meter error err j meter utils report error to user err to string doaction actionevent doaction actionevent getsource getname indexof _ tostring jmeterutils setlocale jmetererror jmeterutils reporterrortouser tostring see org apache jmeter gui action command get action names public set get action names return commands getactionnames getactionnames private byte read buffer null j meter context clear0 readbuffer jmetercontext public void clear clear0 private void clear0 variables null previous result null current sampler null previous sampler null sampling started false thread num 0 read buffer null previousresult currentsampler previoussampler samplingstarted threadnum readbuffer gives access to the j meter variables for the current thread return a pointer to the j meter variables public j meter variables get variables return variables jmeter jmeter jmetervariables getvariables a temporary buffer that can be shared between samplers in a thread return the shared read buffer public byte get read buffer if read buffer null read buffer new byte 8192 return read buffer getreadbuffer readbuffer readbuffer readbuffer public void set variables j meter variables vars this variables vars setvariables jmetervariables public sample result get previous result return previous result sampleresult getpreviousresult previousresult public void set previous result sample result result this previous result result setpreviousresult sampleresult previousresult public sampler get current sampler return current sampler getcurrentsampler currentsampler public void set current sampler sampler sampler this previous sampler current sampler this current sampler sampler setcurrentsampler previoussampler currentsampler currentsampler returns the previous sampler return sampler public sampler get previous sampler return previous sampler previoussampler getprevioussampler previoussampler returns the thread num return int public int get thread num return thread num threadnum getthreadnum threadnum sets the thread num param thread num the thread num to set public void set thread num int thread num this thread num thread num threadnum threadnum threadnum setthreadnum threadnum threadnum threadnum public j meter thread get thread return this thread jmeterthread getthread public void set thread j meter thread thread this thread thread setthread jmeterthread public thread group get thread group return this thread group threadgroup getthreadgroup threadgroup public void set thread group thread group threadgrp this thread group threadgrp setthreadgroup threadgroup threadgroup public standardj meter engine get engine return engine standardjmeterengine getengine public void set engine standardj meter engine engine this engine engine setengine standardjmeterengine public boolean is sampling started return sampling started issamplingstarted samplingstarted public void set sampling started boolean b sampling started b setsamplingstarted samplingstarted public j meter menu bar list for recent files menu items file load recent files new linked list lists for remote engines menu items remote engine start new linked list remote engine stop new linked list remote engine exit new linked list remote hosts j orphan utils split j meter utils get prop default remote hosts non nls 1 if remote hosts length 1 remote hosts 0 equals remote hosts new string 0 this get remote items create menu bar j meter utils add locale change listener this jmetermenubar file_load_recent_files linkedlist remote_engine_start linkedlist remote_engine_stop linkedlist remote_engine_exit linkedlist remotehosts jorphanutils jmeterutils getpropdefault remote_hosts remotehosts remotehosts remotehosts getremoteitems createmenubar jmeterutils addlocalechangelistener public void set file save enabled boolean enabled if file save as null file save as set enabled enabled setfilesaveenabled file_save_as file_save_as setenabled public void set file load enabled boolean enabled if file load null file load set enabled enabled if file merge null file merge set enabled enabled setfileloadenabled file_load file_load setenabled file_merge file_merge setenabled public void set file revert enabled boolean enabled if file revert null file revert set enabled enabled setfilerevertenabled file_revert file_revert setenabled public void set project file loaded string file if file load recent files null file null load recent project update recent file menu items file load recent files file setprojectfileloaded file_load_recent_files loadrecentproject updaterecentfilemenuitems file_load_recent_files public void set edit enabled boolean enabled if edit menu null edit menu set enabled enabled seteditenabled editmenu editmenu setenabled does not appear to be used called by main frame set edit add menu but that is not called public void set edit add menu j menu menu if the add menu already exists remove it if edit add null edit menu remove edit add insert the add menu as the first menu item in the edit menu edit add menu edit menu insert edit add 0 mainframe seteditaddmenu seteditaddmenu jmenu edit_add editmenu edit_add edit_add editmenu edit_add called by main frame set edit menu which is called by edit command do action and gui package locale changed public void set edit menu j popup menu menu if menu null edit menu remove all component comps menu get components for int i 0 i comps length i edit menu add comps i edit menu set enabled true else edit menu set enabled false mainframe seteditmenu editcommand doaction guipackage localechanged seteditmenu jpopupmenu editmenu removeall getcomponents editmenu editmenu setenabled editmenu setenabled public void set edit add enabled boolean enabled there was a npe being thrown without the null check here jkb if edit add null edit add set enabled enabled if we are enabling the edit add menu item then we also need to enable the edit menu the edit menu may already be enabled but there s no harm it trying to enable it again if enabled set edit enabled true else if we are disabling the edit add menu item and the edit remove menu item is disabled then we also need to disable the edit menu the java look and feel guidelines say to disable a menu if all menu items are disabled if edit remove is enabled edit menu set enabled false seteditaddenabled edit_add edit_add setenabled seteditenabled edit_remove isenabled editmenu setenabled public void set edit remove enabled boolean enabled edit remove set enabled enabled if we are enabling the edit remove menu item then we also need to enable the edit menu the edit menu may already be enabled but there s no harm it trying to enable it again if enabled set edit enabled true else if we are disabling the edit remove menu item and the edit add menu item is disabled then we also need to disable the edit menu the java look and feel guidelines say to disable a menu if all menu items are disabled if edit add is enabled edit menu set enabled false seteditremoveenabled edit_remove setenabled seteditenabled edit_add isenabled editmenu setenabled creates the menu bar for this application i believe in my heart that this should be defined in a file somewhere but that is for later public void create menu bar make file menu make edit menu make run menu make options menu make help menu this add file menu this add edit menu this add run menu this add options menu this add help menu menubar createmenubar makefilemenu makeeditmenu makerunmenu makeoptionsmenu makehelpmenu filemenu editmenu runmenu optionsmenu helpmenu private void make help menu help menu help menu make menu res help h non nls 1 j menu item context help make menu item res help h action names help key strokes help non nls 1 j menu item what class make menu item res help node w action names what class key strokes what class non nls 1 j menu item set debug make menu item res debug on action names debug on key strokes debug on non nls 1 j menu item reset debug make menu item res debug off action names debug off key strokes debug off non nls 1 help about make menu item res about a action names about non nls 1 help menu add context help help menu add separator help menu add what class help menu add set debug help menu add reset debug help menu add separator help menu add help about makehelpmenu helpmenu makemenures jmenuitem contexthelp makemenuitemres actionnames keystrokes jmenuitem whatclass makemenuitemres help_node actionnames what_class keystrokes what_class jmenuitem setdebug makemenuitemres debug_on actionnames debug_on keystrokes debug_on jmenuitem resetdebug makemenuitemres debug_off actionnames debug_off keystrokes debug_off help_about makemenuitemres actionnames helpmenu contexthelp helpmenu addseparator helpmenu whatclass helpmenu setdebug helpmenu resetdebug helpmenu addseparator helpmenu help_about private void make options menu options menu options menu make menu res option o non nls 1 j menu item function helper make menu item res function dialog menu item f action names functions key strokes functions non nls 1 laf menu make menu res appearance l non nls 1 ui manager look and feel info lafs ui manager get installed look and feels for int i 0 i lafs length i j menu item laf new j menu item lafs i get name laf add action listener action router get instance laf set action command action names laf prefix lafs i get class name laf menu add laf options menu add function helper options menu add laf menu if ssl manager isssl supported ssl manager make menu item res sslmanager s action names ssl manager key strokes ssl manager non nls 1 options menu add ssl manager options menu add make language menu j menu item collapse make menu item res menu collapse all action names collapse all key strokes collapse all non nls 1 options menu add collapse j menu item expand make menu item res menu expand all action names expand all key strokes expand all non nls 1 options menu add expand makeoptionsmenu optionsmenu makemenures jmenuitem functionhelper makemenuitemres function_dialog_menu_item actionnames keystrokes lafmenu makemenures uimanager lookandfeelinfo uimanager getinstalledlookandfeels jmenuitem jmenuitem getname addactionlistener actionrouter getinstance setactioncommand actionnames laf_prefix getclassname lafmenu optionsmenu functionhelper optionsmenu lafmenu sslmanager issslsupported sslmanager makemenuitemres actionnames ssl_manager keystrokes ssl_manager optionsmenu sslmanager optionsmenu makelanguagemenu jmenuitem makemenuitemres menu_collapse_all actionnames collapse_all keystrokes collapse_all optionsmenu jmenuitem makemenuitemres menu_expand_all actionnames expand_all keystrokes expand_all optionsmenu final j menu language menu lang menu helper j menu languagemenu language menu languagemenu jmenu languagemenu langmenuhelper jmenu _languagemenu languagemenu _languagemenu create a language entry from the locale name param locale must also be a valid resource name void add lang string locale string locale string j meter utils get locale string locale j menu item language new j menu item locale string language add action listener action router language set action command action names change language language set name locale this is used by the change language class to define the locale language menu add language addlang localestring jmeterutils getlocalestring jmenuitem jmenuitem localestring addactionlistener actionrouter setactioncommand actionnames change_language setname changelanguage languagemenu generate the list of supported languages return list of languages also used by org apache jmeter resources package test public static string get languages list lang new array list 20 lang add locale english to string en lang add locale french to string fr lang add locale german to string de lang add no non nls 1 lang add pl non nls 1 lang add pt br non nls 1 lang add es non nls 1 lang add tr non nls 1 lang add locale japanese to string ja lang add locale simplified chinese to string zh cn lang add locale traditional chinese to string zh tw final string added locales j meter utils get property locales add if added locales null string add languages added locales split non nls 1 for int i 0 i add languages length i log info adding locale add languages i lang add add languages i return string lang to array new string lang size packagetest getlanguages arraylist tostring tostring tostring pt_br tostring simplified_chinese tostring zh_cn traditional_chinese tostring zh_tw addedlocales jmeterutils getproperty addedlocales addlanguages addedlocales addlanguages addlanguages addlanguages toarray static j menu make language menu final j menu language menu make menu res choose language c non nls 1 lang menu helper lang menu new lang menu helper language menu note the item name is used by change language to create a locale for that language so need to ensure that the language strings are valid if they exist use the locale language constants also need to ensure that the names are valid resource entries too string lang get languages for int i 0 i lang length i lang menu add lang lang i return language menu jmenu makelanguagemenu jmenu languagemenu makemenures choose_language langmenuhelper langmenu langmenuhelper languagemenu changelanguage getlanguages langmenu addlang languagemenu private void make run menu run menu run menu make menu res run r non nls 1 run start make menu item res start s action names action start key strokes action start non nls 1 run stop make menu item res stop t action names action stop key strokes action stop non nls 1 run stop set enabled false run shut make menu item res shutdown y action names action shutdown key strokes action shutdown non nls 1 run shut set enabled false run clear make menu item res clear c action names clear key strokes clear non nls 1 run clearall make menu item res clear all a action names clear all key strokes clear all non nls 1 run menu add run start if remote start null run menu add remote start remote start all make menu item res remote start all action names remote start all key strokes remote start all non nls 1 run menu add remote start all run menu add run stop run menu add run shut if remote stop null run menu add remote stop remote stop all make menu item res remote stop all x action names remote stop all key strokes remote stop all non nls 1 run menu add remote stop all if remote exit null run menu add remote exit remote exit all make menu item res remote exit all action names remote exit all non nls 1 run menu add remote exit all run menu add separator run menu add run clear run menu add run clearall makerunmenu runmenu makemenures run_start makemenuitemres actionnames action_start keystrokes action_start run_stop makemenuitemres actionnames action_stop keystrokes action_stop run_stop setenabled run_shut makemenuitemres actionnames action_shutdown keystrokes action_shutdown run_shut setenabled run_clear makemenuitemres actionnames keystrokes run_clearall makemenuitemres clear_all actionnames clear_all keystrokes clear_all runmenu run_start remote_start runmenu remote_start remote_start_all makemenuitemres remote_start_all actionnames remote_start_all keystrokes remote_start_all runmenu remote_start_all runmenu run_stop runmenu run_shut remote_stop runmenu remote_stop remote_stop_all makemenuitemres remote_stop_all actionnames remote_stop_all keystrokes remote_stop_all runmenu remote_stop_all remote_exit runmenu remote_exit remote_exit_all makemenuitemres remote_exit_all actionnames remote_exit_all runmenu remote_exit_all runmenu addseparator runmenu run_clear runmenu run_clearall private void make edit menu edit menu edit menu make menu res edit e non nls 1 from the java look and feel guidelines if all items in a menu are disabled then disable the menu makes sense edit menu set enabled false makeeditmenu editmenu makemenures editmenu setenabled private void make file menu file menu file menu make menu res file f non nls 1 j menu item file save make menu item res save s action names save key strokes save non nls 1 file save set enabled true file save as make menu item res save all as a action names save all as key strokes save all as non nls 1 file save as set enabled true file selection as make menu item res save as action names save as non nls 1 file selection as set enabled true file revert make menu item res revert project r action names revert project non nls 1 file revert set enabled false file load make menu item res menu open o action names open key strokes open non nls 1 set default save menu item to disabled since the default node that is selected is root which does not allow items to be inserted file load set enabled false file close make menu item res menu close c action names close key strokes close non nls 1 file exit make menu item res exit x action names exit key strokes exit non nls 1 file merge make menu item res menu merge m action names merge non nls 1 file merge set accelerator key stroke get key stroke key event vk o key event ctrl mask set default save menu item to disabled since the default node that is selected is root which does not allow items to be inserted file merge set enabled false file menu add file close file menu add file load file menu add file merge file menu add separator file menu add file save file menu add file save as file menu add file selection as file menu add file revert file menu add separator add the recent files which will also add a separator that is visible when needed file load recent files load recent project get recent file menu items for iterator i file load recent files iterator i has next file menu add j component i next file menu add file exit makefilemenu filemenu makemenures jmenuitem file_save makemenuitemres actionnames keystrokes file_save setenabled file_save_as makemenuitemres save_all_as actionnames save_all_as keystrokes save_all_as file_save_as setenabled file_selection_as makemenuitemres save_as actionnames save_as file_selection_as setenabled file_revert makemenuitemres revert_project actionnames revert_project file_revert setenabled file_load makemenuitemres menu_open actionnames keystrokes file_load setenabled file_close makemenuitemres menu_close actionnames keystrokes file_exit makemenuitemres actionnames keystrokes file_merge makemenuitemres menu_merge actionnames file_merge setaccelerator keystroke getkeystroke keyevent vk_o keyevent ctrl_mask file_merge setenabled filemenu file_close filemenu file_load filemenu file_merge filemenu addseparator filemenu file_save filemenu file_save_as filemenu file_selection_as filemenu file_revert filemenu addseparator file_load_recent_files loadrecentproject getrecentfilemenuitems file_load_recent_files hasnext filemenu jcomponent filemenu file_exit public void set running boolean running string host log info set running running host iterator iter remote engine start iterator iterator iter2 remote engine stop iterator iterator iter3 remote engine exit iterator while iter has next iter2 has next iter3 has next j menu item start j menu item iter next j menu item stop j menu item iter2 next j menu item exit j menu item iter3 next if start get text equals host log debug found start host start get text start set enabled running if stop get text equals host log debug found stop host stop get text stop set enabled running if exit get text equals host log debug found exit host exit get text exit set enabled true setrunning setrunning remote_engine_start remote_engine_stop remote_engine_exit hasnext hasnext hasnext jmenuitem jmenuitem jmenuitem jmenuitem jmenuitem jmenuitem gettext gettext setenabled gettext gettext setenabled gettext gettext setenabled public void set enabled boolean enable run start set enabled enable run stop set enabled enable run shut set enabled enable setenabled run_start setenabled run_stop setenabled run_shut setenabled private void get remote items if remote hosts length 0 remote start make menu res remote start non nls 1 remote stop make menu res remote stop non nls 1 remote exit make menu res remote exit non nls 1 for int i 0 i remote hosts length i remote hosts i remote hosts i trim j menu item item make menu item no res remote hosts i action names remote start remote engine start add item remote start add item item make menu item no res remote hosts i action names remote stop item set enabled false remote engine stop add item remote stop add item item make menu item no res remote hosts i action names remote exit item set enabled false remote engine exit add item remote exit add item getremoteitems remotehosts remote_start makemenures remote_start remote_stop makemenures remote_stop remote_exit makemenures remote_exit remotehosts remotehosts remotehosts jmenuitem makemenuitemnores remotehosts actionnames remote_start remote_engine_start remote_start makemenuitemnores remotehosts actionnames remote_stop setenabled remote_engine_stop remote_stop makemenuitemnores remotehosts actionnames remote_exit setenabled remote_engine_exit remote_exit processes a locale change notification changes the texts in all menus to the new language public void locale changed locale change event event update menu element file menu update menu element edit menu update menu element run menu update menu element options menu update menu element help menu localechanged localechangeevent updatemenuelement filemenu updatemenuelement editmenu updatemenuelement runmenu updatemenuelement optionsmenu updatemenuelement helpmenu p refreshes all texts in the menu and all submenus to a new locale p p assumes that the item name is set to the resource key so the resource can be retrieved certain action types do not follow this rule see j meter menu bar is not resource string p the language change event assumes that the name is the same as the locale name so this additionally means that all supported locales must be defined as resources private void update menu element menu element menu component component menu get component final string comp name component get name if comp name null if component instanceof j menu final j menu j menu j menu component if is resource j menu get action command j menu set text j meter utils get res string comp name else final j menu item j menu item j menu item component if is resource j menu item get action command j menu item set text j meter utils get res string comp name else if action names change language equals j menu item get action command j menu item set text j meter utils get locale string comp name menu element subelements menu get sub elements for int i 0 i subelements length i update menu element subelements i jmetermenubar isnotresource updatemenuelement menuelement getcomponent compname getname compname jmenu jmenu jmenu jmenu isresource jmenu getactioncommand jmenu settext jmeterutils getresstring compname jmenuitem jmenuitem jmenuitem isresource jmenuitem getactioncommand jmenuitem settext jmeterutils getresstring compname actionnames change_language jmenuitem getactioncommand jmenuitem settext jmeterutils getlocalestring compname menuelement getsubelements updatemenuelement return true if component name is a resource br i e it is not a hostname br tt action names remote start tt br tt action names remote stop tt br tt action names remote exit tt br nor a filename br tt action names open recent tt nor a look and feel prefix br tt action names laf prefix tt private static boolean is resource string action command if action names change language equals action command return false if action names add equals action command return false if action names remote start equals action command return false if action names remote stop equals action command return false if action names remote exit equals action command return false if action names open recent equals action command return false if action command null action command starts with action names laf prefix return false return true actionnames remote_start actionnames remote_stop actionnames remote_exit actionnames open_recent actionnames laf_prefix isresource actioncommand actionnames change_language actioncommand actionnames actioncommand actionnames remote_start actioncommand actionnames remote_stop actioncommand actionnames remote_exit actioncommand actionnames open_recent actioncommand actioncommand actioncommand startswith actionnames laf_prefix make a menu from a resource string param resource used to name menu and set text return the menu private static j menu make menu res string resource j menu menu new j menu j meter utils get res string resource menu set name resource return menu jmenu makemenures jmenu jmenu jmeterutils getresstring setname make a menu from a resource string and set its mnemonic param resource param mnemonic return the menu private static j menu make menu res string resource int mnemonic j menu menu make menu res resource menu set mnemonic mnemonic return menu jmenu makemenures jmenu makemenures setmnemonic make a menu item using a fixed label which is also used as the item name this is used for items such as recent files and hostnames which are not resources param label this is not used as a resource key param action command return the menu item private static j menu item make menu item no res string label string action command j menu item menu item new j menu item label menu item set name label menu item set action command action command menu item add action listener action router get instance return menu item menuitem actioncommand jmenuitem makemenuitemnores actioncommand jmenuitem menuitem jmenuitem menuitem setname menuitem setactioncommand actioncommand menuitem addactionlistener actionrouter getinstance menuitem private static j menu item make menu item res string resource string action command return make menu item res resource key event vk undefined action command null jmenuitem makemenuitemres actioncommand makemenuitemres keyevent vk_undefined actioncommand private static j menu item make menu item res string resource string action command key stroke key stroke return make menu item res resource key event vk undefined action command key stroke jmenuitem makemenuitemres actioncommand keystroke keystroke makemenuitemres keyevent vk_undefined actioncommand keystroke private static j menu item make menu item res string resource int mnemonic string action command return make menu item res resource mnemonic action command null jmenuitem makemenuitemres actioncommand makemenuitemres actioncommand private static j menu item make menu item res string resource int mnemonic string action command key stroke key stroke j menu item menu item new j menu item j meter utils get res string resource mnemonic menu item set name resource menu item set action command action command menu item set accelerator key stroke menu item add action listener action router get instance return menu item jmenuitem makemenuitemres actioncommand keystroke keystroke jmenuitem menuitem jmenuitem jmeterutils getresstring menuitem setname menuitem setactioncommand actioncommand menuitem setaccelerator keystroke menuitem addactionlistener actionrouter getinstance menuitem private constructor to permit instantiation only from within this class use link get instance to retrieve a singleton instance private gui package j meter utils add locale change listener this getinstance guipackage jmeterutils addlocalechangelistener retrieve the singleton gui package instance return the gui package instance public static gui package get instance return gui pack guipackage guipackage guipackage getinstance guipack when gui package is requested for the first time it should be given handles to j meter s tree listener and tree model param listener the tree listener for j meter s test tree param tree model the model for j meter s test tree return gui package public static gui package get instance j meter tree listener listener j meter tree model tree model if gui pack null gui pack new gui package gui pack set tree listener listener gui pack set tree model tree model return gui pack guipackage jmeter treemodel treelistener jmeter treemodel jmeter guipackage guipackage getinstance jmetertreelistener jmetertreemodel treemodel guipack guipack guipackage guipack settreelistener guipack settreemodel treemodel guipack get a j metergui component for the specified test element if the gui has already been created that instance will be returned otherwise if a gui component of the same type has been created and the component is not marked as an link unshared component that shared component will be returned otherwise a new instance of the component will be created the test element s gui class property will be used to determine the appropriate type of gui component to use param node the test element which this gui is being created for return the gui component corresponding to the specified test element public j metergui component get gui test element node string test class name node get property as string test element test class string gui class name node get property as string test element gui class try class test class if test class name equals non nls 1 test class node get class else test class class for name test class name class gui class null if gui class name equals non nls 1 gui class class for name gui class name return get gui node gui class test class catch class not found exception e log error could not get gui for node e return null jmeterguicomponent unsharedcomponent testelement gui_class jmeterguicomponent getgui testelement testclassname getpropertyasstring testelement test_class guiclassname getpropertyasstring testelement gui_class testclass testclassname testclass getclass testclass forname testclassname guiclass guiclassname guiclass forname guiclassname getgui guiclass testclass classnotfoundexception get a j metergui component for the specified test element if the gui has already been created that instance will be returned otherwise if a gui component of the same type has been created and the component is not marked as an link unshared component that shared component will be returned otherwise a new instance of the component will be created param node the test element which this gui is being created for param gui class the fully qualifed class name of the gui component which will be created if it doesn t already exist param test class the fully qualifed class name of the test elements which have to be edited by the returned gui component return the gui component corresponding to the specified test element public j metergui component get gui test element node class gui class class test class try j metergui component comp j metergui component nodes to gui get node if comp null comp get gui from cache gui class test class nodes to gui put node comp log debug gui retrieved comp return comp catch exception e log error problem retrieving gui e return null jmeterguicomponent unsharedcomponent guiclass testclass jmeterguicomponent getgui testelement guiclass testclass jmeterguicomponent jmeterguicomponent nodestogui getguifromcache guiclass testclass nodestogui remove a test element from the tree this removes the reference to any associated gui component param node the test element being removed public void remove node test element node nodes to gui remove node removenode testelement nodestogui convenience method for grabbing the gui for the current node return the gui component associated with the currently selected node public j metergui component get current gui try update current node test element cur node tree listener get current node get test element j metergui component comp get gui cur node comp clear gui log debug updating gui to new node comp configure cur node current node updated false return comp catch exception e log error problem retrieving gui e return null jmeterguicomponent getcurrentgui updatecurrentnode testelement curnode treelistener getcurrentnode gettestelement jmeterguicomponent getgui curnode cleargui curnode currentnodeupdated find the j meter tree node for a certain test element object param user object the test element to search for return the tree node associated with the test element public j meter tree node get node of test element user object return tree model get node of user object jmetertreenode testelement userobject jmetertreenode getnodeof testelement userobject treemodel getnodeof userobject create a test element corresponding to the specified gui class param gui class the fully qualified class name of the gui component or a test bean class for test beangu is param test class the fully qualified class name of the test elements edited by this gui component return the test element corresponding to the specified gui class public test element create test element class gui class class test class try j metergui component comp get gui from cache gui class test class comp clear gui test element node comp create test element nodes to gui put node comp return node catch exception e log error problem retrieving gui e return null testelement guiclass testbean testbeanguis testclass testelement createtestelement guiclass testclass jmeterguicomponent getguifromcache guiclass testclass cleargui testelement createtestelement nodestogui create a test element for a gui or test bean class p this is a utility method to help actions do with one single string parameter param obj class the fully qualified class name of the gui component or of the test bean subclass for which a test beangui is wanted return the test element corresponding to the specified gui class public test element create test element string obj class j metergui component comp class c try c class for name obj class if test bean class is assignable from c comp get gui from cache test beangui class c else comp get gui from cache c null comp clear gui test element node comp create test element nodes to gui put node comp return node catch no class def found error e log error problem retrieving gui for obj class e string msg cannot find class e get message j option pane show message dialog null msg missing jar see log file j option pane error message throw new runtime exception e to string probably a missing jar catch class not found exception e log error problem retrieving gui for obj class e throw new runtime exception e to string programming error bail out catch instantiation exception e log error problem retrieving gui for obj class e throw new runtime exception e to string programming error bail out catch illegal access exception e log error problem retrieving gui for obj class e throw new runtime exception e to string programming error bail out testelement testbean objclass testbean testbeangui testelement createtestelement objclass jmeterguicomponent forname objclass testbean isassignablefrom getguifromcache testbeangui getguifromcache cleargui testelement createtestelement nodestogui noclassdeffounderror objclass getmessage joptionpane showmessagedialog joptionpane error_message runtimeexception tostring classnotfoundexception objclass runtimeexception tostring instantiationexception objclass runtimeexception tostring illegalaccessexception objclass runtimeexception tostring get an instance of the specified j metergui component class if an instance of the gui class has previously been created and it is not marked as an link unshared component that shared instance will be returned otherwise a new instance of the component will be created and shared components will be cached for future retrieval param gui class the fully qualified class name of the gui component this class must implement j metergui component param test class the fully qualified class name of the test elements edited by this gui component this class must implement test element return an instance of the specified class throws instantiation exception if an instance of the object cannot be created throws illegal access exception if access rights do not allow the default constructor to be called throws class not found exception if the specified gui class cannot be found private j metergui component get gui from cache class gui class class test class throws instantiation exception illegal access exception j metergui component comp if gui class test beangui class comp test beangui test beangu is get test class if comp null comp new test beangui test class test beangu is put test class comp else comp j metergui component guis get gui class if comp null comp j metergui component gui class new instance if comp instanceof unshared component guis put gui class comp return comp jmeterguicomponent unsharedcomponent guiclass jmeterguicomponent testclass testelement instantiationexception illegalaccessexception classnotfoundexception jmeterguicomponent getguifromcache guiclass testclass instantiationexception illegalaccessexception jmeterguicomponent guiclass testbeangui testbeangui testbeanguis testclass testbeangui testclass testbeanguis testclass jmeterguicomponent guiclass jmeterguicomponent guiclass newinstance unsharedcomponent guiclass update the gui for the currently selected node the gui component is configured to reflect the settings in the current tree node public void update current gui update current node current node tree listener get current node test element element current node get test element j metergui component comp get gui element comp configure element current node updated false updatecurrentgui updatecurrentnode currentnode treelistener getcurrentnode testelement currentnode gettestelement jmeterguicomponent getgui currentnodeupdated this method should be called in order for gui package to change the current node this will save any changes made to the earlier node before choosing the new node public void update current node try if current node null current node updated log debug updating current node current node get name j metergui component comp get gui current node get test element test element el current node get test element comp modify test element el the current node is now updated current node updated true current node tree listener get current node catch exception e log error problem retrieving gui e guipackage updatecurrentnode currentnode currentnodeupdated currentnode getname jmeterguicomponent getgui currentnode gettestelement testelement currentnode gettestelement modifytestelement currentnodeupdated currentnode treelistener getcurrentnode public j meter tree node get current node return tree listener get current node jmetertreenode getcurrentnode treelistener getcurrentnode public test element get current element return get current node get test element testelement getcurrentelement getcurrentnode gettestelement the dirty property is a flag that indicates whether there are parts of j meter s test tree that the user has not saved since last modification various link command actions set this property when components are modified created saved param dirty the new value of the dirty flag public void set dirty boolean dirty this dirty dirty jmeter setdirty retrieves the state of the dirty property a flag that indicates if there are test tree components that have been modified since they were last saved return true if some tree components have been modified since they were last saved false otherwise public boolean is dirty return dirty isdirty add a subtree to the currently selected node param sub tree the subtree to add return the resulting subtree starting with the currently selected node throws illegal user action exception if a subtree cannot be added to the currently selected node public hash tree add sub tree hash tree sub tree throws illegal user action exception return tree model add sub tree sub tree tree listener get current node subtree illegaluseractionexception hashtree addsubtree hashtree subtree illegaluseractionexception treemodel addsubtree subtree treelistener getcurrentnode get the currently selected subtree return the subtree of the currently selected node public hash tree get current sub tree return tree model get current sub tree tree listener get current node hashtree getcurrentsubtree treemodel getcurrentsubtree treelistener getcurrentnode get the model for j meter s test tree return the j meter tree model todo consider removing this method and providing method wrappers instead this would allow the gui package to do any additional clearups if required as has been done with clear test plan public j meter tree model get tree model return tree model jmeter jmeter cleartestplan jmetertreemodel gettreemodel treemodel set the model for j meter s test tree param new tree model the new j meter tree model public void set tree model j meter tree model new tree model tree model new tree model jmeter newtreemodel jmeter settreemodel jmetertreemodel newtreemodel treemodel newtreemodel get a value replacer for the test tree return a value replacer configured for the test tree public value replacer get replacer return new value replacer test plan j meter tree node get tree model get test plan get array 0 get test element valuereplacer valuereplacer valuereplacer getreplacer valuereplacer testplan jmetertreenode gettreemodel gettestplan getarray gettestelement set the main j meter frame param new main frame the new j meter main frame public void set main frame main frame new main frame main frame new main frame jmeter newmainframe jmeter setmainframe mainframe newmainframe mainframe newmainframe get the main j meter frame return the main j meter frame public main frame get main frame return main frame jmeter jmeter mainframe getmainframe mainframe set the listener for j meter s test tree param new tree listener the new j meter test tree listener public void set tree listener j meter tree listener new tree listener tree listener new tree listener jmeter newtreelistener jmeter settreelistener jmetertreelistener newtreelistener treelistener newtreelistener get the listener for j meter s test tree return the j meter test tree listener public j meter tree listener get tree listener return tree listener jmeter jmeter jmetertreelistener gettreelistener treelistener display the specified popup menu with the source component and location from the specified mouse event param e the mouse event causing this popup to be displayed param popup the popup menu to display public void display pop up mouse event e j popup menu popup display pop up component e get source e popup displaypopup mouseevent jpopupmenu displaypopup getsource display the specified popup menu at the location specified by a mouse event with the specified source component param invoker the source component param e the mouse event causing this popup to be displayed param popup the popup menu to display public void display pop up component invoker mouse event e j popup menu popup if popup null log debug showing pop up for invoker at x y e getx e gety popup pack popup show invoker e getx e gety popup set visible true popup request focus displaypopup mouseevent jpopupmenu setvisible requestfocus public void locale changed locale change event event f irst make sure we save the content of the current gui since we will flush it away update current node forget about all gu is we ve created so far we ll need to re created them all guis new hash map nodes to gui new hash map test beangu is new hash map bean info objects also contain locale sensitive data flush them away introspector flush caches now put the current gui in place this code was copied from the edit command action we can t just trigger the action because that would populate the current node with the contents of the new gui which is empty main frame mf get main frame fetch once if mf null probably caused by unit testing on headless system log warn mainframe is null else mf set main panel javax swing j component get current gui mf set edit menu get tree listener get current node create popup menu localechanged localechangeevent first updatecurrentnode guis hashmap nodestogui hashmap testbeanguis hashmap beaninfo flushcaches editcommand mainframe getmainframe setmainpanel jcomponent getcurrentgui seteditmenu gettreelistener getcurrentnode createpopupmenu sets the filepath of the current test plan it s shown in the main frame title and used on saving param f public void set test plan file string f test plan file f get main frame set extended frame title test plan file enable file revert action if a file is used get main frame set file revert enabled f null get main frame set project file loaded f try file server get file server set basedir test plan file catch io exception e1 log error failure setting file server s base dir e1 settestplanfile testplanfile getmainframe setextendedframetitle testplanfile getmainframe setfilerevertenabled getmainframe setprojectfileloaded fileserver getfileserver setbasedir testplanfile ioexception public string get test plan file return test plan file gettestplanfile testplanfile clears the test plan and associated objects clears the test plan file name public void clear test plan get tree model clear test plan nodes to gui clear set test plan file null cleartestplan gettreemodel cleartestplan nodestogui settestplanfile clears the test plan element and associated object param element to clear public void clear test plan test element element get tree model clear test plan element remove node element cleartestplan testelement gettreemodel cleartestplan removenode public static void show error message final string message final string title show message message title j option pane error message showerrormessage showmessage joptionpane error_message public static void show info message final string message final string title show message message title j option pane information message showinfomessage showmessage joptionpane information_message public static void show warning message final string message final string title show message message title j option pane warning message showwarningmessage showmessage joptionpane warning_message public static void show message final string message final string title final int type if gui pack null return swing utilities invoke later new runnable public void run j option pane show message dialog null message title type showmessage guipack swingutilities invokelater joptionpane showmessagedialog swing utilities invoke later new runnable public void run j option pane show message dialog null message title type swingutilities invokelater joptionpane showmessagedialog private static final string mimetype send file mime label non nls 1 public http file args panel this required for unit tests send_file_mime_label httpfileargspanel create a new http file args panel as an embedded component using the specified title param label the title for the component public http file args panel string label table label new j label label init httpfileargspanel httpfileargspanel tablelabel jlabel initialize the table model used for the http files table private void initialize table model table model new object table model new string filepath paramname mimetype http file arg class new functor new functor get path non nls 1 new functor get param name non nls 1 new functor get mime type non nls 1 new functor new functor set path non nls 1 new functor set param name non nls 1 new functor set mime type non nls 1 new class string class string class string class initializetablemodel tablemodel objecttablemodel httpfilearg getpath getparamname getmimetype setpath setparamname setmimetype public static boolean test functors http file args panel instance new http file args panel non nls 1 instance initialize table model return instance table model check functors null instance get class testfunctors httpfileargspanel httpfileargspanel initializetablemodel tablemodel checkfunctors getclass resize the table columns to appropriate widths param table the table to resize columns for private void size columns j table table int resize mode table get auto resize mode table set auto resize mode j table auto resize off fix size table get column paramname fix size table get column mimetype table set auto resize mode resize mode sizecolumns jtable resizemode getautoresizemode setautoresizemode jtable auto_resize_off fixsize getcolumn fixsize getcolumn setautoresizemode resizemode resize the table column to a fixed size param column the column whose size will be fixed private void fix size table column column column size width to fit column set max width column get width 2 column set width column get max width column set resizable false fixsize tablecolumn sizewidthtofit setmaxwidth getwidth setwidth getmaxwidth setresizable save the gui data in the http sampler base element param test element public void modify test element test element test element stop table editing if test element instanceof http sampler base http sampler base base http sampler base test element int rows table model get row count iterator model data table model iterator http file arg files new http file arg rows int row 0 while model data has next http file arg file http file arg model data next files row file base sethttp files files httpsamplerbase testelement modifytestelement testelement testelement stoptableediting testelement httpsamplerbase httpsamplerbase httpsamplerbase testelement tablemodel getrowcount modeldata tablemodel httpfilearg httpfilearg modeldata hasnext httpfilearg httpfilearg modeldata sethttpfiles a newly created component can be initialized with the contents of a http sampler base object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui param test element the http sampler base to be used to configure the gui public void configure test element test element if test element instanceof http sampler base http sampler base base http sampler base test element table model clear data http file arg files base gethttp files for int i 0 i files length i table model add row files i check delete and browse status httpsamplerbase testelement httpsamplerbase testelement testelement testelement httpsamplerbase httpsamplerbase httpsamplerbase testelement tablemodel cleardata httpfilearg gethttpfiles tablemodel addrow checkdeleteandbrowsestatus enable or disable the delete button depending on whether or not there is a row to be deleted private void check delete and browse status disable delete and browse buttons if there are no rows in the table to delete if table model get row count 0 browse set enabled false delete set enabled false else browse set enabled true delete set enabled true checkdeleteandbrowsestatus tablemodel getrowcount setenabled setenabled setenabled setenabled clear all rows from the table public void clear stop table editing table model clear data stoptableediting tablemodel cleardata invoked when an action occurs this implementation supports the add and delete buttons param e the event that has occurred public void action performed action event e string action e get action command if action equals add add file non nls 1 run command on selected file action actionperformed actionevent getactioncommand addfile runcommandonselectedfile runs specified command on currently selected file param command specifies which process will be done on selected file it s coming from action command currently catched by action listener see run command on row private void run command on selected file string command if a table cell is being edited we must cancel the editing before deleting the row if table is editing table cell editor cell editor table get cell editor table get editing row table get editing column cell editor cancel cell editing int row selected table get selected row if row selected 0 run command on row command row selected table model fire table data changed disable delete and browse if there are no rows in the table to delete check delete and browse status table still contains one or more rows so highlight select the appropriate one if table model get row count 0 int row to select row selected if row selected table model get row count row to select row selected 1 table set row selection interval row to select row to select runcommandonrow runcommandonselectedfile isediting tablecelleditor celleditor getcelleditor geteditingrow geteditingcolumn celleditor cancelcellediting rowselected getselectedrow rowselected runcommandonrow rowselected tablemodel firetabledatachanged checkdeleteandbrowsestatus tablemodel getrowcount rowtoselect rowselected rowselected tablemodel getrowcount rowtoselect rowselected setrowselectioninterval rowtoselect rowtoselect runs specified command on currently selected table row param command specifies which process will be done on selected file it s coming from action command currently catched by action listener param row selected index of selected row private void run command on row string command int row selected if delete equals command table model remove row row selected else if browse equals command string path browse and get file path table model set value at path row selected 0 rowselected runcommandonrow rowselected tablemodel removerow rowselected browseandgetfilepath tablemodel setvalueat rowselected add a new file row to the table private void add file string path if a table cell is being edited we should accept the current value and stop the editing before adding a new row stop table editing table model add row new http file arg path enable delete which may already be enabled but it won t hurt delete set enabled true browse set enabled true highlight select the appropriate row int row to select table model get row count 1 table set row selection interval row to select row to select addfile stoptableediting tablemodel addrow httpfilearg setenabled setenabled rowtoselect tablemodel getrowcount setrowselectioninterval rowtoselect rowtoselect opens a dialog box to choose a file and returns selected file s path return a new file object private string browse and get file path string path non nls 1 j file chooser chooser file dialoger prompt to open file if chooser null file file chooser get selected file if file null path file get path return path browseandgetfilepath jfilechooser filedialoger prompttoopenfile getselectedfile getpath stop any editing that is currently being done on the table this will save any changes that have already been made protected void stop table editing if table is editing table cell editor cell editor table get cell editor table get editing row table get editing column cell editor stop cell editing stoptableediting isediting tablecelleditor celleditor getcelleditor geteditingrow geteditingcolumn celleditor stopcellediting create the main gui panel which contains the file table return the main gui panel private component make main panel initialize table model table new j table table model table get table header set default renderer new header as property renderer table set selection mode list selection model single selection return make scroll pane table makemainpanel initializetablemodel jtable tablemodel gettableheader setdefaultrenderer headeraspropertyrenderer setselectionmode listselectionmodel single_selection makescrollpane create a panel containing the title label for the table return a panel containing the title label private component make label panel j panel label panel new j panel new flow layout flow layout center label panel add table label return label panel makelabelpanel jpanel labelpanel jpanel flowlayout flowlayout labelpanel tablelabel labelpanel create a panel containing the add and delete buttons return a gui panel containing the buttons private j panel make button panel add new j button j meter utils get res string add non nls 1 add set action command add add set enabled true browse new j button j meter utils get res string browse non nls 1 browse set action command browse delete new j button j meter utils get res string delete non nls 1 delete set action command delete check delete and browse status j panel button panel new j panel button panel set border border factory create empty border 0 10 0 10 add add action listener this browse add action listener this delete add action listener this button panel add add button panel add browse button panel add delete return button panel jpanel makebuttonpanel jbutton jmeterutils getresstring setactioncommand setenabled jbutton jmeterutils getresstring setactioncommand jbutton jmeterutils getresstring setactioncommand checkdeleteandbrowsestatus jpanel buttonpanel jpanel buttonpanel setborder borderfactory createemptyborder addactionlistener addactionlistener addactionlistener buttonpanel buttonpanel buttonpanel buttonpanel initialize the components and layout of this component private void init j panel p this p set layout new border layout p add make label panel border layout north p add make main panel border layout center force a minimum table height of 70 pixels p add box create vertical strut 70 border layout west p add make button panel border layout south table revalidate size columns table jpanel setlayout borderlayout makelabelpanel borderlayout makemainpanel borderlayout createverticalstrut borderlayout makebuttonpanel borderlayout sizecolumns private j scroll pane make scroll pane component comp j scroll pane pane new j scroll pane comp pane set preferred size pane get minimum size return pane jscrollpane makescrollpane jscrollpane jscrollpane setpreferredsize getminimumsize param label resouce text resource name for group label param item resources list of resource names for individual buttons param selected item button to be selected if not null public j labeled radioi18n string label resouce string item resources string selected item set label label resouce init item resources selected item label_resouce item_resources selecteditem jlabeledradioi18n label_resouce item_resources selecteditem setlabel label_resouce item_resources selecteditem deprecated only for use in testing public j labeled radioi18n super jlabeledradioi18n method is responsible for creating the j radio buttons and adding them to the button group the resource name is used as the action command for the button model and the reource value is used to set the button label param resouces list of resource names param selected initially selected resource if not null private void init string resouces string selected this add m label for int idx 0 idx resouces length idx j radio button btn new j radio button j meter utils get res string resouces idx btn set action command resouces idx btn add action listener this add the button to the button group this b group add btn add the button this add btn if selected null selected equals resouces idx btn set selected true jradiobuttons buttongroup mlabel jradiobutton jradiobutton jmeterutils getresstring setactioncommand addactionlistener bgroup setselected the implementation will get the resource name from the selected radio button in the j button group public string get text return this b group get selection get action command jbuttongroup gettext bgroup getselection getactioncommand the implementation will iterate through the radio buttons and find the match it then sets it to selected and sets all other radio buttons as not selected param resourcename name of resource whose button is to be selected public void set text string resourcename enumeration en this b group get elements while en has more elements button model model j radio button en next element get model if model get action command equals resourcename this b group set selected model true else this b group set selected model false settext bgroup getelements hasmoreelements buttonmodel jradiobutton nextelement getmodel getactioncommand bgroup setselected bgroup setselected set the group label from the resource name param label resource public final void set label string label resource this m label set text j meter utils get res string label resource label_resource setlabel label_resource mlabel settext jmeterutils getresstring label_resource see org apache jorphan gui j labeled field add change listener javax swing event change listener public void add change listener change listener p change listener this m change listeners add p change listener jlabeledfield addchangelistener changelistener addchangelistener changelistener pchangelistener mchangelisteners pchangelistener notify all registered change listeners that the text in the text field has changed private void notify change listeners change event ce new change event this for int index 0 index m change listeners size index change listener m change listeners get index state changed ce notifychangelisteners changeevent changeevent mchangelisteners changelistener mchangelisteners statechanged method will return all the label and j radio buttons button group is excluded from the list public list get component list list comps new linked list comps add m label enumeration en this b group get elements while en has more elements comps add en next element return comps jradiobuttons buttongroup getcomponentlist linkedlist mlabel bgroup getelements hasmoreelements nextelement when a radio button is clicked an action event is triggered public void action performed action event e this notify change listeners actionevent actionperformed actionevent notifychangelisteners retrieve an array of arguments that have not been parsed due to the parser halting return an array of unparsed args public final string get unparsed args return m unparsedargs getunparsedargs m_unparsedargs retrieve a list of options that were parsed from command list return the list of options public final vector get arguments system out println arguments m options return m options getarguments m_options m_options retrieve the link cl option with specified id or code null code if no command line option is found param id the command line option id return the link cl option with the specified id or code null code if no cl option is found see cl option public final cl option get argument by id final int id return cl option m optionindex get new integer id cloption cloption cloption cloption cloption getargumentbyid cloption m_optionindex retrieve the link cl option with specified name or code null code if no command line option is found param name the command line option name return the link cl option with the specified name or code null code if no cl option is found see cl option public final cl option get argument by name final string name return cl option m optionindex get name cloption cloption cloption cloption cloption getargumentbyname cloption m_optionindex get descriptor for option id param id the id return the descriptor private final cl option descriptor get descriptor for final int id for int i 0 i m optiondescriptors length i if m optiondescriptors i get id id return m optiondescriptors i return null cloptiondescriptor getdescriptorfor m_optiondescriptors m_optiondescriptors getid m_optiondescriptors retrieve a descriptor by name param name the name return the descriptor private final cl option descriptor get descriptor for final string name for int i 0 i m optiondescriptors length i if m optiondescriptors i get name equals name return m optiondescriptors i return null cloptiondescriptor getdescriptorfor m_optiondescriptors m_optiondescriptors getname m_optiondescriptors retrieve an error message that occured during parsing if one existed return the error string public final string get error string system out println error string m errormessage return m errormessage geterrorstring errorstring m_errormessage m_errormessage require state to be placed in for option param descriptor the option descriptor return the state private final int get state for final cl option descriptor descriptor final int flags descriptor get flags if flags cl option descriptor arguments required 2 cl option descriptor arguments required 2 return state require 2args else if flags cl option descriptor argument required cl option descriptor argument required return state require arg else if flags cl option descriptor argument optional cl option descriptor argument optional return state optional arg else return state normal getstatefor cloptiondescriptor getflags cloptiondescriptor arguments_required_2 cloptiondescriptor arguments_required_2 state_require_2args cloptiondescriptor argument_required cloptiondescriptor argument_required state_require_arg cloptiondescriptor argument_optional cloptiondescriptor argument_optional state_optional_arg state_normal create a parser that can deal with options and parses certain args param args the args typically that passed to the code public static void main string args code method param option descriptors the option descriptors param control the parser control used determine behaviour of parser public cl args parser final string args final cl option descriptor option descriptors final parser control control m optiondescriptors option descriptors m control control m options new vector m args args try parse check incompatibilities m options build option index catch final parse exception pe m errormessage pe get message system out println built m options system out println from arrays as list args optiondescriptors clargsparser cloptiondescriptor optiondescriptors parsercontrol m_optiondescriptors optiondescriptors m_control m_options m_args checkincompatibilities m_options buildoptionindex parseexception m_errormessage getmessage m_options aslist check for duplicates of an option it is an error to have duplicates unless appropriate flags is set in descriptor param arguments the arguments private final void check incompatibilities final vector arguments throws parse exception final int size arguments size for int i 0 i size i final cl option option cl option arguments element at i final int id option get descriptor get id final cl option descriptor descriptor get descriptor for id this occurs when id 0 and user has not supplied a descriptor for arguments if null descriptor continue final int incompatible descriptor get incompatible check incompatible arguments incompatible i checkincompatibilities parseexception cloption cloption elementat getdescriptor getid cloptiondescriptor getdescriptorfor getincompatible checkincompatible private final void check incompatible final vector arguments final int incompatible final int original throws parse exception final int size arguments size for int i 0 i size i if original i continue final cl option option cl option arguments element at i final int id option get descriptor get id for int j 0 j incompatible length j if id incompatible j final cl option original option cl option arguments element at original final int original id original option get descriptor get id string message null if id original id message duplicate options for describe dual option original id found else message incompatible options describe dual option id and describe dual option original id found throw new parse exception message 0 checkincompatible parseexception cloption cloption elementat getdescriptor getid cloption originaloption cloption elementat originalid originaloption getdescriptor getid originalid describedualoption originalid describedualoption describedualoption originalid parseexception private final string describe dual option final int id final cl option descriptor descriptor get descriptor for id if null descriptor return parameter else final string buffer sb new string buffer boolean has char option false if character is letter char id sb append sb append char id has char option true final string long option descriptor get name if null long option if has char option sb append sb append sb append long option return sb to string describedualoption cloptiondescriptor getdescriptorfor stringbuffer stringbuffer hascharoption isletter hascharoption longoption getname longoption hascharoption longoption tostring create a parser that deals with options and parses certain args param args the args param option descriptors the option descriptors public cl args parser final string args final cl option descriptor option descriptors this args option descriptors null optiondescriptors clargsparser cloptiondescriptor optiondescriptors optiondescriptors create a string array that is subset of input array the sub array should start at array entry indicated by index that array element should only include characters from char index onwards param array the original array param index the cut point in array param char index the cut point in element of array return the result array private final string sub array final string array final int index final int char index final int remaining array length index final string result new string remaining if remaining 1 system arraycopy array index 1 result 1 remaining 1 result 0 array index substring char index 1 return result charindex charindex subarray charindex charindex actually parse arguments private final void parse throws parse exception if 0 m args length return m stringlength m args m argindex length while true m ch peek at char if m argindex m args length break if null m control m control is finished m lastoptionid this may need mangling due to peeks m unparsedargs sub array m args m argindex m stringindex return if state option mode m state if get to an arg barrier then return to normal mode else continue accumulating options if 0 m ch get char strip the null m state state normal else parse short option else if state normal m state parse normal else if state no options m state should never get to here when string index 0 add option new cl option m args m argindex else parse arguments reached end of input arguments perform final processing if m option null if state optional arg m state m options add element m option else if state require arg m state final cl option descriptor descriptor get descriptor for m option get descriptor get id final string message missing argument to option get option description descriptor throw new parse exception message 0 else if state require 2args m state if 1 m option get argument count m option add argument m options add element m option else final cl option descriptor descriptor get descriptor for m option get descriptor get id final string message missing argument to option get option description descriptor throw new parse exception message 0 else throw new parse exception illegal state m state m option 0 parseexception m_args m_stringlength m_args m_argindex m_ch peekatchar m_argindex m_args m_control m_control isfinished m_lastoptionid m_unparsedargs subarray m_args m_argindex m_stringindex state_option_mode m_state m_ch getchar m_state state_normal parseshortoption state_normal m_state parsenormal state_no_options m_state stringindex addoption cloption m_args m_argindex parsearguments m_option state_optional_arg m_state m_options addelement m_option state_require_arg m_state cloptiondescriptor getdescriptorfor m_option getdescriptor getid getoptiondescription parseexception state_require_2args m_state m_option getargumentcount m_option addargument m_options addelement m_option cloptiondescriptor getdescriptorfor m_option getdescriptor getid getoptiondescription parseexception parseexception illegalstate m_state m_option private final string get option description final cl option descriptor descriptor if m islong return descriptor get name else return char descriptor get id getoptiondescription cloptiondescriptor m_islong getname getid private final char peek at char if invalid m lastchar m lastchar read char return char m lastchar peekatchar m_lastchar m_lastchar readchar m_lastchar private final char get char if invalid m lastchar final char result char m lastchar m lastchar invalid return result else return read char getchar m_lastchar m_lastchar m_lastchar readchar private final char read char if m stringindex m stringlength m argindex m stringindex 0 if m argindex m args length m stringlength m args m argindex length else m stringlength 0 return 0 if m argindex m args length return 0 return m args m argindex char at m stringindex readchar m_stringindex m_stringlength m_argindex m_stringindex m_argindex m_args m_stringlength m_args m_argindex m_stringlength m_argindex m_args m_args m_argindex charat m_stringindex private final token next token final char separators m ch get char if is separator m ch separators m tokesep m ch m ch get char return new token token separator null final string buffer sb new string buffer do sb append m ch m ch get char while is separator m ch separators m tokesep m ch return new token token string sb to string nexttoken m_ch getchar isseparator m_ch m_tokesep m_ch m_ch getchar token_separator stringbuffer stringbuffer m_ch m_ch getchar isseparator m_ch m_tokesep m_ch token_string tostring private final boolean is separator final char ch final char separators for int i 0 i separators length i if ch separators i return true return false isseparator private final void add option final cl option option m options add element option m lastoptionid option get descriptor get id m option null addoption cloption m_options addelement m_lastoptionid getdescriptor getid m_option private final void parse option final cl option descriptor descriptor final string option string throws parse exception if null descriptor throw new parse exception unknown option option string 0 m state get state for descriptor m option new cl option descriptor if state normal m state add option m option parseoption cloptiondescriptor optionstring parseexception parseexception optionstring m_state getstatefor m_option cloption state_normal m_state addoption m_option private final void parse short option throws parse exception m ch get char final cl option descriptor descriptor get descriptor for m ch m islong false parse option descriptor m ch if state normal m state m state state option mode parseshortoption parseexception m_ch getchar cloptiondescriptor getdescriptorfor m_ch m_islong parseoption m_ch state_normal m_state m_state state_option_mode private final void parse arguments throws parse exception if state require arg m state if m ch 0 m ch get char final token token next token null separators m option add argument token get value add option m option m state state normal else if state optional arg m state if m ch 0 m ch get char consume stray character add option m option m state state normal return if m islong m tokesep long optional arg must have as separator add option m option m state state normal return if m ch get char final token token next token null separators m option add argument token get value add option m option m state state normal else if state require 2args m state if 0 m option get argument count fix bug d arg1 arg2 was causing parse error however define arg1 arg2 is ok this seems to be because the parser skips the terminator for the long options but was not doing so for the short options if m islong if 0 peek at char get char final token token next token arg separators if token separator token get type final cl option descriptor descriptor get descriptor for m option get descriptor get id final string message unable to parse first argument for option get option description descriptor throw new parse exception message 0 else m option add argument token get value are we about to start a new option if 0 m ch peek at char yes so the second argument is missing m option add argument m options add element m option m state state normal else 2nd argument final string buffer sb new string buffer m ch get char while is separator m ch null separators sb append m ch m ch get char final string argument sb to string system out println arguement argument m option add argument argument add option m option m option null m state state normal parsearguments parseexception state_require_arg m_state m_ch m_ch getchar nexttoken null_separators m_option addargument getvalue addoption m_option m_state state_normal state_optional_arg m_state m_ch m_ch getchar addoption m_option m_state state_normal m_islong m_tokesep addoption m_option m_state state_normal m_ch getchar nexttoken null_separators m_option addargument getvalue addoption m_option m_state state_normal state_require_2args m_state m_option getargumentcount m_islong peekatchar getchar nexttoken arg_separators token_separator gettype cloptiondescriptor getdescriptorfor m_option getdescriptor getid getoptiondescription parseexception m_option addargument getvalue m_ch peekatchar m_option addargument m_options addelement m_option m_state state_normal stringbuffer stringbuffer m_ch getchar isseparator m_ch null_separators m_ch m_ch getchar tostring m_option addargument addoption m_option m_option m_state state_normal parse options from normal mode private final void parse normal throws parse exception if m ch parse the arguments that are not options final string argument next token null separators get value add option new cl option argument m state state normal else get char strip the if 0 peek at char throw new parse exception malformed option 0 else m ch peek at char if it is a short option then parse it else if m ch parse short option else get char strip the sequence it can either mean a change of state to state no options or else a long option if 0 peek at char get char m state state no options else its a long option final string option name next token arg separators get value final cl option descriptor descriptor get descriptor for option name m islong true parse option descriptor option name parsenormal parseexception m_ch nexttoken null_separators getvalue addoption cloption m_state state_normal getchar peekatchar parseexception m_ch peekatchar m_ch parseshortoption getchar state_no_options peekatchar getchar m_state state_no_options optionname nexttoken arg_separators getvalue cloptiondescriptor getdescriptorfor optionname m_islong parseoption optionname build the m optionindex lookup map for the parsed options private final void build option index final int size m options size m optionindex new hashtable size 2 for int i 0 i size i final cl option option cl option m options get i final cl option descriptor option descriptor get descriptor for option get descriptor get id m optionindex put new integer option get descriptor get id option if null option descriptor null option descriptor get name m optionindex put option descriptor get name option m_optionindex buildoptionindex m_options m_optionindex cloption cloption m_options cloptiondescriptor optiondescriptor getdescriptorfor getdescriptor getid m_optionindex getdescriptor getid optiondescriptor optiondescriptor getname m_optionindex optiondescriptor getname public add parent addparent public void do action action event e string name component e get source get name gui package gui package gui package get instance try gui package update current node test element controller gui package create test element name add parent to tree controller catch exception err log error err doaction actionevent getsource getname guipackage guipackage guipackage getinstance guipackage updatecurrentnode testelement guipackage createtestelement addparenttotree public set get action names return commands getactionnames protected void add parent to tree test element new parent gui package gui package gui package get instance j meter tree node new node new j meter tree node new parent gui package get tree model j meter tree node current node gui package get tree listener get current node j meter tree node parent node j meter tree node current node get parent int index parent node get index current node gui package get tree model insert node into new node parent node index j meter tree node nodes gui package get tree listener get selected nodes for int i 0 i nodes length i move node gui package nodes i new node addparenttotree testelement newparent guipackage guipackage guipackage getinstance jmetertreenode newnode jmetertreenode newparent guipackage gettreemodel jmetertreenode currentnode guipackage gettreelistener getcurrentnode jmetertreenode parentnode jmetertreenode currentnode getparent parentnode getindex currentnode guipackage gettreemodel insertnodeinto newnode parentnode jmetertreenode guipackage gettreelistener getselectednodes movenode guipackage newnode private void move node gui package gui package j meter tree node node j meter tree node new parent node gui package get tree model remove node from parent node gui package get tree model insert node into node new parent node new parent node get child count movenode guipackage guipackage jmetertreenode jmetertreenode newparentnode guipackage gettreemodel removenodefromparent guipackage gettreemodel insertnodeinto newparentnode newparentnode getchildcount private static final filename filter jmx filter new filename filter public boolean accept file dir string name return name ends with jmx filenamefilter jmxfilter filenamefilter endswith public test load string name super name test file null parent null testload testfile public test load string name file file string dir super name test file file parent dir testload testfile public static test suite suite test suite suite new test suite load test suite add test new test load check gui package scan files suite testfiledir scan files suite demofiledir return suite testsuite testsuite testsuite addtest testload checkguipackage scanfiles scanfiles private static void scan files test suite suite file parent file test files parent list files jmx filter string dir parent get name for int i 0 i test files length i suite add test new test load check test file test files i dir scanfiles testsuite testfiles listfiles jmxfilter getname testfiles addtest testload checktestfile testfiles public void check test file throws exception hash tree tree null try tree get tree test file catch exception e fail parent test file get name caused e assert tree tree checktestfile hashtree gettree testfile testfile getname asserttree private void assert tree hash tree tree throws exception final object object tree get array 0 final string name test file get name if object instanceof org apache jmeter testelement test plan not test plan contains name fail parent name tree should be test plan but is object get class get name asserttree hashtree getarray testfile getname testplan nottestplan testplan getclass getname private hash tree get tree file f throws exception file input stream fis new file input stream f hash tree tree null try tree save service load tree fis finally fis close return tree hashtree gettree fileinputstream fileinputstream hashtree saveservice loadtree private final string perthread label j meter utils get res string throughput control perthread label non nls 1 public throughput controller gui init perthread_label jmeterutils getresstring throughput_control_perthread_label throughputcontrollergui public test element create test element throughput controller tc new throughput controller modify test element tc return tc testelement createtestelement throughputcontroller throughputcontroller modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element tc configure test element tc throughput controller tc set style style throughput controller tc set per thread is per thread if style throughput controller bynumber try throughput controller tc set max throughput integer parse int throughput get text trim catch number format exception e in case we are converting back from floating point drop the decimal fraction throughput controller tc set max throughput throughput get text trim split 0 non nls 1 else try throughput controller tc set percent throughput float parse float throughput get text trim catch number format exception e throughput controller tc set percent throughput throughput get text testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement throughputcontroller setstyle throughputcontroller setperthread isperthread throughputcontroller throughputcontroller setmaxthroughput parseint gettext numberformatexception throughputcontroller setmaxthroughput gettext throughputcontroller setpercentthroughput parsefloat gettext numberformatexception throughputcontroller setpercentthroughput gettext implements j metergui component clear gui public void clear gui super clear gui style box set selected index 0 throughput set text 1 non nls 1 perthread set selected true jmeterguicomponent cleargui cleargui cleargui stylebox setselectedindex settext setselected public void configure test element el super configure el if throughput controller el get style throughput controller bynumber style box get model set selected item bynumber label throughput set text throughput controller el get max throughput else style box set selected item bypercent label throughput set text throughput controller el get percent throughput perthread set selected throughput controller el is per thread testelement throughputcontroller getstyle throughputcontroller stylebox getmodel setselecteditem bynumber_label settext throughputcontroller getmaxthroughput stylebox setselecteditem bypercent_label settext throughputcontroller getpercentthroughput setselected throughputcontroller isperthread public string get label resource return throughput control title non nls 1 getlabelresource throughput_control_title private void init set layout new vertical layout 5 vertical layout both vertical layout top set border make border add make title panel default combo box model style model new default combo box model style model add element bynumber label style model add element bypercent label style box new j combo box style model style box add action listener new action listener public void action performed action event e if string style box get selected item equals bynumber label style throughput controller bynumber else style throughput controller bypercent add style box type field j panel tp panel new j panel j label tp label new j label throughput label tp panel add tp label text field throughput new j text field 5 tp panel add throughput throughput set text 1 non nls 1 throughput add action listener this tp panel add throughput add tp panel perthread field perthread new j check box perthread label is per thread perthread add item listener new item listener public void item state changed item event event if event get state change item event selected is per thread true else is per thread false add perthread setlayout verticallayout verticallayout verticallayout setborder makeborder maketitlepanel defaultcomboboxmodel stylemodel defaultcomboboxmodel stylemodel addelement bynumber_label stylemodel addelement bypercent_label stylebox jcombobox stylemodel stylebox addactionlistener actionlistener actionperformed actionevent stylebox getselecteditem bynumber_label throughputcontroller throughputcontroller stylebox jpanel tppanel jpanel jlabel tplabel jlabel throughput_label tppanel tplabel jtextfield tppanel settext addactionlistener tppanel tppanel jcheckbox perthread_label isperthread additemlistener itemlistener itemstatechanged itemevent getstatechange itemevent isperthread isperthread style box add action listener new action listener public void action performed action event e if string style box get selected item equals bynumber label style throughput controller bynumber else style throughput controller bypercent stylebox addactionlistener actionlistener actionperformed actionevent stylebox getselecteditem bynumber_label throughputcontroller throughputcontroller perthread add item listener new item listener public void item state changed item event event if event get state change item event selected is per thread true else is per thread false additemlistener itemlistener itemstatechanged itemevent getstatechange itemevent isperthread isperthread create a new loop control panel as a standalone component public if controller panel this true loopcontrolpanel ifcontrollerpanel create a new if controller panel as either a standalone or an embedded component param display name indicates whether or not this component should display its name if true this is a standalone component if false this component is intended to be used as a subpanel for another component public if controller panel boolean display name this display name display name init ifcontrollerpanel displayname ifcontrollerpanel displayname displayname displayname a newly created component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui param element the test element to configure public void configure test element element super configure element if element instanceof if controller if controller if controller if controller element the condition set text if controller get condition evaluate all set selected if controller is evaluate all use expression set selected if controller is use expression testelement testelement ifcontroller ifcontroller ifcontroller ifcontroller thecondition settext ifcontroller getcondition evaluateall setselected ifcontroller isevaluateall useexpression setselected ifcontroller isuseexpression implements j metergui component create test element public test element create test element if controller controller new if controller modify test element controller return controller jmeterguicomponent createtestelement testelement createtestelement ifcontroller ifcontroller modifytestelement implements j metergui component modify test element test element public void modify test element test element controller configure test element controller if controller instanceof if controller if controller if controller if controller controller if controller set condition the condition get text if controller set evaluate all evaluate all is selected if controller set use expression use expression is selected jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement ifcontroller ifcontroller ifcontroller ifcontroller ifcontroller setcondition thecondition gettext ifcontroller setevaluateall evaluateall isselected ifcontroller setuseexpression useexpression isselected implements j metergui component clear gui public void clear gui super clear gui the condition set text non nls 1 evaluate all set selected false jmeterguicomponent cleargui cleargui cleargui thecondition settext evaluateall setselected invoked when an action occurs this implementation assumes that the target component is the infinite loops checkbox param event the event that has occurred public void action performed action event event new focus requester the condition actionperformed actionevent focusrequester thecondition public string get label resource return if controller title non nls 1 getlabelresource if_controller_title initialize the gui components and layout for this component private void init standalone if display name set layout new border layout 0 5 set border make border add make title panel border layout north j panel main panel new j panel new border layout main panel add create condition panel border layout north add main panel border layout center else embedded set layout new border layout add create condition panel border layout north displayname setlayout borderlayout setborder makeborder maketitlepanel borderlayout jpanel mainpanel jpanel borderlayout mainpanel createconditionpanel borderlayout mainpanel borderlayout setlayout borderlayout createconditionpanel borderlayout create a gui panel containing the condition return a gui panel containing the condition components private j panel create condition panel j panel condition panel new j panel new border layout 5 0 condition label j label condition label new j label j meter utils get res string if controller label non nls 1 condition panel add condition label border layout west text field the condition new j text field non nls 1 condition label set label for the condition condition panel add the condition border layout center the condition add action listener this condition panel add box create horizontal strut condition label get preferred size width the condition get preferred size width border layout north j panel option panel new j panel use expression instead of javascript use expression new j check box j meter utils get res string if controller expression non nls 1 option panel add use expression evaluate all checkbox evaluate all new j check box j meter utils get res string if controller evaluate all non nls 1 option panel add evaluate all condition panel add option panel border layout south return condition panel jpanel createconditionpanel jpanel conditionpanel jpanel borderlayout jlabel conditionlabel jlabel jmeterutils getresstring if_controller_label conditionpanel conditionlabel borderlayout thecondition jtextfield conditionlabel setlabelfor thecondition conditionpanel thecondition borderlayout thecondition addactionlistener conditionpanel createhorizontalstrut conditionlabel getpreferredsize thecondition getpreferredsize borderlayout jpanel optionpanel jpanel useexpression jcheckbox jmeterutils getresstring if_controller_expression optionpanel useexpression evaluateall jcheckbox jmeterutils getresstring if_controller_evaluate_all optionpanel evaluateall conditionpanel optionpanel borderlayout conditionpanel private final socket client socket public http mirror thread socket clientsocket this client socket clientsocket clientsocket httpmirrorthread _clientsocket clientsocket _clientsocket main processing method for the http mirror object public void run log info starting thread buffered input stream in null buffered output stream out null try in new buffered input stream client socket get input stream out new buffered output stream client socket get output stream the headers are written using iso 8859 1 encoding out write http 1 0 200 ok get bytes iso 8859 1 non nls 1 out write crlf out write content type text plain get bytes iso 8859 1 non nls 1 out write crlf out write crlf out flush read the header part we will be looking for a content length header so we know how much we should read we assume headers are in iso 8859 1 if we do not find such a header we will just have to read until we have to block to read more until we support chunked transfer int content length 1 boolean is chunked false byte buffer new byte 1024 string buffer headers new string buffer int length 0 int position of body 0 while position of body 0 length in read buffer 1 out write buffer 0 length echo back headers append new string buffer 0 length iso 8859 1 check if we have read all the headers position of body get position of body headers to string check if we have found a content length header final string header string headers to string string content length header value get request header value header string content length non nls 1 if content length header value null content length new integer content length header value int value string sleep header value get request header value header string x sleep non nls 1 if sleep header value null thread sleep integer parse int sleep header value string transfer encoding header value get request header value header string transfer encoding non nls 1 if transfer encoding header value null is chunked transfer encoding header value equals ignore case chunked non nls 1 we only support chunked transfer encoding if is chunked log error transfer encoding header set the value is not supported transfer encoding header value if we know the content length we can allow the reading of the request to block until more data arrives if it is chunked transfer we cannot allow the reading to block because we do not know when to stop reading because the chunked transfer is not properly supported yet length 0 if content length 0 check how much of the body we have already read as part of reading the headers we subtract two bytes for the crlf divider between header and body int total read bytes header string length position of body 2 we know when to stop reading so we can allow the read method to block while total read bytes content length length in read buffer 1 out write buffer 0 length total read bytes length else if is chunked it is chunked transfer encoding which we do not really support yet so we just read without blocking because we do not know when to stop reading so we cannot block todo propery implement support for chunked transfer i e to know when we have read the whole request and therefore allow the reading to block while in available 0 length in read buffer 1 out write buffer 0 length else the reqest has no body or it has a transfer encoding we do not support in either case we read any data available while in available 0 length in read buffer 1 out write buffer 0 length out flush catch io exception e log error e catch interrupted exception e log error e finally j orphan utils close quietly out j orphan utils close quietly in j orphan utils close quietly client socket log info end of thread httpmirror bufferedinputstream bufferedoutputstream bufferedinputstream clientsocket getinputstream bufferedoutputstream clientsocket getoutputstream iso_8859_1 getbytes iso_8859_1 getbytes iso_8859_1 iso_8859_1 contentlength ischunked stringbuffer stringbuffer positionofbody positionofbody iso_8859_1 positionofbody getpositionofbody tostring headerstring tostring contentlengthheadervalue getrequestheadervalue headerstring contentlengthheadervalue contentlength contentlengthheadervalue intvalue sleepheadervalue getrequestheadervalue headerstring sleepheadervalue parseint sleepheadervalue transferencodingheadervalue getrequestheadervalue headerstring transferencodingheadervalue ischunked transferencodingheadervalue equalsignorecase ischunked transferencodingheadervalue contentlength totalreadbytes headerstring positionofbody totalreadbytes contentlength totalreadbytes ischunked ioexception interruptedexception jorphanutils closequietly jorphanutils closequietly jorphanutils closequietly clientsocket private static string get request header value string request headers string header name perl5 matcher local matcher j meter utils get matcher we use multi line mask so can prefix the line with also match w to catch transfer encoding chunked todo may need to be extended to allow for other header values with non word contents string expression header name s w non nls 1 non nls 2 pattern pattern j meter utils get pattern expression perl5 compiler read only mask perl5 compiler case insensitive mask perl5 compiler multiline mask if local matcher contains request headers pattern the value is in the first group group 0 is the whole match return local matcher get match group 1 else return null getrequestheadervalue requestheaders headername perl5matcher localmatcher jmeterutils getmatcher headername jmeterutils getpattern perl5compiler read_only_mask perl5compiler case_insensitive_mask perl5compiler multiline_mask localmatcher requestheaders localmatcher getmatch private static int get position of body string string to check perl5 matcher local matcher j meter utils get matcher the headers and body are divided by a blank line the r is to allow for the cr before lf string regular expression r non nls 1 pattern pattern j meter utils get pattern regular expression perl5 compiler read only mask perl5 compiler case insensitive mask perl5 compiler multiline mask pattern matcher input input new pattern matcher input string to check if local matcher contains input pattern match result match local matcher get match return match begin offset 0 no divider was found return 1 getpositionofbody stringtocheck perl5matcher localmatcher jmeterutils getmatcher regularexpression jmeterutils getpattern regularexpression perl5compiler read_only_mask perl5compiler case_insensitive_mask perl5compiler multiline_mask patternmatcherinput patternmatcherinput stringtocheck localmatcher matchresult localmatcher getmatch beginoffset private final map remote engines new hash map public remote start remoteengines hashmap remotestart public void do action action event e string name component e get source get name if name null name name trim string action e get action command if action equals action names remote stop do remote stop name else if action equals action names remote start popup should save e do remote init name do remote start name else if action equals action names remote start all popup should save e string remote hosts string j meter utils get prop default remote hosts local host java util string tokenizer st new java util string tokenizer remote hosts string remote hosts separator while st has more elements string el string st next element do remote init el trim st new java util string tokenizer remote hosts string remote hosts separator while st has more elements string el string st next element do remote start el trim else if action equals action names remote stop all string remote hosts string j meter utils get prop default remote hosts local host java util string tokenizer st new java util string tokenizer remote hosts string remote hosts separator while st has more elements string el string st next element do remote stop el trim else if action equals action names remote exit do remote exit name else if action equals action names remote exit all string remote hosts string j meter utils get prop default remote hosts local host java util string tokenizer st new java util string tokenizer remote hosts string remote hosts separator while st has more elements string el string st next element do remote exit el trim doaction actionevent getsource getname getactioncommand actionnames remote_stop doremotestop actionnames remote_start popupshouldsave doremoteinit doremotestart actionnames remote_start_all popupshouldsave remote_hosts_string jmeterutils getpropdefault remote_hosts local_host stringtokenizer stringtokenizer remote_hosts_string remote_hosts_separator hasmoreelements nextelement doremoteinit stringtokenizer remote_hosts_string remote_hosts_separator hasmoreelements nextelement doremotestart actionnames remote_stop_all remote_hosts_string jmeterutils getpropdefault remote_hosts local_host stringtokenizer stringtokenizer remote_hosts_string remote_hosts_separator hasmoreelements nextelement doremotestop actionnames remote_exit doremoteexit actionnames remote_exit_all remote_hosts_string jmeterutils getpropdefault remote_hosts local_host stringtokenizer stringtokenizer remote_hosts_string remote_hosts_separator hasmoreelements nextelement doremoteexit stops a remote testing engine param name the dns name or ip address of the remote testing engine private void do remote stop string name gui package get instance get main frame show stopping message name j meter engine engine j meter engine remote engines get name engine stop test doremotestop guipackage getinstance getmainframe showstoppingmessage jmeterengine jmeterengine remoteengines stoptest exits a remote testing engine param name the dns name or ip address of the remote testing engine private void do remote exit string name j meter engine engine j meter engine remote engines get name if engine null return gui package get instance get main frame show stopping message name engine exit doremoteexit jmeterengine jmeterengine remoteengines guipackage getinstance getmainframe showstoppingmessage starts a remote testing engine param name the dns name or ip address of the remote testing engine private void do remote start string name j meter engine engine j meter engine remote engines get name if engine null try engine run test catch j meter engine exception e j meter utils report error to user e get message j meter utils get res string remote error starting non nls 1 doremotestart jmeterengine jmeterengine remoteengines runtest jmeterengineexception jmeterutils reporterrortouser getmessage jmeterutils getresstring remote_error_starting initializes remote engines private void do remote init string name j meter engine engine j meter engine remote engines get name if engine null try log info initialising remote engine name engine new clientj meter engine name remote engines put name engine catch exception ex log error failed to initialise remote engine ex j meter utils report error to user ex get message j meter utils get res string remote error init name non nls 1 non nls 2 return else engine reset init engine engine name doremoteinit jmeterengine jmeterengine remoteengines clientjmeterengine remoteengines jmeterutils reporterrortouser getmessage jmeterutils getresstring remote_error_init initengine public set get action names return commands getactionnames initializes test on engine param engine remote engine object param host host the engine will run on private void init engine j meter engine engine string host gui package gui gui package get instance hash tree test tree gui get tree model get test plan j meter convert sub tree test tree test tree add test tree get array 0 gui get main frame engine configure test tree initengine jmeterengine guipackage guipackage getinstance hashtree testtree gettreemodel gettestplan jmeter convertsubtree testtree testtree testtree getarray getmainframe testtree private constructor to prevent instantiation private all tests alltests private static void logprop string prop boolean show string value system get property prop log info prop value if show system out println prop value getproperty private static void logprop string prop logprop prop false starts a run through all unit tests found in the specified classpaths the first argument should be a list of paths to search the second argument is optional and specifies a properties file used to initialize logging the third argument is also optional and specifies a class that implements the unit test manager interface this provides a means of initializing your application with a configuration file prior to the start of any unit tests param args the command line arguments public static void main string args if args length 1 system out println you must specify a comma delimited list of paths to search for unit tests system exit 1 string home new file system get property user dir get parent system out println setting j meter home home j meter utils setj meter home home initialize logging args initialize manager args log info j meter version j meter utils getj meter version logprop java version true logprop java vm name logprop java vendor logprop java home true logprop user home logprop user dir true logprop user language logprop user region logprop user country logprop user variant log info locale locale get default to string logprop os name true logprop os version true logprop os arch logprop java class version logprop java class path string cp system get property java class path string cpe j orphan utils split cp java io file path separator string buffer sb new string buffer 3000 sb append java class path for int i 0 i cpe length i sb append n sb append cpe i if new java io file cpe i exists sb append ok else sb append log info sb to string gui tests throw the error test argument creation org apache jmeter config gui arguments panel test java lang no class def found error at java lang class for name0 native method at java lang class for name class java 141 at java awt graphics environment get local graphics environment graphics environment java 62 try to find out why this is system out println logprop java awt headless true logprop java awt graphicsenv true try class c class for name n system out println found class n c new instance system out println instantiated n catch exception e1 system out println error finding class n e1 catch java lang internal error e1 system out println error finding class n e1 system out println don t call is headless here as it has a side effect system out println creating test suite test suite suite suite args 0 int count test cases suite count test cases system out println starting test run test count count test cases for int i 0 i suite test count i test test at suite test at i int test cases test at count test cases if test at instanceof junit framework test case system out print junit framework test case test at get name if test at instanceof test suite test suite test suite test suite test at string name test suite get name system out print name system out println test cases jeremy arnold this method used to attempt to write results to a file but it had a bug and instead just wrote to system out since nobody has complained about this behavior i m changing the code to not attempt to write to a file so it will continue behaving as it did before it would be simple to make it write to a file instead if that is the desired behavior test runner run suite recheck settings system out println system out println e system get property e system out println g system get property g system out println headless java awt graphics environment is headless jdk 1 4 try class c class for name n system out println found class n c new instance system out println instantiated n catch exception e1 system out println error with class n e1 catch java lang internal error e1 system out println error with class n e1 system out println system exit 0 this is needed because the test may start the awt event queue thread which is not a daemon unittestmanager getproperty getparent jmeterhome jmeterutils setjmeterhome initializelogging initializemanager jmeterversion jmeterutils getjmeterversion getdefault tostring getproperty jorphanutils pathseparator stringbuffer stringbuffer tostring testargumentcreation argumentspanel noclassdeffounderror forname0 forname graphicsenvironment getlocalgraphicsenvironment graphicsenvironment forname newinstance internalerror isheadless testsuite counttestcases counttestcases counttestcases testcount testat testat testcases testat counttestcases testat testcase testcase testat getname testat testsuite testsuite testsuite testsuite testat testsuite getname testcases testrunner getproperty getproperty graphicsenvironment isheadless forname newinstance internalerror eventqueue an overridable method that initializes the logging for the unit test run using the properties file passed in as the second argument param args protected static void initialize logging string args if args length 2 properties props new properties try system out println setting up logging props using file args 1 props load new file input stream args 1 logging manager initialize logging props catch file not found exception e system out println e get localized message catch io exception e system out println e get localized message initializelogging fileinputstream loggingmanager initializelogging filenotfoundexception getlocalizedmessage ioexception getlocalizedmessage an overridable method that that instantiates a unit test manager if one was specified in the command line arguments and hands it the name of the properties file to use to configure the system param args protected static void initialize manager string args if args length 3 try system out println using initialize properties from args 2 unit test manager um unit test manager class for name args 2 new instance system out println setting up initial properties using args 1 um initialize properties args 1 catch class not found exception e system out println couldn t create args 2 e print stack trace catch instantiation exception e system out println couldn t create args 2 e print stack trace catch illegal access exception e system out println couldn t create args 2 e print stack trace unittestmanager initializemanager initializeproperties unittestmanager unittestmanager forname newinstance initializeproperties classnotfoundexception printstacktrace instantiationexception printstacktrace illegalaccessexception printstacktrace public static test suite suite string args lib ext jmetertest properties org apache jmeter util j meter utils initialize manager args return suite args 0 testsuite jmeterutils initializemanager a unit test suite for j unit return the test suite private static test suite suite string search paths test suite suite new test suite all tests system out println scanning search paths for test cases int tests 0 int suites 0 try log info class finder test case list class list class finder find classes that extend j orphan utils split search paths new class test case class true int sz class list size log info class finder test case found sz test case classes system out println class finder found sz test case classes iterator classes class list iterator while classes has next string name string classes next try test suite only finds testxxx methods and does not look for suite methods to provide more compatibilty with stand alone tests where j unit does look for a suite method check for it first here class clazz class for name name test t null try method m clazz get method suite new class 0 t test m invoke clazz null suites catch no such method exception e this is not an error the others are catch security exception e catch illegal access exception e catch illegal argument exception e catch invocation target exception e if t null t new test suite clazz tests suite add test t catch exception ex system out println error adding test for class name ex to string log error error adding test ex catch io exception e log error e system out println created tests tests including suites suites return suite junit testsuite searchpaths testsuite testsuite searchpaths classfinder testcase classlist classfinder findclassesthatextend jorphanutils searchpaths testcase classlist classfinder testcase testcase classfinder testcase classlist hasnext testsuite junit forname getmethod nosuchmethodexception securityexception illegalaccessexception illegalargumentexception invocationtargetexception testsuite addtest tostring ioexception public class null sampler extends abstract sampler public sample result sample entry e return new sample result nullsampler abstractsampler sampleresult sampleresult private final string label public calculator this public calculator string label this label label public void clear maximum long min value minimum long max value sum 0 sum of squares 0 mean 0 deviation 0 count 0 min_value max_value sumofsquares public void add value long new value add value new value 1 addvalue newvalue addvalue newvalue private void add value long new value int sample count count sample count minimum math min new value minimum maximum math max new value maximum double current val new value sum current val sum of squares current val current val calculate each time as likely to be called for each add mean sum count deviation math sqrt sum of squares count mean mean addvalue newvalue samplecount samplecount newvalue newvalue currentval newvalue currentval sumofsquares currentval currentval sumofsquares public void add bytes long new value bytes new value addbytes newvalue newvalue public void add sample sample result res add bytes res get bytes add value res get time res get sample count errors res get error count account for multiple samples if start time 0 start time res get start time start time math min start time res get start time elapsed time math max elapsed time res get end time start time addsample sampleresult addbytes getbytes addvalue gettime getsamplecount geterrorcount starttime starttime getstarttime starttime starttime getstarttime elapsedtime elapsedtime getendtime starttime public long get total bytes return bytes gettotalbytes public double get mean return mean getmean public number get mean as number return new long long mean getmeanasnumber public double get standard deviation return deviation getstandarddeviation public long get min return minimum getmin public long get max return maximum getmax public int get count return count getcount public string get label return label getlabel returns the raw double value of the percentage of samples with errors that were recorded between 0 0 and 1 0 return the raw double value of the percentage of samples with errors that were recorded public double get error percentage double rval 0 0 if count 0 return rval rval double errors double count return rval geterrorpercentage returns the throughput associated to this sampler in requests per second may be slightly skewed because it takes the timestamps of the first and last samples as the total time passed and the test may actually have started before that start time and ended after that end time public double get rate if elapsed time 0 return 0 0 return double count double elapsed time 1000 getrate elapsedtime elapsedtime calculates the average page size which means divide the bytes by number of samples this is an ambiguous name so deprecated use get avg page bytes instead return average page size public double get page size if count 0 bytes 0 return double bytes count return 0 0 getavgpagebytes getpagesize calculates the average page size which means divide the bytes by number of samples return average page size in bytes public double get avg page bytes if count 0 bytes 0 return double bytes count return 0 0 getavgpagebytes throughput in bytes second return throughput in bytes second public double get bytes per second if elapsed time 0 return bytes double elapsed time 1000 1000 millisecs sec return 0 0 getbytespersecond elapsedtime elapsedtime throughput in kilobytes second return throughput in kilobytes second public double getkb per second return get bytes per second 1024 1024 bytes per kb getkbpersecond getbytespersecond private constructor to prevent instantiation private menu factory menufactory public static void add edit menu j popup menu menu boolean removable add separator menu if removable menu add make menu item res cut action names cut key strokes cut non nls 1 menu add make menu item res copy action names copy key strokes copy non nls 1 menu add make menu item res paste action names paste key strokes paste non nls 1 menu add make menu item res reset gui action names reset gui non nls 1 if removable menu add make menu item res remove action names remove key strokes remove non nls 1 addeditmenu jpopupmenu addseparator makemenuitemres actionnames keystrokes makemenuitemres actionnames keystrokes makemenuitemres actionnames keystrokes makemenuitemres reset_gui actionnames reset_gui makemenuitemres actionnames keystrokes public static void add paste reset menu j popup menu menu add separator menu menu add make menu item res paste action names paste key strokes paste non nls 1 menu add make menu item res reset gui action names reset gui non nls 1 addpasteresetmenu jpopupmenu addseparator makemenuitemres actionnames keystrokes makemenuitemres reset_gui actionnames reset_gui public static void add file menu j popup menu menu add separator menu menu add make menu item res open action names open non nls 1 menu add make menu item res menu merge action names merge non nls 1 menu add make menu item res save as action names save as non nls 1 add separator menu j menu item save picture make menu item res save as image non nls 1 action names save graphics key strokes save graphics menu add save picture if gui package get instance get current gui instanceof printable save picture set enabled false j menu item save picture all make menu item res save as image all non nls 1 action names save graphics all key strokes save graphics all menu add save picture all add separator menu j menu item disabled make menu item res disable action names disable non nls 1 j menu item enabled make menu item res enable action names enable non nls 1 boolean is enabled gui package get instance get tree listener get current node is enabled if is enabled disabled set enabled true enabled set enabled false else disabled set enabled false enabled set enabled true menu add enabled menu add disabled add separator menu menu add make menu item res help action names help non nls 1 addfilemenu jpopupmenu addseparator makemenuitemres actionnames makemenuitemres menu_merge actionnames makemenuitemres save_as actionnames save_as addseparator jmenuitem savepicture makemenuitemres save_as_image actionnames save_graphics keystrokes save_graphics savepicture guipackage getinstance getcurrentgui savepicture setenabled jmenuitem savepictureall makemenuitemres save_as_image_all actionnames save_graphics_all keystrokes save_graphics_all savepictureall addseparator jmenuitem makemenuitemres actionnames jmenuitem makemenuitemres actionnames isenabled guipackage getinstance gettreelistener getcurrentnode isenabled isenabled setenabled setenabled setenabled setenabled addseparator makemenuitemres actionnames public static j menu make menus string categories string label string action command j menu add menu new j menu label for int i 0 i categories length i add menu add make menu categories i action command return add menu jmenu makemenus actioncommand jmenu addmenu jmenu addmenu makemenu actioncommand addmenu public static j popup menu get default controller menu j popup menu pop new j popup menu pop add menu factory make menus menu add controller j meter utils get res string add non nls 1 action names add pop add make menus menu parent controller j meter utils get res string insert parent non nls 1 action names add parent menu factory add edit menu pop true menu factory add file menu pop return pop jpopupmenu getdefaultcontrollermenu jpopupmenu jpopupmenu menufactory makemenus menu_add_controller jmeterutils getresstring actionnames makemenus menu_parent_controller jmeterutils getresstring insert_parent actionnames add_parent menufactory addeditmenu menufactory addfilemenu public static j popup menu get default sampler menu j popup menu pop new j popup menu pop add menu factory make menus menu add sampler j meter utils get res string add non nls 1 action names add pop add make menus menu parent sampler j meter utils get res string insert parent non nls 1 action names add parent menu factory add edit menu pop true menu factory add file menu pop return pop jpopupmenu getdefaultsamplermenu jpopupmenu jpopupmenu menufactory makemenus menu_add_sampler jmeterutils getresstring actionnames makemenus menu_parent_sampler jmeterutils getresstring insert_parent actionnames add_parent menufactory addeditmenu menufactory addfilemenu public static j popup menu get default config element menu j popup menu pop new j popup menu menu factory add edit menu pop true menu factory add file menu pop return pop jpopupmenu getdefaultconfigelementmenu jpopupmenu jpopupmenu menufactory addeditmenu menufactory addfilemenu public static j popup menu get default visualizer menu j popup menu pop new j popup menu menu factory add edit menu pop true menu factory add file menu pop return pop jpopupmenu getdefaultvisualizermenu jpopupmenu jpopupmenu menufactory addeditmenu menufactory addfilemenu public static j popup menu get default timer menu j popup menu pop new j popup menu menu factory add edit menu pop true menu factory add file menu pop return pop jpopupmenu getdefaulttimermenu jpopupmenu jpopupmenu menufactory addeditmenu menufactory addfilemenu public static j popup menu get default assertion menu j popup menu pop new j popup menu menu factory add edit menu pop true menu factory add file menu pop return pop jpopupmenu getdefaultassertionmenu jpopupmenu jpopupmenu menufactory addeditmenu menufactory addfilemenu public static j popup menu get default extractor menu j popup menu pop new j popup menu menu factory add edit menu pop true menu factory add file menu pop return pop jpopupmenu getdefaultextractormenu jpopupmenu jpopupmenu menufactory addeditmenu menufactory addfilemenu create a menu from a menu category param category predefined string used as key for menu map hash map and messages properties lookup param action command predefined string e g action names add see org apache jmeter gui action action names return the menu public static j menu make menu string category string action command return make menu collection menu map get category action command j meter utils get res string category menumap hashmap actioncommand actionnames actionnames jmenu makemenu actioncommand makemenu menumap actioncommand jmeterutils getresstring create a menu from a collection of items param menu info collection of menu info items param action command predefined string e g action names add see org apache jmeter gui action action names param menu name return the menu public static j menu make menu collection menu info string action command string menu name iterator iter menu info iterator j menu menu new j menu menu name while iter has next menu info info menu info iter next menu add make menu item info action command return menu menuinfo menuinfo actioncommand actionnames actionnames menuname jmenu makemenu menuinfo actioncommand menuname menuinfo jmenu jmenu menuname hasnext menuinfo menuinfo makemenuitem actioncommand public static void set enabled j menu menu if menu get sub elements length 0 menu set enabled false setenabled jmenu getsubelements setenabled create a single menu item param label for the menu item param name for the menu item param action command predefined string e g action names add see org apache jmeter gui action action names return the menu item public static j menu item make menu item string label string name string action command j menu item new menu choice new j menu item label new menu choice set name name new menu choice add action listener action router get instance if action command null new menu choice set action command action command return new menu choice menuitem menuitem actioncommand actionnames actionnames jmenuitem makemenuitem actioncommand jmenuitem newmenuchoice jmenuitem newmenuchoice setname newmenuchoice addactionlistener actionrouter getinstance actioncommand newmenuchoice setactioncommand actioncommand newmenuchoice create a single menu item from the resource name param resource for the menu item param action command predefined string e g action names add see org apache jmeter gui action action names return the menu item public static j menu item make menu item res string resource string action command j menu item new menu choice new j menu item j meter utils get res string resource new menu choice set name resource new menu choice add action listener action router get instance if action command null new menu choice set action command action command return new menu choice menuitem actioncommand actionnames actionnames jmenuitem makemenuitemres actioncommand jmenuitem newmenuchoice jmenuitem jmeterutils getresstring newmenuchoice setname newmenuchoice addactionlistener actionrouter getinstance actioncommand newmenuchoice setactioncommand actioncommand newmenuchoice create a single menu item from a menu info object param info the menu info object param action command predefined string e g action names add see org apache jmeter gui action action names return the menu item public static component make menu item menu info info string action command j menu item new menu choice new j menu item info get label new menu choice set name info get class name new menu choice add action listener action router get instance if action command null new menu choice set action command action command return new menu choice menuinfo menuinfo actioncommand actionnames actionnames makemenuitem menuinfo actioncommand jmenuitem newmenuchoice jmenuitem getlabel newmenuchoice setname getclassname newmenuchoice addactionlistener actionrouter getinstance actioncommand newmenuchoice setactioncommand actioncommand newmenuchoice public static j menu item make menu item res string resource string action command key stroke accel j menu item item make menu item res resource action command item set accelerator accel return item jmenuitem makemenuitemres actioncommand keystroke jmenuitem makemenuitemres actioncommand setaccelerator public static j menu item make menu item string label string name string action command key stroke accel j menu item item make menu item label name action command item set accelerator accel return item jmenuitem makemenuitem actioncommand keystroke jmenuitem makemenuitem actioncommand setaccelerator private static void initialize menus try list gui classes class finder find classes that extend j meter utils get search paths new class j metergui component class test bean class collections sort gui classes iterator iter gui classes iterator while iter has next string name string iter next j meter tree node and test beangui are special gui classes and aren t intended to be added to menus todo find a better way of checking this if name ends with j meter tree node non nls 1 name ends with test beangui non nls 1 continue don t try to instantiate these j metergui component item try class c class for name name if test bean class is assignable from c item new test beangui c else item j metergui component c new instance catch no class def found error e log warn missing jar could not create name e continue catch throwable e log warn could not instantiate name e continue if elements to skip contains name elements to skip contains item get static label log info skipping name continue else elements to skip add name collection categories item get menu categories if categories null log debug name participates in no menus continue if categories contains timers timers add new menu info item name if categories contains post processors post processors add new menu info item name if categories contains pre processors pre processors add new menu info item name if categories contains controllers controllers add new menu info item name if categories contains samplers samplers add new menu info item name if categories contains non test elements non test elements add new menu info item name if categories contains listeners listeners add new menu info item name if categories contains config elements config elements add new menu info item name if categories contains assertions assertions add new menu info item name catch io exception e log error e initializemenus guiclasses classfinder findclassesthatextend jmeterutils getsearchpaths jmeterguicomponent testbean guiclasses guiclasses hasnext jmetertreenode testbeangui endswith jmetertreenode endswith testbeangui jmeterguicomponent forname testbean isassignablefrom testbeangui jmeterguicomponent newinstance noclassdeffounderror elementstoskip elementstoskip getstaticlabel elementstoskip getmenucategories menuinfo post_processors postprocessors menuinfo pre_processors preprocessors menuinfo menuinfo menuinfo non_test_elements nontestelements menuinfo menuinfo config_elements configelements menuinfo menuinfo ioexception private static void add separator j popup menu menu menu element elements menu get sub elements if elements length 0 elements elements length 1 instanceof j popup menu separator menu add separator addseparator jpopupmenu menuelement getsubelements jpopupmenu addseparator determine whether or not nodes can be added to this parent used by merge param parent node param element top level test element to be added return whether it is ok to add the element to this parent public static boolean can add to j meter tree node parent node test element element j meter tree node node new j meter tree node element null return can add to parent node new j meter tree node node parentnode canaddto jmetertreenode parentnode testelement jmetertreenode jmetertreenode canaddto parentnode jmetertreenode determine whether or not nodes can be added to this parent used by dragn drop and paste param parent node param nodes array of nodes that are to be added return whether it is ok to add the dragged nodes to this parent public static boolean can add to j meter tree node parent node j meter tree node nodes if null parent node return false if found class nodes new class work bench class can t add a workbench anywhere return false if found class nodes new class test plan class can t add a test plan anywhere return false test element parent parent node get test element if parent instanceof work bench allow everything else return true if parent instanceof test plan if found class nodes new class sampler class controller class samplers and controllers need not apply org apache jmeter threads thread group class but thread group controller is ok return false return true thread group is only allowed under a test plan if found class nodes new class org apache jmeter threads thread group class return false if parent instanceof controller includes thread group anything goes return true if parent instanceof sampler samplers and controllers need not apply if found class nodes new class sampler class controller class return false return true all other return false dragndrop parentnode canaddto jmetertreenode parentnode jmetertreenode parentnode foundclass workbench foundclass testplan testplan testelement parentnode gettestelement workbench testplan foundclass threadgroup threadgroup threadgroup testplan foundclass threadgroup foundclass is any node an instance of one of the classes private static boolean found class j meter tree node nodes class classes for int i 0 i nodes length i j meter tree node node nodes i for int j 0 j classes length j if classes j is instance node get user object return true return false foundclass jmetertreenode jmetertreenode isinstance getuserobject is any node an instance of one of the classes but not an exception private static boolean found class j meter tree node nodes class classes class except for int i 0 i nodes length i j meter tree node node nodes i object user object node get user object if except is instance user object for int j 0 j classes length j if classes j is instance user object return true return false foundclass jmetertreenode jmetertreenode userobject getuserobject isinstance userobject isinstance userobject methods used for test cases static int menumap size return menu map size menumap_size menumap return menu map size static int assertions size return assertions size menumap assertions_size return assertions size static int configelements size return config elements size configelements_size configelements return config elements size static int controllers size return controllers size configelements controllers_size return controllers size static int listeners size return listeners size listeners_size return listeners size static int nontestelements size return non test elements size nontestelements_size nontestelements return non test elements size static int postprocessors size return post processors size nontestelements postprocessors_size postprocessors return post processors size static int preprocessors size return pre processors size postprocessors preprocessors_size preprocessors return pre processors size static int samplers size return samplers size preprocessors samplers_size return samplers size static int timers size return timers size timers_size return timers size static int elementstoskip size return elements to skip size elementstoskip_size elementstoskip create the header public header this set name this set value setname setvalue create the coookie public header string name string value this set name name this set value value setname setvalue public void add config element config element config addconfigelement configelement public boolean expects modification return false expectsmodification get the name for this object public synchronized string get name return get property as string hname getname getpropertyasstring set the name for this object public synchronized void set name string name this set property hname name setname setproperty get the value for this object public synchronized string get value return get property as string value getvalue getpropertyasstring set the value for this object public synchronized void set value string value this set property value value setvalue setproperty creates a string representation of this header public string to string return get name t get value non nls 1 tostring getname getvalue public monitor stats super monitorstats default constructor param health param load param cpuload param memload param threadload param host param port param protocol param time public monitor stats int health int load int cpuload int memload int threadload string host string port string protocol long time this set health health this set load load this set cpu load cpuload this set mem load memload this set thread load threadload this set host host this set port port this set protocol protocol this set time stamp time monitorstats sethealth setload setcpuload setmemload setthreadload sethost setport setprotocol settimestamp for convienance this method returns the protocol host and port as a url return protocol host port public string geturl return this get protocol this get host this get port getprotocol gethost getport public void set health int health this set property health string value of health sethealth setproperty valueof public void set load int load this set property load string value of load setload setproperty valueof public void set cpu load int load this set property cpuload string value of load setcpuload setproperty valueof public void set mem load int load this set property memload string value of load setmemload setproperty valueof public void set thread load int load this set property threadload string value of load setthreadload setproperty valueof public void set host string host this set property host host sethost setproperty public void set port string port this set property port port setport setproperty public void set protocol string protocol this set property protocol protocol setprotocol setproperty public void set time stamp long time this set property timestamp string value of time settimestamp setproperty valueof public int get health return this get property as int health gethealth getpropertyasint public int get load return this get property as int load getload getpropertyasint public int get cpu load return this get property as int cpuload getcpuload getpropertyasint public int get mem load return this get property as int memload getmemload getpropertyasint public int get thread load return this get property as int threadload getthreadload getpropertyasint public string get host return this get property as string host gethost getpropertyasstring public string get port return this get property as string port getport getpropertyasstring public string get protocol return this get property as string protocol getprotocol getpropertyasstring public long get time stamp return this get property as long timestamp gettimestamp getpropertyaslong http sampler base partial config public url config test string name super name httpsamplerbase partialconfig urlconfigtest protected void set up arguments args new arguments args add argument username mstover args add argument password pass args add argument action login config new http null sampler config set name full config config set property http sampler base domain www lazer com config set property http sampler base path login jsp config set property http sampler base method http sampler base post config set property new test element property http sampler base arguments args default config new http null sampler default config set name default default config set property http sampler base domain www xerox com default config set property http sampler base path default html partial config new http null sampler partial config set property http sampler base path main jsp partial config set property http sampler base method http sampler base get setup addargument addargument addargument httpnullsampler setname setproperty httpsamplerbase setproperty httpsamplerbase setproperty httpsamplerbase httpsamplerbase setproperty testelementproperty httpsamplerbase defaultconfig httpnullsampler defaultconfig setname defaultconfig setproperty httpsamplerbase defaultconfig setproperty httpsamplerbase partialconfig httpnullsampler partialconfig setproperty httpsamplerbase partialconfig setproperty httpsamplerbase httpsamplerbase public void test simple config assert true config get name equals full config assert equals config get domain www lazer com testsimpleconfig asserttrue getname assertequals getdomain public void test over ride j meter property jmp partial config get property http sampler base domain assert true jmp instanceof null property assert true new null property http sampler base domain equals jmp partial config add test element default config assert equals partial config get property as string http sampler base domain www xerox com assert equals partial config get property as string http sampler base path main jsp testoverride jmeterproperty partialconfig getproperty httpsamplerbase asserttrue nullproperty asserttrue nullproperty httpsamplerbase partialconfig addtestelement defaultconfig assertequals partialconfig getpropertyasstring httpsamplerbase assertequals partialconfig getpropertyasstring httpsamplerbase public final class j meter context service private static final thread local thread context new thread local public object initial value return new j meter context jmetercontextservice threadlocal threadcontext threadlocal initialvalue jmetercontext private constructor to prevent instantiation private j meter context service jmetercontextservice gives access to the current thread context return the current thread context public static j meter context get context return j meter context thread context get jmetercontext getcontext jmetercontext threadcontext method is called by the j meter engine class when a test run is started zeroes number of active threads saves current time in a field and in the j meter property teststart ms public static synchronized void start test if test start 0 number of active threads 0 test start system current time millis j meter utils set property teststart ms long to string test start non nls 1 jmeterengine numberofactivethreads jmeter starttest teststart numberofactivethreads teststart currenttimemillis jmeterutils setproperty tostring teststart increment number of active threads static synchronized void incr number of threads number of active threads incrnumberofthreads numberofactivethreads decrement number of active threads static synchronized void decr number of threads number of active threads decrnumberofthreads numberofactivethreads get the number of currently active threads return active thread count public static synchronized int get number of threads return number of active threads getnumberofthreads numberofactivethreads called by main frame test ended clears start time field public static synchronized void end test test start 0 mainframe testended endtest teststart public static synchronized long get test start time not used return test start getteststarttime teststart get the total number of threads active return total thread count public static synchronized int get total threads return total threads gettotalthreads totalthreads update the total number of threads param this group number of threads in this thread group public static synchronized void add total threads int this group total threads this group thisgroup addtotalthreads thisgroup totalthreads thisgroup set total threads to zero public static synchronized void clear total threads total threads 0 cleartotalthreads totalthreads public j meter tree node allow serializable test to work todo is the serializable test necessary now that j meter tree node is no longer a gui component this null null jmetertreenode jmetertreenode public j meter tree node test element user obj j meter tree model tree model super user obj this tree model tree model jmetertreenode testelement userobj jmetertreemodel treemodel userobj treemodel treemodel public boolean is enabled return abstract test element get test element get property as boolean test element enabled isenabled abstracttestelement gettestelement getpropertyasboolean testelement public void set enabled boolean enabled get test element set property new boolean property test element enabled enabled tree model node changed this setenabled gettestelement setproperty booleanproperty testelement treemodel nodechanged public image icon get icon return get icon true imageicon geticon geticon public image icon get icon boolean enabled test element test element get test element try if test element instanceof test bean class test class test element get class try image img introspector get bean info test class get icon bean info icon color 16x16 if icon has not been defined then use gui class property if img null object clazz introspector get bean info test class get bean descriptor get value test element gui class if clazz null log warn get icon can t obtain gui class from test class get name return null return gui factory get icon class for name string clazz enabled return new image icon img catch introspection exception e1 log error can t obtain icon for class test element e1 throw new org apache jorphan util j meter error e1 return gui factory get icon class for name test element get property as string test element gui class enabled catch class not found exception e log warn can t get icon for class test element e return null imageicon geticon testelement testelement gettestelement testelement testbean testclass testelement getclass getbeaninfo testclass geticon beaninfo icon_color_16x16 gui_class getbeaninfo testclass getbeandescriptor getvalue testelement gui_class geticon testclass getname guifactory geticon forname imageicon introspectionexception testelement jmetererror guifactory geticon forname testelement getpropertyasstring testelement gui_class classnotfoundexception testelement public collection get menu categories try return gui package get instance get gui get test element get menu categories catch exception e log error can t get popup menu for gui e return null getmenucategories guipackage getinstance getgui gettestelement getmenucategories public j popup menu create popup menu try return gui package get instance get gui get test element create popup menu catch exception e log error can t get popup menu for gui e return null jpopupmenu createpopupmenu guipackage getinstance getgui gettestelement createpopupmenu public test element get test element return test element get user object testelement gettestelement testelement getuserobject public string get static label return gui package get instance get gui test element get user object get static label getstaticlabel guipackage getinstance getgui testelement getuserobject getstaticlabel public string get doc anchor return gui package get instance get gui test element get user object get doc anchor getdocanchor guipackage getinstance getgui testelement getuserobject getdocanchor public void set name string name test element get user object set name name setname testelement getuserobject setname public string get name return test element get user object get name getname testelement getuserobject getname public void name changed tree model node changed this namechanged treemodel nodechanged private static final number field error listener listener new number field error listener public static number field error listener get number field error listener return listener numberfielderrorlistener numberfielderrorlistener numberfielderrorlistener getnumberfielderrorlistener public void focus lost focus event e component source component e get source string text if source instanceof j text component text j text component source get text else if source instanceof text component text text component source get text try integer parse int text catch number format exception nfe j option pane show message dialog source j meter utils get res string you must enter a valid number non nls 1 j meter utils get res string invalid data non nls 1 j option pane warning message new focus requester source focuslost focusevent getsource jtextcomponent jtextcomponent gettext textcomponent textcomponent gettext parseint numberformatexception joptionpane showmessagedialog jmeterutils getresstring you_must_enter_a_valid_number jmeterutils getresstring invalid_data joptionpane warning_message focusrequester the default implementation will use default tree table model public j tree table super new default tree table model defaulttreetablemodel jtreetable defaulttreetablemodel param num rows param num columns public j tree table int num rows int num columns super num rows num columns numrows numcolumns jtreetable numrows numcolumns numrows numcolumns param dm public j tree table tree table model dm super dm jtreetable treetablemodel param row data param column names public j tree table object row data object column names super row data column names rowdata columnnames jtreetable rowdata columnnames rowdata columnnames param row data param column names public j tree table vector row data vector column names super row data column names rowdata columnnames jtreetable rowdata columnnames rowdata columnnames see org apache jmeter functions function execute sample result sampler public string execute sample result previous result sampler current sampler throws invalid variable exception return thread current thread get name substring thread current thread get name last index of 1 non nls 1 sampleresult sampleresult previousresult currentsampler invalidvariableexception currentthread getname currentthread getname lastindexof see org apache jmeter functions function set parameters collection public void set parameters collection parameters throws invalid variable exception check parameter count parameters 0 0 setparameters setparameters invalidvariableexception checkparametercount see org apache jmeter functions function get reference key public string get reference key return key getreferencekey getreferencekey see org apache jmeter functions function get argument desc public list get argument desc return desc getargumentdesc getargumentdesc protected connection factory super connectionfactory public void test started string test teststarted public void test ended string test test ended testended testended end test cleans up the client see junit framework test listener end test junit framework test public synchronized void test ended connection factory factory null n b static reference endtest testlistener endtest testended connectionfactory start test sets up the client and gets it ready for the test since async messaging is different than request response applications the connection is created at the beginning of the test and closed at the end of the test public void test started starttest teststarted public void test iteration start loop iteration event event testiterationstart loopiterationevent public static synchronized topic connection factory get topic connection factory context ctx string fac int counter max retry while factory null counter 0 try object objfac ctx lookup fac if objfac instanceof topic connection factory factory topic connection factory objfac catch naming exception e if counter max retry log error unable to find connection factory fac will retry error e to string else if counter 1 log error unable to find connection factory fac giving up error e to string counter try thread current thread sleep pause millis catch interrupted exception ie do nothing getting interrupted is acceptable return factory topicconnectionfactory gettopicconnectionfactory max_retry topicconnectionfactory topicconnectionfactory namingexception max_retry tostring tostring currentthread pause_millis interruptedexception public static synchronized queue connection factory get queue connection factory context ctx string fac int counter max retry while qfactory null counter 0 try object objfac ctx lookup fac if objfac instanceof queue connection factory qfactory queue connection factory objfac catch naming exception e if counter max retry log error unable to find connection factory fac will retry error e to string else if counter 1 log error unable to find connection factory fac giving up error e to string counter try thread current thread sleep pause millis catch interrupted exception ie do nothing getting interrupted is acceptable return qfactory queueconnectionfactory getqueueconnectionfactory max_retry queueconnectionfactory queueconnectionfactory namingexception max_retry tostring tostring currentthread pause_millis interruptedexception public static synchronized topic connection get topic connection if factory null try return factory create topic connection catch jms exception e log error e get message return null topicconnection gettopicconnection createtopicconnection jmsexception getmessage public static synchronized queue connection get queue connection context ctx string queue conn if factory null try return qfactory create queue connection catch jms exception e log error e get message return null queueconnection getqueueconnection queueconn createqueueconnection jmsexception getmessage for test bean implementations only public bsf test element super init testbean bsftestelement private void init parameters ensure variables are not null filename script script language scriptlanguage protected object read resolve init return this readresolve public object clone bsf test element o bsf test element super clone o init return o bsftestelement bsftestelement protected bsf manager get manager throws bsf exception bsf manager mgr new bsf manager init manager mgr return mgr bsfmanager getmanager bsfexception bsfmanager bsfmanager initmanager protected void init manager bsf manager mgr throws bsf exception final string label get name final string file name get filename final string script parameters get parameters use actual class name for log final logger logger logging manager get logger for short name get class get name mgr declare bean log logger logger class non nls 1 mgr declare bean label label string class non nls 1 mgr declare bean file name file name string class non nls 1 mgr declare bean parameters script parameters string class non nls 1 string args j orphan utils split script parameters non nls 1 mgr declare bean args args args get class non nls 1 add variables for access to context and variables j meter context jmctx j meter context service get context j meter variables vars jmctx get variables properties props j meter utils getj meter properties mgr declare bean ctx jmctx jmctx get class non nls 1 mgr declare bean vars vars vars get class non nls 1 mgr declare bean props props props get class non nls 1 for use in debugging mgr declare bean out system out print stream class non nls 1 most subclasses will need these sampler sampler jmctx get current sampler mgr declare bean sampler sampler sampler class sample result prev jmctx get previous result mgr declare bean prev prev sample result class initmanager bsfmanager bsfexception getname filename getfilename scriptparameters getparameters loggingmanager getloggerforshortname getclass getname declarebean declarebean declarebean filename filename declarebean scriptparameters jorphanutils scriptparameters declarebean getclass jmetercontext jmetercontextservice getcontext jmetervariables getvariables jmeterutils getjmeterproperties declarebean getclass declarebean getclass declarebean getclass declarebean printstream getcurrentsampler declarebean sampleresult getpreviousresult declarebean sampleresult protected void process file or script bsf manager mgr throws bsf exception bsf engine bsf engine mgr load scripting engine get script language final string script file get filename if script file length 0 bsf engine exec script 0 0 get script else we have a file read and process it try string script file utils read file to string new file script file bsf engine exec script file 0 0 script catch io exception e log warn e get localized message throw new bsf exception bsf exception reason io error problem reading script file e processfileorscript bsfmanager bsfexception bsfengine bsfengine loadscriptingengine getscriptlanguage scriptfile getfilename scriptfile bsfengine getscript fileutils readfiletostring scriptfile bsfengine scriptfile ioexception getlocalizedmessage bsfexception bsfexception reason_io_error return the script test bean version must be overridden for subclasses that don t implement test bean otherwise the clone method won t work return the script to execute public string get script return script testbean testbean getscript set the script test bean version must be overridden for subclasses that don t implement test bean otherwise the clone method won t work param s the script to execute may be blank public void set script string s script s testbean testbean setscript public string get parameters return parameters getparameters public void set parameters string s parameters s setparameters public string get filename return filename getfilename public void set filename string s filename s setfilename public string get script language return script language getscriptlanguage scriptlanguage public void set script language string s script language s setscriptlanguage scriptlanguage param arg0 public line graph test string arg0 super arg0 linegraphtest public void test generate line chart log info jtl version j meter utils get property file format testlog string sample log c eclipse3 workspace jmeter 21 bin testfiles sample log1 jtl string sample log testfiles sample log1 jtl string sample log2 testfiles sample log1b jtl string sample log3 testfiles sample log1c jtl jtl data input new jtl data jtl data input2 new jtl data jtl data input3 new jtl data input set data source sample log input load data input2 set data source sample log2 input2 load data input3 set data source sample log3 input3 load data assert true input get start timestamp 0 assert true input get end timestamp input get start timestamp assert true input getur ls size 0 log info url count input getur ls size java util array list list new java util array list list add input list add input2 list add input3 line chart lgraph new line chart lgraph set title sample line graph lgraph set caption sample lgraph set name sample lgraph sety axis milliseconds lgraph sety label test runs lgraph setx axis abstract table report table max lgraph setx label abstract chart x data filename label lgraph setur ls jakarta home jmeter home j component gr lgraph render chart list assert not null gr save graphics service serv new save graphics service string filename lgraph get title filename filename replace if true equals ignore case system get property java awt headless serv savej component testfiles filename save graphics service png gr testgeneratelinechart jmeterutils getproperty file_format samplelog sample_log1 samplelog sample_log1 samplelog2 sample_log1b samplelog3 sample_log1c jtldata jtldata jtldata jtldata jtldata jtldata setdatasource samplelog loaddata setdatasource samplelog2 loaddata setdatasource samplelog3 loaddata asserttrue getstarttimestamp asserttrue getendtimestamp getstarttimestamp asserttrue geturls geturls arraylist arraylist linechart linechart settitle setcaption setname setyaxis setylabel setxaxis abstracttable report_table_max setxlabel abstractchart x_data_filename_label seturls jakarta_home jmeter_home jcomponent renderchart assertnotnull savegraphicsservice savegraphicsservice gettitle _ equalsignorecase getproperty savejcomponent savegraphicsservice the x path extractor public string get label resource return xpath extractor title non nls 1 xpathextractor getlabelresource xpath_extractor_title public x path extractor gui super init xpathextractorgui public void configure test element el super configure el x path extractor xpe x path extractor el xpath query field set text xpe getx path query default field set text xpe get default value ref name field set text xpe get ref name tolerant set selected xpe is tolerant quiet set selected xpe is quiet show warnings set selected xpe show warnings report errors set selected xpe report errors name space set selected xpe use name space set tidy options tolerant is selected testelement xpathextractor xpathextractor xpathqueryfield settext getxpathquery defaultfield settext getdefaultvalue refnamefield settext getrefname setselected istolerant setselected isquiet showwarnings setselected showwarnings reporterrors setselected reporterrors namespace setselected usenamespace settidyoptions isselected public test element create test element x path extractor extractor new x path extractor modify test element extractor return extractor testelement createtestelement xpathextractor xpathextractor modifytestelement public void modify test element test element extractor super configure test element extractor if extractor instanceof x path extractor x path extractor xpath x path extractor extractor xpath set default value default field get text xpath set ref name ref name field get text xpath setx path query xpath query field get text xpath set tolerant tolerant is selected xpath set name space name space is selected xpath set show warnings show warnings is selected xpath set report errors report errors is selected xpath set quiet quiet is selected modifytestelement testelement configuretestelement xpathextractor xpathextractor xpathextractor setdefaultvalue defaultfield gettext setrefname refnamefield gettext setxpathquery xpathqueryfield gettext settolerant isselected setnamespace namespace isselected setshowwarnings showwarnings isselected setreporterrors reporterrors isselected setquiet isselected implements j metergui component clear gui public void clear gui super clear gui xpath query field set text non nls 1 default field set text non nls 1 ref name field set text non nls 1 tolerant set selected false name space set selected true quiet set selected true report errors set selected false show warnings set selected false jmeterguicomponent cleargui cleargui cleargui xpathqueryfield settext defaultfield settext refnamefield settext setselected namespace setselected setselected reporterrors setselected showwarnings setselected private void set tidy options boolean tidy selected quiet set enabled tidy selected report errors set enabled tidy selected show warnings set enabled tidy selected name space set enabled tidy selected settidyoptions tidyselected setenabled tidyselected reporterrors setenabled tidyselected showwarnings setenabled tidyselected namespace setenabled tidyselected private void init set layout new border layout set border make border box box box create vertical box box add make title panel box options box create horizontal box tolerant new j check box j meter utils get res string xpath extractor tolerant non nls 1 quiet new j check box j meter utils get res string xpath tidy quiet true non nls 1 report errors new j check box j meter utils get res string xpath tidy report errors true non nls 1 show warnings new j check box j meter utils get res string xpath tidy show warnings true non nls 1 name space new j check box j meter utils get res string xpath extractor namespace true non nls 1 tolerant add action listener new action listener public void action performed action event e set tidy options tolerant is selected set tidy options tolerant is selected box tidy options box create horizontal box tidy options add tolerant tidy options add quiet tidy options add report errors tidy options add show warnings tidy options set border border factory create etched border options add tidy options options add name space box add options add box border layout north add make parameter panel border layout center setlayout borderlayout setborder makeborder createverticalbox maketitlepanel createhorizontalbox jcheckbox jmeterutils getresstring xpath_extractor_tolerant jcheckbox jmeterutils getresstring xpath_tidy_quiet reporterrors jcheckbox jmeterutils getresstring xpath_tidy_report_errors showwarnings jcheckbox jmeterutils getresstring xpath_tidy_show_warnings namespace jcheckbox jmeterutils getresstring xpath_extractor_namespace addactionlistener actionlistener actionperformed actionevent settidyoptions isselected settidyoptions isselected tidyoptions createhorizontalbox tidyoptions tidyoptions tidyoptions reporterrors tidyoptions showwarnings tidyoptions setborder borderfactory createetchedborder tidyoptions namespace borderlayout makeparameterpanel borderlayout tolerant add action listener new action listener public void action performed action event e set tidy options tolerant is selected addactionlistener actionlistener actionperformed actionevent settidyoptions isselected private j panel make parameter panel xpath query field new j labeled text field j meter utils get res string xpath extractor query non nls 1 default field new j labeled text field j meter utils get res string default value field non nls 1 ref name field new j labeled text field j meter utils get res string ref name field non nls 1 j panel panel new j panel new grid bag layout grid bag constraints gbc new grid bag constraints init constraints gbc add field panel ref name field gbc reset contraints gbc add field panel xpath query field gbc reset contraints gbc gbc weighty 1 add field panel default field gbc return panel jpanel makeparameterpanel xpathqueryfield jlabeledtextfield jmeterutils getresstring xpath_extractor_query defaultfield jlabeledtextfield jmeterutils getresstring default_value_field refnamefield jlabeledtextfield jmeterutils getresstring ref_name_field jpanel jpanel gridbaglayout gridbagconstraints gridbagconstraints initconstraints addfield refnamefield resetcontraints addfield xpathqueryfield resetcontraints addfield defaultfield private void add field j panel panel j labeled text field field grid bag constraints gbc list item field get component list panel add component item get 0 gbc clone gbc gridx gbc weightx 1 gbc fill grid bag constraints horizontal panel add component item get 1 gbc clone addfield jpanel jlabeledtextfield gridbagconstraints getcomponentlist gridbagconstraints private void reset contraints grid bag constraints gbc gbc gridx 0 gbc gridy gbc weightx 0 gbc fill grid bag constraints none resetcontraints gridbagconstraints gridbagconstraints private void init constraints grid bag constraints gbc gbc anchor grid bag constraints northwest gbc fill grid bag constraints none gbc gridheight 1 gbc gridwidth 1 gbc gridx 0 gbc gridy 0 gbc weightx 0 gbc weighty 0 initconstraints gridbagconstraints gridbagconstraints gridbagconstraints private transient string share mode private object read resolve recycle true return this sharemode readresolve public void iteration start loop iteration event iter event file server server file server get file server final j meter context context get thread context if vars null string filename get filename string mode get share mode int mode int csv data set bean info get share mode as int mode switch mode int case csv data set bean info share all alias filename break case csv data set bean info share group alias filename system identity hash code context get thread group break case csv data set bean info share thread alias filename system identity hash code context get thread break default alias filename mode user specified key break server reserve file filename get file encoding alias vars j orphan utils split get variable names non nls 1 try string delim get delimiter if delim equals t non nls 1 delim t make it easier to enter a tab non nls 1 else if delim length 0 log warn empty delimiter converted to delim todo fetch this once as per vars above j meter variables thread vars context get variables string line server read line alias get recycle if line null i e not eof string line values get quoted data csv save service csv split string line delim char at 0 j orphan utils split line delim false for int a 0 a vars length a line values length a thread vars put vars a line values a todo report unused columns todo provide option to set unused variables else if get stop thread throw new j meter stop thread exception end of file detected for int a 0 a vars length a thread vars put vars a eofvalue catch io exception e todo should the error be indicated in the variables log error e to string iterationstart loopiterationevent iterevent fileserver fileserver getfileserver jmetercontext getthreadcontext _filename getfilename getsharemode modeint csvdatasetbeaninfo getsharemodeasint modeint csvdatasetbeaninfo share_all _filename csvdatasetbeaninfo share_group _filename identityhashcode getthreadgroup csvdatasetbeaninfo share_thread _filename identityhashcode getthread _filename reservefile _filename getfileencoding jorphanutils getvariablenames getdelimiter jmetervariables threadvars getvariables readline getrecycle linevalues getquoteddata csvsaveservice csvsplitstring charat jorphanutils linevalues threadvars linevalues getstopthread jmeterstopthreadexception threadvars ioexception tostring return returns the filename public string get filename return filename getfilename param filename the filename to set public void set filename string filename this filename filename setfilename return returns the file encoding public string get file encoding return file encoding getfileencoding fileencoding param file encoding the file encoding to set public void set file encoding string file encoding this file encoding file encoding fileencoding fileencoding setfileencoding fileencoding fileencoding fileencoding return returns the variable names public string get variable names return variable names variablenames getvariablenames variablenames param variable names the variable names to set public void set variable names string variable names this variable names variable names variablenames variablenames setvariablenames variablenames variablenames variablenames public string get delimiter return delimiter getdelimiter public void set delimiter string delimiter this delimiter delimiter setdelimiter public boolean get quoted data return quoted getquoteddata public void set quoted data boolean quoted this quoted quoted setquoteddata public boolean get recycle return recycle getrecycle public void set recycle boolean recycle this recycle recycle setrecycle public boolean get stop thread return stop thread getstopthread stopthread public void set stop thread boolean value this stop thread value setstopthread stopthread public string get share mode return share mode getsharemode sharemode public void set share mode string value this share mode value setsharemode sharemode public constant throughput timer bean info super constant throughput timer class resource bundle rb resource bundle get bean descriptor get value resource bundle these must agree with the timer resources tags 0 rb get string calc mode 1 non nls 1 tags 1 rb get string calc mode 2 non nls 1 tags 2 rb get string calc mode 3 non nls 1 tags 3 rb get string calc mode 4 non nls 1 tags 4 rb get string calc mode 5 non nls 1 create property group delay non nls 1 new string throughput non nls 1 calc mode non nls 1 property descriptor p property throughput non nls 1 p set value not undefined boolean true p set value default new double 0 0 p property calc mode non nls 1 p set value not undefined boolean true p set value default tags 0 p set value not other boolean true p set value not expression boolean true p set value tags tags constantthroughputtimerbeaninfo constantthroughputtimer resourcebundle resourcebundle getbeandescriptor getvalue resource_bundle getstring calcmode getstring calcmode getstring calcmode getstring calcmode getstring calcmode createpropertygroup calcmode propertydescriptor setvalue not_undefined setvalue calcmode setvalue not_undefined setvalue setvalue not_other setvalue not_expression setvalue todo need to find better way to do this public static int get calc mode as int string mode for int i 0 i tags length i if tags i equals mode return i return 1 getcalcmodeasint public final static color purple new j meter color 150 255f 0 150 255f public j meter color float r float g float b super r g b jmetercolor jmetercolor public j meter color super 0 0 0 jmetercolor see org apache jmeter gui action command do action action event public void do action action event e string action e get action command report gui package gui package report gui package get instance report tree node dragged nodes gui package get tree listener get dragged nodes report tree listener tree listener gui package get tree listener report tree node current node tree listener get current node report tree node parent node report tree node current node get parent test element te current node get test element if te instanceof test plan te instanceof work bench parent node null so elements can only be added as children system out println action te get class get name if add equals action can add to current node remove nodes from parents dragged nodes for int i 0 i dragged nodes length i report gui package get instance get tree model insert node into dragged nodes i current node current node get child count else if insert before equals action can add to parent node remove nodes from parents dragged nodes for int i 0 i dragged nodes length i int index parent node get index current node report gui package get instance get tree model insert node into dragged nodes i parent node index else if insert after equals action can add to parent node remove nodes from parents dragged nodes for int i 0 i dragged nodes length i int index parent node get index current node 1 report gui package get instance get tree model insert node into dragged nodes i parent node index report gui package get instance get main frame repaint doaction actionevent doaction actionevent getactioncommand reportguipackage guipackage reportguipackage getinstance reporttreenode draggednodes guipackage gettreelistener getdraggednodes reporttreelistener treelistener guipackage gettreelistener reporttreenode currentnode treelistener getcurrentnode reporttreenode parentnode reporttreenode currentnode getparent testelement currentnode gettestelement testplan workbench parentnode getclass getname canaddto currentnode removenodesfromparents draggednodes draggednodes reportguipackage getinstance gettreemodel insertnodeinto draggednodes currentnode currentnode getchildcount insert_before canaddto parentnode removenodesfromparents draggednodes draggednodes parentnode getindex currentnode reportguipackage getinstance gettreemodel insertnodeinto draggednodes parentnode insert_after canaddto parentnode removenodesfromparents draggednodes draggednodes parentnode getindex currentnode reportguipackage getinstance gettreemodel insertnodeinto draggednodes parentnode reportguipackage getinstance getmainframe determine whether or not dragged nodes can be added to this parent also used by paste todo tighten rules todo move to menu factory param parent node return whether it is ok to add the dragged nodes to this parent static boolean can add to report tree node parent node if null parent node return false test element te parent node get test element system out println add to te get class get name if te instanceof controller return true if te instanceof sampler return true if te instanceof work bench return true if te instanceof test plan return true return false menufactory parentnode canaddto reporttreenode parentnode parentnode testelement parentnode gettestelement getclass getname workbench testplan protected void remove nodes from parents report tree node nodes for int i 0 i nodes length i report gui package get instance get tree model remove node from parent nodes i removenodesfromparents reporttreenode reportguipackage getinstance gettreemodel removenodefromparent see org apache jmeter gui action command get action names public set get action names return commands getactionnames getactionnames public status impl super connectors new linked list statusimpl linkedlist see org apache jmeter monitor model status get jvm public jvm get jvm return jvm getjvm getjvm see org apache jmeter monitor model status set jvm org apache jmeter monitor model jvm public void set jvm jvm vm this jvm vm setjvm setjvm see org apache jmeter monitor model status get connector public list get connector return this connectors getconnector getconnector public void add connector connector conn this connectors add conn addconnector public void set connector prefix string prefix connector prefix prefix setconnectorprefix connectorprefix public string get connector prefix return connector prefix getconnectorprefix connectorprefix public analyze public set get action names return commands getactionnames public void do action action event e file reporter analyzer new file reporter final j file chooser chooser file dialoger prompt to open file new string jtl non nls 1 if chooser null try analyzer init chooser get selected file get path catch io exception err j meter utils report error to user the file you selected could not be analyzed doaction actionevent filereporter filereporter jfilechooser filedialoger prompttoopenfile getselectedfile getpath ioexception jmeterutils reporterrortouser no arg constructor public random timer this random new random randomtimer set the range value public void set range double range set property new double property range range setrange setproperty doubleproperty public void set range string range set property new string property range range setrange setproperty stringproperty get the range value return double public double get range return this get property as double range getrange getpropertyasdouble public jtl data super jtldata return a set of the ur ls return set of ur ls public set getur ls return this data key set urls urls geturls keyset return a set of the values return values public set get stats return this data entry set getstats entryset the purpose of the method is to make it convienant to pass a list of the ur ls and return a list of the sampling stat calculators if no ur ls match the list is empty the sampling stat calculators will be returned in the same sequence as the url list param urls return array list of non null entries may be empty public list get stats list urls array list items new array list iterator itr urls iterator if itr has next sampling stat calculator row sampling stat calculator itr next if row null items add row return items urls samplingstatcalculators urls samplingstatcalculators getstats arraylist arraylist hasnext samplingstatcalculator samplingstatcalculator public void set data source string absolute path this jtl file absolute path setdatasource absolutepath jtl_file absolutepath public string get data source return this jtl file getdatasource jtl_file public string get data source name if input file null input file new file get data source return input file get name substring 0 input file get name length 4 getdatasourcename inputfile inputfile getdatasource inputfile getname inputfile getname public void set start timestamp long stamp this start timestamp stamp setstarttimestamp starttimestamp public long get start timestamp return this start timestamp getstarttimestamp starttimestamp public void set end timestamp long stamp this end timestamp stamp setendtimestamp endtimestamp public long get end timestamp return this end timestamp getendtimestamp endtimestamp the date we use for the result is the start timestamp the reasoning is that a test may run for a long time but it is most likely scheduled to run using cron on unix or scheduled task in windows return start time public date get date return new date this start timestamp getdate starttimestamp public string get month day date calendar cal calendar get instance cal set time in millis this start timestamp return string value of cal get calendar month string value of cal get calendar day of month getmonthdaydate getinstance settimeinmillis starttimestamp valueof valueof day_of_month public string get month day year date calendar cal calendar get instance cal set time in millis this start timestamp return string value of cal get calendar month string value of cal get calendar day of month string value of cal get calendar year getmonthdayyeardate getinstance settimeinmillis starttimestamp valueof valueof day_of_month valueof the method will sampling stat calculator for the given url if the url doesn t exist the method returns null param url return data for this url public sampling stat calculator get statistics string url if this data contains key url return sampling stat calculator this data get url else return null samplingstatcalculator samplingstatcalculator getstatistics containskey samplingstatcalculator the implementation loads a single jtl file and cleans up the result collector public void load data if this get data source null result collector rc new result collector rc set filename this get data source rc set listener this rc load existing file we clean up the result collector to make sure there s no slow leaks rc clear rc set listener null rc null resultcollector loaddata getdatasource resultcollector resultcollector setfilename getdatasource setlistener loadexistingfile resultcollector setlistener the implementation will set the start timestamp if the hash map is empty otherwise it will set the end timestamp using the end time public void add sample result sample if data size 0 this start timestamp sample get start time else this end timestamp sample get end time now add the samples to the hash map string url sample get sample label if url null url sample geturl to string sampling stat calculator row sampling stat calculator data get url if row null row new sampling stat calculator just like the aggregate listener we use the sample label to represent a row in this case we use it as a key this data put url row row add sample sample hashmap sampleresult starttimestamp getstarttime endtimestamp getendtime hashmap getsamplelabel tostring samplingstatcalculator samplingstatcalculator samplingstatcalculator addsample by default the method always returns true subclasses can over ride the implementation public boolean is stats return true isstats constructor for the ldap client object public ldap ext client ldapclient ldapextclient connect to server param host description of parameter param username description of parameter param password description of parameter exception naming exception description of exception public dir context connect string host string port string rootdn string username string password string conn time out boolean secure throws naming exception dir context dir context hashtable env new hashtable env put context initial context factory com sun jndi ldap ldap ctx factory non nls 1 string buffer sb new string buffer 80 if secure sb append ldaps non nls 1 else sb append ldap non nls 1 sb append host if port length 0 sb append non nls 1 sb append port sb append non nls 1 sb append rootdn env put context provider url sb to string log info prov url env get context provider url non nls 1 if conn time out length 0 env put com sun jndi ldap connect timeout conn time out non nls 1 env put context referral throw non nls 1 env put java naming batchsize 0 non nls 1 non nls 2 env put context security credentials password env put context security principal username dir context new initial dir context env return dir context namingexception dircontext conntimeout namingexception dircontext dircontext initial_context_factory ldapctxfactory stringbuffer stringbuffer provider_url tostring prov_url provider_url conntimeout conntimeout security_credentials security_principal dircontext initialdircontext dircontext disconnect from the server public void disconnect dir context dir context if dir context null log info cannot disconnect null context return try dir context close catch naming exception e log warn ldap client disconnect e dircontext dircontext dircontext dircontext namingexception filter the data in the ldap directory for the given search base param search base base where the search should start param search filter filter filter this value from the base public naming enumeration search test dir context dir context string search base string search filter int scope long countlim int timelim string attrs boolean retobj boolean deref throws naming exception if dir context null throw new naming exception context is null if log is debug enabled log debug search base search base scope scope countlim countlim timelim timelim attrs j meter utils unsplit attrs retobj retobj deref deref filter search filter search controls searchcontrols null searchcontrols new search controls scope countlim timelim attrs retobj deref return dir context search search base search filter searchcontrols searchbase searchfilter namingenumeration searchtest dircontext dircontext searchbase searchfilter namingexception dircontext namingexception context_is_null isdebugenabled searchbase searchbase jmeterutils searchfilter searchcontrols searchcontrols dircontext searchbase searchfilter filter the data in the ldap directory param filter filter this value from the base public naming enumeration compare dir context dir context string filter string entrydn throws naming exception if dir context null throw new naming exception context is null search controls searchcontrols new search controls 0 1 0 new string 0 false false return dir context search entrydn filter searchcontrols namingenumeration dircontext dircontext namingexception dircontext namingexception context_is_null searchcontrols searchcontrols dircontext moddn the data in the ldap directory for the given search base public void moddn op dir context dir context string ddn string newdn throws naming exception log debug ddn and new dn ddn newdn if dir context null throw new naming exception context is null dir context rename ddn newdn moddnop dircontext dircontext namingexception newdn dircontext namingexception context_is_null dircontext modify the attribute in the ldap directory for the given string param mods add all the entry in to the modification item param string the string dn value public void modify test dir context dir context modification item mods string string throws naming exception if dir context null throw new naming exception context is null dir context modify attributes string mods modificationitem modifytest dircontext dircontext modificationitem namingexception dircontext namingexception context_is_null dircontext modifyattributes create the entry in the ldap directory for the given string param attributes add all the attributes and values from the attributes object param string the string dn value public dir context create test dir context dir context attributes attributes string string throws naming exception if dir context null throw new naming exception context is null return dir context create subcontext string attributes dircontext createtest dircontext dircontext namingexception dircontext namingexception context_is_null dircontext createsubcontext delete the attribute from the ldap directory param string the string dn value public void delete test dir context dir context string string throws naming exception if dir context null throw new naming exception context is null dir context destroy subcontext string deletetest dircontext dircontext namingexception dircontext namingexception context_is_null dircontext destroysubcontext constructor for a non configured constant throughput timer public constant throughput timer constantthroughputtimer constantthroughputtimer sets the desired throughput param throughput desired sampling rate in samples per minute public void set throughput double throughput this throughput throughput setthroughput gets the configured desired throughput return the rate at which samples should occur in samples per minute public double get throughput return throughput getthroughput public string get calc mode return calc mode getcalcmode calcmode needed by test code int get calc mode int return mode int getcalcmodeint modeint public void set calc mode string mode this calc mode mode todo find better way to get mode int this mode int constant throughput timer bean info get calc mode as int calc mode setcalcmode calcmode modeint modeint constantthroughputtimerbeaninfo getcalcmodeasint calcmode retrieve the delay to use during test execution see org apache jmeter timers timer delay public long delay long current time system current time millis if previous time is zero then target will be in the past this is what we want so first sample is run without a delay long current target previous time calculate delay if current time current target we re behind schedule try to catch up previous time current time return 0 previous time current target return current target current time currenttime currenttimemillis currenttarget previoustime calculatedelay currenttime currenttarget previoustime currenttime previoustime currenttarget currenttarget currenttime param current time return new target time todo is this used apart from test code protected long calculate current target long current time return current time calculate delay currenttime calculatecurrenttarget currenttime currenttime calculatedelay calculate the delay based on the mode private long calculate delay long delay 0 n b we fetch the throughput each time as it may vary during a test double ms per request millisec per min get throughput switch mode int case 1 total number of threads delay long j meter context service get number of threads ms per request break case 2 active threads in this group delay long j meter context service get context get thread group get number of threads ms per request break case 3 all threads alternate calculation delay calculate shared delay all threads info long ms per request break case 4 all threads in this group alternate calculation final org apache jmeter threads thread group group j meter context service get context get thread group throughput info group info synchronized thread groups info map group info throughput info thread groups info map get group if group info null group info new throughput info thread groups info map put group group info delay calculate shared delay group info long ms per request break default e g 0 delay long ms per request i e 1 break return delay calculatedelay msperrequest millisec_per_min getthroughput modeint jmetercontextservice getnumberofthreads msperrequest jmetercontextservice getcontext getthreadgroup getnumberofthreads msperrequest calculateshareddelay allthreadsinfo msperrequest threadgroup jmetercontextservice getcontext getthreadgroup throughputinfo groupinfo threadgroupsinfomap groupinfo throughputinfo threadgroupsinfomap groupinfo groupinfo throughputinfo threadgroupsinfomap groupinfo calculateshareddelay groupinfo msperrequest msperrequest private long calculate shared delay throughput info info long milli sec per request final long now system current time millis final long calculated delay synchronize on the info object s mutex to ensure multiple threads don t update the scheduled time simultaneously synchronized info mutex final long next requst time info last scheduled time milli sec per request info last scheduled time math max now next requst time calculated delay info last scheduled time now return math max calculated delay 0 calculateshareddelay throughputinfo millisecperrequest currenttimemillis calculateddelay nextrequsttime lastscheduledtime millisecperrequest lastscheduledtime nextrequsttime calculateddelay lastscheduledtime calculateddelay private synchronized void reset all threads info last scheduled time 0 thread groups info map clear previous time 0 allthreadsinfo lastscheduledtime threadgroupsinfomap previoustime provide a description of this timer class todo is this ever used i can t remember where remove if it isn t todo or obtain text from bean s display name or short description return the description of this timer class public string to string return j meter utils get res string constant throughput timer memo non nls 1 displayname shortdescription tostring jmeterutils getresstring constant_throughput_timer_memo get the timer ready to compute delays for a new test see org apache jmeter testelement test listener test started public void test started log debug test started reset throughput calculation reset testlistener teststarted teststarted see org apache jmeter testelement test listener test ended public void test ended testlistener testended testended see org apache jmeter testelement test listener test started java lang string public void test started string host test started testlistener teststarted teststarted teststarted see org apache jmeter testelement test listener test ended java lang string public void test ended string host testlistener testended testended see org apache jmeter testelement test listener test iteration start org apache jmeter engine event loop iteration event public void test iteration start loop iteration event event testlistener testiterationstart loopiterationevent testiterationstart loopiterationevent public final class test html parsing utils extends j meter test case public test html parsing utils string name super name testhtmlparsingutils jmetertestcase testhtmlparsingutils protected void set up setup public void test get parser throws exception html parsing utils get parser testgetparser htmlparsingutils getparser public void test get dom throws exception html parsing utils getdom html html html parsing utils getdom testgetdom htmlparsingutils htmlparsingutils public void test is argument matched throws exception argument arg new argument argument argp new argument assert true html parsing utils is argument matched arg argp arg new argument test abcd argp new argument test a d assert true html parsing utils is argument matched arg argp arg new argument test abcd argp new argument test a e assert false html parsing utils is argument matched arg argp testisargumentmatched asserttrue htmlparsingutils isargumentmatched asserttrue htmlparsingutils isargumentmatched assertfalse htmlparsingutils isargumentmatched public void test is anchor matched throws exception http sampler base target new http null sampler http sampler base pattern new http null sampler assert true html parsing utils is anchor matched target pattern target set protocol http assert false html parsing utils is anchor matched target pattern pattern set protocol assert true html parsing utils is anchor matched target pattern target set domain a b c assert true html parsing utils is anchor matched target pattern pattern set domain assert true html parsing utils is anchor matched target pattern target set path abc assert false html parsing utils is anchor matched target pattern pattern set path assert true html parsing utils is anchor matched target pattern target add argument param2 value2 assert true html parsing utils is anchor matched target pattern pattern add argument param1 assert false html parsing utils is anchor matched target pattern target add argument param1 value1 assert true html parsing utils is anchor matched target pattern testisanchormatched httpsamplerbase httpnullsampler httpsamplerbase httpnullsampler asserttrue htmlparsingutils isanchormatched setprotocol assertfalse htmlparsingutils isanchormatched setprotocol asserttrue htmlparsingutils isanchormatched setdomain asserttrue htmlparsingutils isanchormatched setdomain asserttrue htmlparsingutils isanchormatched setpath assertfalse htmlparsingutils isanchormatched setpath asserttrue htmlparsingutils isanchormatched addargument asserttrue htmlparsingutils isanchormatched addargument assertfalse htmlparsingutils isanchormatched addargument asserttrue htmlparsingutils isanchormatched public void testis equal or matches throws exception assert true html parsing utils is equal or matches http http assert false html parsing utils is equal or matches http ht tp assert true html parsing utils is equal or matches http ht p assert false html parsing utils is equal or matches ht p http testisequalormatches asserttrue htmlparsingutils isequalormatches assertfalse htmlparsingutils isequalormatches http asserttrue htmlparsingutils isequalormatches assertfalse htmlparsingutils isequalormatches public void testis equal or matches case blind throws exception assert true html parsing utils is equal or matches case blind http http assert true html parsing utils is equal or matches case blind http ht tp assert true html parsing utils is equal or matches http ht p assert false html parsing utils is equal or matches ht p http testisequalormatchescaseblind asserttrue htmlparsingutils isequalormatchescaseblind asserttrue htmlparsingutils isequalormatchescaseblind http asserttrue htmlparsingutils isequalormatches assertfalse htmlparsingutils isequalormatches create a new arguments object with no arguments public arguments set property new collection property arguments new array list setproperty collectionproperty arraylist get the arguments return the arguments public collection property get arguments return collection property get property arguments collectionproperty getarguments collectionproperty getproperty clear the arguments public void clear super clear set property new collection property arguments new array list setproperty collectionproperty arraylist set the list of arguments any existing arguments will be lost param arguments the new arguments public void set arguments list arguments set property new collection property arguments arguments setarguments setproperty collectionproperty get the arguments as a map each argument name is used as the key and its value as the value return a new map with string keys and values containing the arguments public map get arguments as map property iterator iter get arguments iterator map arg map new linked hash map while iter has next argument arg argument iter next get object value because collection property merge in will not prevent adding two properties of the same name we need to select the first value so that this element s values prevail over defaults provided by configuration elements if arg map contains key arg get name arg map put arg get name arg get value return arg map getargumentsasmap propertyiterator getarguments argmap linkedhashmap hasnext getobjectvalue collectionproperty mergein argmap containskey getname argmap getname getvalue argmap add a new argument with the given name and value param name the name of the argument param value the value of the argument public void add argument string name string value add argument new argument name value null addargument addargument add a new argument param arg the new argument public void add argument argument arg test element property new arg new test element property arg get name arg if is running version this set temporary new arg get arguments add item new arg addargument testelementproperty newarg testelementproperty getname isrunningversion settemporary newarg getarguments additem newarg add a new argument with the given name value and metadata param name the name of the argument param value the value of the argument param metadata the metadata for the argument public void add argument string name string value string metadata add argument new argument name value metadata addargument addargument get a property iterator of the arguments return an iteration of the arguments public property iterator iterator return get arguments iterator propertyiterator propertyiterator getarguments create a string representation of the arguments return the string representation of the arguments public string to string string buffer str new string buffer property iterator iter get arguments iterator while iter has next argument arg argument iter next get object value final string meta data arg get meta data str append arg get name if meta data null str append non nls 1 else str append meta data str append arg get value if iter has next str append non nls 1 return str to string tostring stringbuffer stringbuffer propertyiterator getarguments hasnext getobjectvalue metadata getmetadata getname metadata metadata getvalue hasnext tostring remove the specified argument from the list param row the index of the argument to remove public void remove argument int row if row get arguments size get arguments remove row removeargument getarguments getarguments remove the specified argument from the list param arg the argument to remove public void remove argument argument arg property iterator iter get arguments iterator while iter has next argument item argument iter next get object value if arg equals item iter remove removeargument propertyiterator getarguments hasnext getobjectvalue remove the argument with the specified name param arg name the name of the argument to remove public void remove argument string arg name property iterator iter get arguments iterator while iter has next argument arg argument iter next get object value if arg get name equals arg name iter remove argname removeargument argname propertyiterator getarguments hasnext getobjectvalue getname argname remove all arguments from the list public void remove all arguments get arguments clear removeallarguments getarguments add a new empty argument to the list the new argument will have the empty string as its name and value and null metadata public void add empty argument add argument new argument null addemptyargument addargument get the number of arguments in the list return the number of arguments public int get argument count return get arguments size getargumentcount getarguments get a single argument param row the index of the argument to return return the argument at the specified index or null if no argument exists at that index public argument get argument int row argument argument null if row get arguments size argument argument get arguments get row get object value return argument getargument getarguments getarguments getobjectvalue when a user right clicks on the component in the test tree or selects the edit menu when the component is selected the component will be asked to return a j popup menu that provides all the options available to the user from this component p this implementation returns menu items appropriate for most visualizer components return a j popup menu appropriate for the component public j popup menu create popup menu return menu factory get default visualizer menu jpopupmenu jpopupmenu jpopupmenu createpopupmenu menufactory getdefaultvisualizermenu this is the list of menu categories this gui component will be available under this implementation returns link org apache jmeter gui util menu factory listeners which is appropriate for most visualizer components return a collection of strings where each element is one of the constants defined in menu factory public collection get menu categories return arrays as list new string menu factory listeners menufactory menufactory getmenucategories aslist menufactory private tcp config gui tcp default panel public tcp sampler gui init tcpconfiggui tcpdefaultpanel tcpsamplergui public void configure test element element super configure element login panel configure element tcp default panel configure element testelement loginpanel tcpdefaultpanel public test element create test element tcp sampler sampler new tcp sampler modify test element sampler return sampler testelement createtestelement tcpsampler tcpsampler modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element sampler sampler clear sampler add test element tcp default panel create test element sampler add test element login panel create test element this configure test element sampler testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement addtestelement tcpdefaultpanel createtestelement addtestelement loginpanel createtestelement configuretestelement implements j metergui component clear gui public void clear gui super clear gui tcp default panel clear gui login panel clear gui jmeterguicomponent cleargui cleargui cleargui tcpdefaultpanel cleargui loginpanel cleargui public string get label resource return tcp sample title non nls 1 getlabelresource tcp_sample_title private void init set layout new border layout 0 5 set border make border add make title panel border layout north vertical panel main panel new vertical panel tcp default panel new tcp config gui false main panel add tcp default panel login panel new login config gui false login panel set border border factory create titled border j meter utils get res string login config non nls 1 main panel add login panel add main panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout verticalpanel mainpanel verticalpanel tcpdefaultpanel tcpconfiggui mainpanel tcpdefaultpanel loginpanel loginconfiggui loginpanel setborder borderfactory createtitledborder jmeterutils getresstring login_config mainpanel loginpanel mainpanel borderlayout public number renderer super formatter number format get instance set horizontal alignment j label right numberrenderer numberformat getinstance sethorizontalalignment jlabel public number renderer string format super formatter new decimal format format set horizontal alignment j label right numberrenderer decimalformat sethorizontalalignment jlabel public void set value object value set text value null formatter format value setvalue settext public connector impl super connectorimpl public thread info get thread info return this threadinfo threadinfo getthreadinfo public void set thread info thread info value this threadinfo value setthreadinfo threadinfo public request info get request info return this requestinfo requestinfo getrequestinfo public void set request info request info value this requestinfo value setrequestinfo requestinfo public workers get workers return this workers getworkers public void set workers workers value this workers value setworkers public string get name return this name getname public void set name string value this name value setname public number comparator super numbercomparator public int compare object val1 object val2 number n1 number val1 number n2 number val2 if n1 0 long value n2 0 long value return 1 else if n1 0 long value n2 0 long value return 0 else return 1 longvalue longvalue longvalue longvalue for instructional purposes only public example sampler class count trace example sampler examplesampler classcount examplesampler public sample result sample entry e trace sample sample result res new sample result boolean isok false did sample succeed string data get data sampler data string response null res set sample label get title perform the sampling res sample start start timing try do something here response thread current thread get name set up the sample result details res set sampler data data res set response data response get bytes res set data type sample result text res set response codeok res set response message ok non nls 1 isok true catch exception ex log debug ex res set response code 500 non nls 1 res set response message ex to string res sample end end timimg res set successful isok return res sampleresult sampleresult sampleresult getdata setsamplelabel gettitle samplestart currentthread getname setsamplerdata setresponsedata getbytes setdatatype sampleresult setresponsecodeok setresponsemessage setresponsecode setresponsemessage tostring sampleend setsuccessful return a string for the sample result title private string get title return this get name sampleresult gettitle getname return the data for the sample public string get data return get property as string data getdata getpropertyasstring private void trace string s string tl get title string tn thread current thread get name string th this to string log debug tn class count tl s th gettitle currentthread getname tostring classcount private cache cache public encoder cache int cache size cache new cachelru cache size encodercache cachesize cachesize get the specified value url encoded using utf 8 encoding param k the value to encode return the value url encoded using utf 8 public string get encoded string k try return get encoded k url argument encoding catch unsupported encoding exception e this can t happen how should utf8 not be supported so just throw an error throw new error should not happen e to string getencoded getencoded url_argument_encoding unsupportedencodingexception tostring get the specified value url encoded using the specified encoding param k the value to encode param content encoding the encoding to use when url encoding return the value url encoded using the specified encoding throws unsupported encoding exception if the specified encoding is not supported public string get encoded string k string content encoding throws unsupported encoding exception string cache key k content encoding check if we have it in the cache object encoded value cache get element cache key if encoded value null return string encoded value perform the encoding encoded value url encoder encode k content encoding add to cache cache add element cache key encoded value return string encoded value contentencoding unsupportedencodingexception getencoded contentencoding unsupportedencodingexception cachekey contentencoding encodedvalue getelement cachekey encodedvalue encodedvalue encodedvalue urlencoder contentencoding addelement cachekey encodedvalue encodedvalue create a new test plan gui public test plan gui init testplangui testplangui when a user right clicks on the component in the test tree or selects the edit menu when the component is selected the component will be asked to return a j popup menu that provides all the options available to the user from this component p the test plan will return a popup menu allowing you to add thread groups listeners configuration elements assertions pre processors post processors and timers return a j popup menu appropriate for the component public j popup menu create popup menu j popup menu pop new j popup menu j menu add menu new j menu j meter utils get res string add non nls 1 add menu add menu factory make menu item new thread group gui get static label thread group gui class get name action names add add menu add menu factory make menu menu factory config elements action names add add menu add menu factory make menu menu factory timers action names add add menu add menu factory make menu menu factory pre processors action names add add menu add menu factory make menu menu factory post processors action names add add menu add menu factory make menu menu factory assertions action names add add menu add menu factory make menu menu factory listeners action names add pop add add menu menu factory add paste reset menu pop menu factory add file menu pop return pop jpopupmenu testplan threadgroups preprocessors postprocessors jpopupmenu jpopupmenu createpopupmenu jpopupmenu jpopupmenu jmenu addmenu jmenu jmeterutils getresstring addmenu menufactory makemenuitem threadgroupgui getstaticlabel threadgroupgui getname actionnames addmenu menufactory makemenu menufactory config_elements actionnames addmenu menufactory makemenu menufactory actionnames addmenu menufactory makemenu menufactory pre_processors actionnames addmenu menufactory makemenu menufactory post_processors actionnames addmenu menufactory makemenu menufactory actionnames addmenu menufactory makemenu menufactory actionnames addmenu menufactory addpasteresetmenu menufactory addfilemenu implements j metergui component create test element public test element create test element test plan tp new test plan modify test element tp return tp jmeterguicomponent createtestelement testelement createtestelement testplan testplan modifytestelement implements j metergui component modify test element test element public void modify test element test element plan super configure test element plan if plan instanceof test plan test plan tp test plan plan tp set functional mode functional mode is selected tp set serialized serialized mode is selected tp set user defined variables arguments args panel create test element tp set test plan classpath array browse jar get files jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement testplan testplan testplan setfunctionalmode functionalmode isselected setserialized serializedmode isselected setuserdefinedvariables argspanel createtestelement settestplanclasspatharray browsejar getfiles public string get label resource return test plan non nls 1 getlabelresource test_plan this is the list of menu categories this gui component will be available under this implementation returns null since the test plan appears at the top level of the tree and cannot be added elsewhere return a collection of strings where each element is one of the constants defined in menu factory public collection get menu categories return null testplan menufactory getmenucategories a newly created component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui param el the test element to configure public void configure test element el super configure el if el instanceof test plan test plan tp test plan el functional mode set selected tp is functional mode serialized mode set selected tp is serialized final j meter property udv tp get user defined variables as property if udv null args panel configure arguments udv get object value browse jar set files tp get test plan classpath array testelement testelement testplan testplan testplan functionalmode setselected isfunctionalmode serializedmode setselected isserialized jmeterproperty getuserdefinedvariablesasproperty argspanel getobjectvalue browsejar setfiles gettestplanclasspatharray create a panel allowing the user to define variables for the test return a panel for user defined variables private j panel create variable panel args panel new arguments panel j meter utils get res string user defined variables non nls 1 return args panel jpanel createvariablepanel argspanel argumentspanel jmeterutils getresstring user_defined_variables argspanel protected container create class path panel browse jar new file list panel j meter utils get res string test plan classpath browse jar non nls 1 non nls 2 return browse jar createclasspathpanel browsejar filelistpanel jmeterutils getresstring test_plan_classpath_browse browsejar initialize the components and layout of this component private void init set layout new border layout 10 10 set border make border add make title panel border layout north add create variable panel border layout center vertical panel south panel new vertical panel serialized mode new j check box j meter utils get res string testplan serialized non nls 1 south panel add serialized mode functional mode new j check box j meter utils get res string functional mode non nls 1 south panel add functional mode j text area explain new j text area j meter utils get res string functional mode explanation non nls 1 explain set editable false explain set background this get background south panel add explain south panel add create class path panel add south panel border layout south setlayout borderlayout setborder makeborder maketitlepanel borderlayout createvariablepanel borderlayout verticalpanel southpanel verticalpanel serializedmode jcheckbox jmeterutils getresstring southpanel serializedmode functionalmode jcheckbox jmeterutils getresstring functional_mode southpanel functionalmode jtextarea jtextarea jmeterutils getresstring functional_mode_explanation seteditable setbackground getbackground southpanel southpanel createclasspathpanel southpanel borderlayout public void clear gui super clear gui functional mode set selected false serialized mode set selected false args panel clear browse jar clear files cleargui cleargui functionalmode setselected serializedmode setselected argspanel browsejar clearfiles constructor param producer the queue to send the message on param timeout timeout to use for the return message public fixed queue executor queue sender producer int timeout this producer producer this timeout timeout this use req msg id as correl id false fixedqueueexecutor queuesender usereqmsgidascorrelid constructor param producer the queue to send the message on param timeout timeout to use for the return message param use req msg id as correl id whether to use the request message id as the correlation id public fixed queue executor queue sender producer int timeout boolean use req msg id as correl id this producer producer this timeout timeout this use req msg id as correl id use req msg id as correl id usereqmsgidascorrelid fixedqueueexecutor queuesender usereqmsgidascorrelid usereqmsgidascorrelid usereqmsgidascorrelid public message send and receive message request throws jms exception string id request getjms correlationid if id null use req msg id as correl id log error correlation id is null set the jms correlationid header return null producer send request if use req msg id as correl id id request getjms messageid message admin get admin put request id request try if log is debug enabled log debug wait for reply id started on system current time millis synchronized request request wait timeout if log is debug enabled log debug done waiting for id ended on system current time millis catch interrupted exception e log warn interrupt exception caught e return message admin get admin get id sendandreceive jmsexception getjmscorrelationid usereqmsgidascorrelid jmscorrelationid usereqmsgidascorrelid getjmsmessageid messageadmin getadmin putrequest isdebugenabled currenttimemillis isdebugenabled currenttimemillis interruptedexception messageadmin getadmin private object values public machine name machinename public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception boolean full host name false if compound function values 0 execute to lower case equals true full host name true string machine name j meter utils get local host name if values length 1 we have a variable name j meter variables vars get variables if vars null may be null if function is used on test plan string var name compound variable values 0 execute trim if var name length 0 vars put var name machine name return machine name sampleresult previousresult currentsampler invalidvariableexception fullhostname compoundfunction tolowercase fullhostname machinename jmeterutils getlocalhostname jmetervariables getvariables testplan varname compoundvariable varname varname machinename machinename public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters 0 1 values parameters to array setparameters invalidvariableexception checkparametercount toarray public string get reference key return key getreferencekey public list get argument desc return desc getargumentdesc use this constructor to create the initial instance public running sample string label int index this label label this index index init runningsample copy constructor to create a duplicate of existing instance without the disadvantages of clone param src existing running sample to be copied public running sample running sample src this counter src counter this error count src error count this first time src first time this index src index this label src label this last time src last time this max src max this min src min this running sum src running sum runningsample runningsample runningsample errorcount errorcount firsttime firsttime lasttime lasttime runningsum runningsum private void init counter 0l running sum 0l max long min value min long max value error count 0l first time long max value last time 0l runningsum min_value max_value errorcount firsttime max_value lasttime clear the counters useful for differential stats public void clear init get the elapsed time for the samples return how long the samples took public long get elapsed if last time 0 return 0 no samples collected return last time first time getelapsed lasttime lasttime firsttime returns the throughput associated to this sampler in requests per second may be slightly skewed because it takes the timestamps of the first and last samples as the total time passed and the test may actually have started before that start time and ended after that end time public double get rate if counter 0 return 0 0 better behaviour when how long 0 or last time 0 long how long running last time first time if how long running 0 return double max value return double counter how long running 1000 0 getrate howlong lasttime howlongrunning lasttime firsttime howlongrunning max_value howlongrunning returns the throughput associated to this sampler in requests per min may be slightly skewed because it takes the timestamps of the first and last samples as the total time passed and the test may actually have started before that start time and ended after that end time public double get rate per min if counter 0 return 0 0 better behaviour when how long 0 or last time 0 long how long running last time first time if how long running 0 return double max value return double counter how long running 60000 0 getratepermin howlong lasttime howlongrunning lasttime firsttime howlongrunning max_value howlongrunning returns a string that represents the throughput associated for this sampler in units appropriate to its dimension p the number is represented in requests second or requests minute or requests hour p examples 34 2 sec 0 1 sec 43 0 hour 15 9 min return a string representation of the rate the samples are being taken at public string get rate string double rate get rate if rate double max value return n a string unit sec if rate 1 0 rate 60 0 unit min if rate 1 0 rate 60 0 unit hour string rval rate formatter format rate unit return rval getratestring getrate max_value rateformatter public string get label return label getlabel public int get index return index getindex records a sample public void add sample sample result res long a time in millis res get time boolean a success flag res is successful counter long start time res get start time long end time res get end time if first time start time this is our first sample set the start time to current timestamp first time start time always update the end time if last time end time last time end time running sum a time in millis if a time in millis max max a time in millis if a time in millis min min a time in millis if a success flag error count addsample sampleresult atimeinmillis gettime asuccessflag issuccessful starttime getstarttime endtime getendtime firsttime starttime firsttime starttime lasttime endtime lasttime endtime runningsum atimeinmillis atimeinmillis atimeinmillis atimeinmillis atimeinmillis asuccessflag errorcount adds another running sample to this one does not check if it has the same label and index public void add sample running sample rs this counter rs counter this error count rs error count this running sum rs running sum if this first time rs first time this first time rs first time if this last time rs last time this last time rs last time if this max rs max this max rs max if this min rs min this min rs min runningsample addsample runningsample errorcount errorcount runningsum runningsum firsttime firsttime firsttime firsttime lasttime lasttime lasttime lasttime returns the time in milliseconds of the quickest sample return the time in milliseconds of the quickest sample public long get min long rval 0 if min long max value rval min return rval getmin max_value returns the time in milliseconds of the slowest sample return the time in milliseconds of the slowest sample public long get max long rval 0 if max long min value rval max return rval getmax min_value returns the average time in milliseconds that samples ran in return the average time in milliseconds that samples ran in public long get average if counter 0 return 0 return running sum counter getaverage runningsum returns the number of samples that have been recorded by this instance of the running sample class return the number of samples that have been recorded by this instance of the running sample class public long get num samples return counter runningsample runningsample getnumsamples returns the raw double value of the percentage of samples with errors that were recorded between 0 0 and 1 0 if you want a nicer return format see link get error percentage string return the raw double value of the percentage of samples with errors that were recorded public double get error percentage double rval 0 0 if counter 0 return rval rval double error count double counter return rval geterrorpercentagestring geterrorpercentage errorcount returns a string which represents the percentage of sample errors that have occurred 0 00 through 100 00 return a string which represents the percentage of sample errors that have occurred public string get error percentage string double my error percentage this get error percentage return error formatter format my error percentage geterrorpercentagestring myerrorpercentage geterrorpercentage errorformatter myerrorpercentage for debugging purposes mainly public string to string string buffer mysb new string buffer mysb append samples this get num samples mysb append avg this get average mysb append min this get min mysb append max this get max mysb append error rate this get error percentage string mysb append sample rate this get rate string return mysb to string tostring stringbuffer stringbuffer getnumsamples getaverage getmin getmax geterrorpercentagestring getratestring tostring return error count public long get error count return error count errorcount geterrorcount errorcount public void recover running version test element owner if saved value null value saved value recoverrunningversion testelement savedvalue savedvalue public void set running version boolean running version super set running version running version if running version saved value value else saved value null setrunningversion runningversion setrunningversion runningversion runningversion savedvalue savedvalue public object clone object property p object property super clone p value value return p objectproperty objectproperty public object property super todo auto generated constructor stub objectproperty param name public object property string name super name objectproperty public object property string name object p super name value p objectproperty see org apache jmeter testelement property j meter property get string value public string get string value return value to string jmeterproperty getstringvalue getstringvalue tostring see org apache jmeter testelement property j meter property get object value public object get object value return value jmeterproperty getobjectvalue getobjectvalue see org apache jmeter testelement property j meter property set object value java lang object public void set object value object value this value value jmeterproperty setobjectvalue setobjectvalue constructor for the start object public start gets the action names attribute of the start object return the action names value public set get action names return commands actionnames actionnames getactionnames public void do action action event e if e get action command equals action names action start popup should save e start engine else if e get action command equals action names action stop if engine null log info stopping test gui package get instance get main frame show stopping message engine stop test else if e get action command equals action names action shutdown if engine null log info shutting test down gui package get instance get main frame show stopping message engine ask threads to stop doaction actionevent getactioncommand actionnames action_start popupshouldsave startengine getactioncommand actionnames action_stop guipackage getinstance getmainframe showstoppingmessage stoptest getactioncommand actionnames action_shutdown guipackage getinstance getmainframe showstoppingmessage askthreadstostop private void start engine gui package gui gui package get instance hash tree test tree gui get tree model get test plan j meter convert sub tree test tree disabled component remover remover new disabled component remover test tree test tree traverse remover test tree add test tree get array 0 gui get main frame log debug test plan before cloning is running version test plan test tree get array 0 is running version tree cloner cloner new tree cloner false test tree traverse cloner engine new standardj meter engine engine configure cloner get cloned tree try engine run test catch j meter engine exception e j option pane show message dialog gui get main frame e get message j meter utils get res string error occurred j option pane error message log debug test plan after cloning and running test is running version test plan test tree get array 0 is running version startengine guipackage guipackage getinstance hashtree testtree gettreemodel gettestplan jmeter convertsubtree testtree disabledcomponentremover disabledcomponentremover testtree testtree testtree testtree getarray getmainframe testplan testtree getarray isrunningversion treecloner treecloner testtree standardjmeterengine getclonedtree runtest jmeterengineexception joptionpane showmessagedialog getmainframe getmessage jmeterutils getresstring joptionpane error_message testplan testtree getarray isrunningversion public header panel header manager new header manager table model new inner table model header manager init headerpanel headermanager headermanager tablemodel innertablemodel headermanager public test element create test element configure test element header manager return test element header manager clone testelement createtestelement configuretestelement headermanager testelement headermanager modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element el if header table is editing bug 41905 header table get cell editor stop cell editing el clear el add test element header manager configure test element el testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement headertable isediting headertable getcelleditor stopcellediting addtestelement headermanager configuretestelement implements j metergui component clear gui public void clear gui super clear gui table model clear data delete button set enabled false save button set enabled false jmeterguicomponent cleargui cleargui cleargui tablemodel cleardata deletebutton setenabled savebutton setenabled public void configure test element el header manager clear super configure el header manager add test element el boolean has rows table model get row count 0 delete button set enabled has rows save button set enabled has rows testelement headermanager headermanager addtestelement hasrows tablemodel getrowcount deletebutton setenabled hasrows savebutton setenabled hasrows public string get label resource return header manager title non nls 1 getlabelresource header_manager_title private void init called from ctor so must not be overridable set layout new border layout set border make border add make title panel border layout north add create header table panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout createheadertablepanel borderlayout public void action performed action event e string action e get action command if action equals delete command if table model get row count 0 if a table cell is being edited we must cancel the editing before deleting the row if header table is editing table cell editor cell editor header table get cell editor header table get editing row header table get editing column cell editor cancel cell editing int row selected header table get selected row if row selected 1 table model remove row row selected table model fire table data changed disable the delete and save buttons if no rows remaining after delete if table model get row count 0 delete button set enabled false save button set enabled false table still contains one or more rows so highlight select the appropriate one else int row to select row selected if row selected table model get row count row to select row selected 1 header table set row selection interval row to select row to select else if action equals add command if a table cell is being edited we should accept the current value and stop the editing before adding a new row if header table is editing table cell editor cell editor header table get cell editor header table get editing row header table get editing column cell editor stop cell editing table model add new row table model fire table data changed enable the delete and save buttons if they are currently disabled if delete button is enabled delete button set enabled true if save button is enabled save button set enabled true highlight select the appropriate row int row to select table model get row count 1 header table set row selection interval row to select row to select else if action equals load command try final j file chooser chooser file dialoger prompt to open file if chooser null header manager add file chooser get selected file get absolute path table model fire table data changed if table model get row count 0 delete button set enabled true save button set enabled true catch io exception ex log error could not load headers ex else if action equals save command try final j file chooser chooser file dialoger prompt to save file null if chooser null header manager save chooser get selected file get absolute path catch io exception ex log error could not save headers ex actionperformed actionevent getactioncommand delete_command tablemodel getrowcount headertable isediting tablecelleditor celleditor headertable getcelleditor headertable geteditingrow headertable geteditingcolumn celleditor cancelcellediting rowselected headertable getselectedrow rowselected tablemodel removerow rowselected tablemodel firetabledatachanged tablemodel getrowcount deletebutton setenabled savebutton setenabled rowtoselect rowselected rowselected tablemodel getrowcount rowtoselect rowselected headertable setrowselectioninterval rowtoselect rowtoselect add_command headertable isediting tablecelleditor celleditor headertable getcelleditor headertable geteditingrow headertable geteditingcolumn celleditor stopcellediting tablemodel addnewrow tablemodel firetabledatachanged deletebutton isenabled deletebutton setenabled savebutton isenabled savebutton setenabled rowtoselect tablemodel getrowcount headertable setrowselectioninterval rowtoselect rowtoselect load_command jfilechooser filedialoger prompttoopenfile headermanager addfile getselectedfile getabsolutepath tablemodel firetabledatachanged tablemodel getrowcount deletebutton setenabled savebutton setenabled ioexception save_command jfilechooser filedialoger prompttosavefile headermanager getselectedfile getabsolutepath ioexception public j panel create header table panel create the j table that holds header per row header table new j table table model header table get table header set default renderer new header as property renderer header table set selection mode list selection model single selection header table set preferred scrollable viewport size new dimension 100 70 j panel panel new j panel new border layout 0 5 panel set border border factory create titled border border factory create etched border j meter utils get res string headers stored non nls 1 panel add new j scroll pane header table border layout center panel add create button panel border layout south return panel jpanel createheadertablepanel jtable headertable jtable tablemodel headertable gettableheader setdefaultrenderer headeraspropertyrenderer headertable setselectionmode listselectionmodel single_selection headertable setpreferredscrollableviewportsize jpanel jpanel borderlayout setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring headers_stored jscrollpane headertable borderlayout createbuttonpanel borderlayout private j button create button string res name char mnemonic string command boolean enabled j button button new j button j meter utils get res string res name button set mnemonic mnemonic button set action command command button set enabled enabled button add action listener this return button jbutton createbutton resname jbutton jbutton jmeterutils getresstring resname setmnemonic setactioncommand setenabled addactionlistener private j panel create button panel boolean table empty table model get row count 0 add button create button add a add command true non nls 1 delete button create button delete d delete command table empty non nls 1 load button create button load l load command true non nls 1 save button create button save s save command table empty non nls 1 j panel button panel new j panel button panel add add button button panel add delete button button panel add load button button panel add save button return button panel jpanel createbuttonpanel tableempty tablemodel getrowcount addbutton createbutton add_command deletebutton createbutton delete_command tableempty loadbutton createbutton load_command savebutton createbutton save_command tableempty jpanel buttonpanel jpanel buttonpanel addbutton buttonpanel deletebutton buttonpanel loadbutton buttonpanel savebutton buttonpanel private header manager manager public inner table model header manager man manager man headermanager innertablemodel headermanager public void clear data manager clear fire table data changed cleardata firetabledatachanged public void remove row int row manager remove row removerow public void add new row manager add addnewrow public boolean is cell editable int row int column all table cells are editable return true iscelleditable public class get column class int column return get value at 0 column get class getcolumnclass getvalueat getclass public int get row count return manager get headers size getrowcount getheaders required by table model interface public int get column count return manager get column count getcolumncount getcolumncount required by table model interface public string get column name int column return manager get column name column getcolumnname getcolumnname required by table model interface public object get value at int row int column header head manager get header row if column 0 return head get name else if column 1 return head get value return null getvalueat getheader getname getvalue required by table model interface public void set value at object value int row int column header header manager get header row if column 0 header set name string value else if column 1 header set value string value setvalueat getheader setname setvalue public static final string resource bundle resource bundle non nls 1 public static final string order string group return group group order resource_bundle resourcebundle private map property map public generic test bean customizer log warn constructor only intended for use in testing non nls 1 propertymap generictestbeancustomizer create a customizer for a given test bean type param test bean class a subclass of test bean see org apache jmeter testbeans test bean generic test bean customizer bean info bean info super this bean info bean info get and sort the property descriptors descriptors bean info get property descriptors arrays sort descriptors new property comparator obtain the property editors editors new property editor descriptors length for int i 0 i descriptors length i string name descriptors i get name don t get editors for hidden or non read write properties if descriptors i is hidden descriptors i is expert j meter utils is expert mode descriptors i get read method null descriptors i get write method null log debug no editor for property name editors i null continue property editor property editor class editor class descriptors i get property editor class if log is debug enabled log debug property name has editor class editor class if editor class null try property editor property editor editor class new instance catch instantiation exception e log error can t create property editor e throw new error e to string catch illegal access exception e log error can t create property editor e throw new error e to string else class c descriptors i get property type property editor property editor manager find editor c if log is debug enabled log debug property name has property editor property editor if property editor null log debug no editor for property name editors i null continue if property editor supports custom editor property editor create wrapper editor property editor descriptors i if log is debug enabled log debug editor for property name is wrapped in property editor if property editor get custom editor instanceof j scroll pane scroller count editors i property editor initialize the editor with the provided default value or null set editor value i descriptors i get value default obtain message formats property field label message new message format j meter utils get res string property as field label non nls 1 property tool tip message new message format j meter utils get res string property tool tip non nls 1 initialize the gui init testbeanclass testbean testbean generictestbeancustomizer beaninfo beaninfo beaninfo beaninfo beaninfo getpropertydescriptors propertycomparator propertyeditors propertyeditor getname ishidden isexpert jmeterutils isexpertmode getreadmethod getwritemethod propertyeditor propertyeditor editorclass getpropertyeditorclass isdebugenabled editorclass editorclass propertyeditor propertyeditor editorclass newinstance instantiationexception tostring illegalaccessexception tostring getpropertytype propertyeditor propertyeditormanager findeditor isdebugenabled propertyeditor propertyeditor propertyeditor supportscustomeditor propertyeditor createwrappereditor propertyeditor isdebugenabled propertyeditor propertyeditor getcustomeditor jscrollpane scrollercount propertyeditor seteditorvalue getvalue propertyfieldlabelmessage messageformat jmeterutils getresstring property_as_field_label propertytooltipmessage messageformat jmeterutils getresstring property_tool_tip find the default type editor and a suitable gui editor for the given property descriptor and combine them in a wrapper editor param type editor param descriptor return private wrapper editor create wrapper editor property editor type editor property descriptor descriptor string editor tags type editor get tags string additional tags string descriptor get value tags string tags null if editor tags null tags additional tags else if additional tags null tags editor tags else tags new string editor tags length additional tags length int j 0 for int i 0 i editor tags length i tags j editor tags i for int i 0 i additional tags length i tags j additional tags i boolean not null boolean true equals descriptor get value not undefined boolean not expression boolean true equals descriptor get value not expression boolean not other boolean true equals descriptor get value not other property editor gui editor if not null tags null gui editor new field string editor else combo string editor e new combo string editor e set no undefined not null e set no edit not expression not other e set tags tags gui editor e wrapper editor wrapper new wrapper editor type editor gui editor not null accepts null not expression accepts expressions not other accepts other descriptor get value default return wrapper typeeditor guieditor wrappereditor typeeditor wrappereditor createwrappereditor propertyeditor typeeditor propertydescriptor editortags typeeditor gettags additionaltags getvalue editortags additionaltags additionaltags editortags editortags additionaltags editortags editortags additionaltags additionaltags notnull getvalue not_undefined notexpression getvalue not_expression notother getvalue not_other propertyeditor guieditor notnull guieditor fieldstringeditor combostringeditor combostringeditor setnoundefined notnull setnoedit notexpression notother settags guieditor wrappereditor wrappereditor typeeditor guieditor notnull acceptsnull notexpression acceptsexpressions notother acceptsother getvalue set the value of the i th property properly reporting a possible failure param i the index of the property in the descriptors and editors arrays param value the value to be stored in the editor throws illegal argument exception if the editor refuses the value private void set editor value int i object value throws illegal argument exception editors i set value value illegalargumentexception seteditorvalue illegalargumentexception setvalue public void set object object map property map map map if property map size 0 uninitialized set it to the defaults for int i 0 i editors length i object value descriptors i get value default string name descriptors i get name if value null property map put name value log debug set name value fire property change name null value now set the editors to the element s values for int i 0 i editors length i if editors i null continue try set editor value i property map get descriptors i get name catch illegal argument exception e i guess this can happen as a result of a bad file read in this case it would be better to replace the incorrect value with anything valid e g the default value for the property but for the time being i just prefer to be aware of any problems occuring here most likely programming errors so i ll bail out ms note can t bail out newly create elements have blank values and must get the defaults also when loading previous versions of jmeter test scripts some values may not be right and should get default values ms todo review this and possibly change to set editor value i descriptors i get value default setobject propertymap propertymap getvalue getname propertymap firepropertychange seteditorvalue propertymap getname illegalargumentexception seteditorvalue getvalue initialize the gui private void init set layout new grid bag layout grid bag constraints cl new grid bag constraints for labels cl gridx 0 cl anchor grid bag constraints east cl insets new insets 0 1 0 1 grid bag constraints ce new grid bag constraints for editors ce fill grid bag constraints both ce gridx 1 ce weightx 1 0 ce insets new insets 0 1 0 1 grid bag constraints cp new grid bag constraints for panels cp fill grid bag constraints both cp gridx 1 cp gridy grid bag constraints relative cp gridwidth 2 cp weightx 1 0 j panel current panel this string current group default group int y 0 for int i 0 i editors length i if editors i null continue if log is debug enabled log debug laying property descriptors i get name string g group descriptors i if current group equals g if current panel this add current panel cp current group g current panel new j panel new grid bag layout current panel set border border factory create titled border border factory create etched border group display name g cp weighty 0 0 y 0 component custom editor editors i get custom editor boolean multi line editor false if custom editor get preferred size height 50 custom editor instanceof j scroll pane todo the above works in the current situation but it s just a hack how to get each editor to report whether it wants to grow bigger whether the property label should be at the left or at the top of the editor multi line editor true j label label create label descriptors i label set label for custom editor cl gridy y cl gridwidth multi line editor 2 1 cl anchor multi line editor grid bag constraints center grid bag constraints east current panel add label cl ce gridx multi line editor 0 1 ce gridy multi line editor y y ce gridwidth multi line editor 2 1 ce weighty multi line editor 1 0 0 0 cp weighty ce weighty current panel add custom editor ce y if current panel this add current panel cp add a 0 sized invisible component that will take all the vertical space that nobody wants cp weighty 0 0001 add box create horizontal strut 0 cp setlayout gridbaglayout gridbagconstraints gridbagconstraints gridbagconstraints gridbagconstraints gridbagconstraints gridbagconstraints gridbagconstraints gridbagconstraints gridbagconstraints gridbagconstraints jpanel currentpanel currentgroup default_group isdebugenabled getname currentgroup currentpanel currentpanel currentgroup currentpanel jpanel gridbaglayout currentpanel setborder borderfactory createtitledborder borderfactory createetchedborder groupdisplayname customeditor getcustomeditor multilineeditor customeditor getpreferredsize customeditor jscrollpane multilineeditor jlabel createlabel setlabelfor customeditor multilineeditor multilineeditor gridbagconstraints gridbagconstraints currentpanel multilineeditor multilineeditor multilineeditor multilineeditor currentpanel customeditor currentpanel currentpanel createhorizontalstrut private j label create label property descriptor desc string text desc get display name if equals text text property field label message format new object desc get display name if the display name is the empty string leave it like that j label label new j label text label set horizontal alignment j label trailing text property tool tip message format new object desc get name desc get short description label set tool tip text text return label jlabel createlabel propertydescriptor getdisplayname propertyfieldlabelmessage getdisplayname displayname jlabel jlabel sethorizontalalignment jlabel propertytooltipmessage getname getshortdescription settooltiptext obtain a property descriptor s group param descriptor return the group string private string group property descriptor d string group string d get value group if group null group default group return group propertydescriptor getvalue default_group obtain a group s display name private string group display name string group try resource bundle b resource bundle bean info get bean descriptor get value resource bundle if b null return group return b get string group display name catch missing resource exception e return group groupdisplayname resourcebundle resourcebundle beaninfo getbeandescriptor getvalue resource_bundle getstring displayname missingresourceexception private class property comparator implements comparator serializable public int compare object o1 object o2 return compare property descriptor o1 property descriptor o2 propertycomparator propertydescriptor propertydescriptor private int compare property descriptor d1 property descriptor d2 int result string g1 group d1 g2 group d2 integer go1 group order g1 go2 group order g2 result go1 compare to go2 if result 0 return result result g1 compare to g2 if result 0 return result integer po1 property order d1 po2 property order d2 result po1 compare to po2 if result 0 return result return d1 get name compare to d2 get name propertydescriptor propertydescriptor grouporder grouporder compareto compareto propertyorder propertyorder compareto getname compareto getname obtain a group s order param group group name return the group s order zero by default private integer group order string group integer order integer bean info get bean descriptor get value order group if order null order new integer 0 return order grouporder beaninfo getbeandescriptor getvalue obtain a property s order param d return the property s order attribute zero by default private integer property order property descriptor d integer order integer d get value order if order null order new integer 0 return order propertyorder propertydescriptor getvalue save values from the gui fields into the property map void save gui fields for int i 0 i editors length i property editor property editor editors i might be null e g in testing if property editor null object value property editor get value string name descriptors i get name if value null property map remove name if log is debug enabled log debug unset name else property map put name value if log is debug enabled log debug set name value saveguifields propertyeditor propertyeditor propertyeditor propertyeditor getvalue getname propertymap isdebugenabled propertymap isdebugenabled void clear gui fields for int i 0 i editors length i property editor property editor editors i might be null e g in testing if property editor null try if property editor instanceof wrapper editor wrapper editor we wrapper editor property editor string tags we get tags if tags null tags length 0 we set as text tags 0 else we set value else if property editor instanceof combo string editor combo string editor cse combo string editor property editor cse set as text cse get initial edit value else property editor set as text catch illegal argument exception ex log error failed to set field descriptors i get name ex clearguifields propertyeditor propertyeditor propertyeditor propertyeditor wrappereditor wrappereditor wrappereditor propertyeditor gettags setastext setvalue propertyeditor combostringeditor combostringeditor combostringeditor propertyeditor setastext getinitialeditvalue propertyeditor setastext illegalargumentexception getname constructor for the remove object public remove gets the action names attribute of the remove object return the action names value public set get action names return commands actionnames actionnames getactionnames public void do action action event e todo removes the nodes from the check dirty map should it be done later in case some can t be removed action router get instance action performed new action event e get source e getid action names check remove gui package gui package gui package get instance j meter tree node nodes gui package get tree listener get selected nodes tree path new tree path save parent node for later gui package get tree listener removed selected node for int i nodes length 1 i 0 i remove node nodes i gui package get tree listener getj tree set selection path new tree path gui package update current gui doaction actionevent checkdirty actionrouter getinstance actionperformed actionevent getsource actionnames check_remove guipackage guipackage guipackage getinstance jmetertreenode guipackage gettreelistener getselectednodes treepath newtreepath guipackage gettreelistener removedselectednode removenode guipackage gettreelistener getjtree setselectionpath newtreepath guipackage updatecurrentgui private static void remove node j meter tree node node test element test element node get test element if test element can remove gui package get instance get tree model remove node from parent node gui package get instance remove node test element else string message test element get class get name is busy j option pane show message dialog null message cannot remove item j option pane error message removenode jmetertreenode testelement testelement gettestelement testelement canremove guipackage getinstance gettreemodel removenodefromparent guipackage getinstance removenode testelement testelement getclass getname joptionpane showmessagedialog joptionpane error_message the default constructor is empty public log filter super logfilter the method will replace the file extension with the new one you can either provide the extension without the period or with the method will check for period and add it if it isn t present see org apache jmeter protocol http util accesslog filter set replace extension java lang string java lang string public void set replace extension string oldext string newext if oldext null newext null this changeext true if oldext index of 0 newext index of 0 this oldext oldext this newext newext else this oldext oldext this newext newext setreplaceextension setreplaceextension indexof indexof give the filter a list of files to include param filenames see org apache jmeter protocol http util accesslog filter include files java lang string public void include files string filenames if filenames null filenames length 0 incfile filenames this filefilter true includefiles includefiles give the filter a list of files to exclude param filenames see org apache jmeter protocol http util accesslog filter exclude files java lang string public void exclude files string filenames if filenames null filenames length 0 excfile filenames this filefilter true excludefiles excludefiles give the filter a set of regular expressions to filter with for inclusion this method hasn t been fully implemented and test yet the implementation is not complete param regexp see org apache jmeter protocol http util accesslog filter include pattern string public void include pattern string regexp if regexp null regexp length 0 incptrn regexp this ptrnfilter true now we create the compiled pattern and add it to the arraylist for int idx 0 idx incptrn length idx this incpatterns add this create pattern incptrn idx includepattern includepattern createpattern give the filter a set of regular expressions to filter with for exclusion this method hasn t been fully implemented and test yet the implementation is not complete param regexp see org apache jmeter protocol http util accesslog filter exclude pattern string public void exclude pattern string regexp if regexp null regexp length 0 excptrn regexp this ptrnfilter true now we create the compiled pattern and add it to the arraylist for int idx 0 idx excptrn length idx this excpatterns add this create pattern excptrn idx excludepattern excludepattern createpattern in the case of log filtering the important thing is whether the log entry should be used therefore the method will only return true if the entry should be used since the interface defines both inclusion and exclusion that means by default inclusion filtering assumes all entries are excluded unless it matches in the case of exlusion filtering it assumes all entries are included unless it matches which means it should be excluded see org apache jmeter protocol http util accesslog filter is filtered string test element param path return boolean public boolean is filtered string path test element el we do a quick check to see if any filters are set if not we just return false to be efficient if this filefilter this ptrnfilter this changeext if this filefilter return filter file path else if this ptrnfilter return filter pattern path else return false else return false isfiltered testelement isfiltered testelement filterfile filterpattern filter the file the implementation performs the exclusion first before the inclusion this means if a file name is in both string arrays the exclusion will take priority depending on how users expect this to work we may want to change the priority so that inclusion is performed first and exclusion second another possible alternative is to perform both inclusion and exclusion doing so would make the most sense if the method throws an exception and tells the user the same filename is in both the include and exclude array param file return boolean protected boolean filter file string file double check this logic make sure it makes sense if this excfile null return exc file file else if this incfile null return inc file file return false filterfile excfile incfile method implements the logic for filtering file name inclusion the method iterates through the array and uses index of once it finds a match it won t bother with the rest of the filenames in the array param text return boolean include public boolean inc file string text inclusion filter assumes most of the files are not wanted therefore usefile is set to false unless it matches this usefile false for int idx 0 idx this incfile length idx if text index of this incfile idx 1 this usefile true break return this usefile indexof incfile indexof method implements the logic for filtering file name exclusion the method iterates through the array and uses index of once it finds a match it won t bother with the rest of the filenames in the array param text return boolean exclude public boolean exc file string text exclusion filter assumes most of the files are used therefore usefile is set to true unless it matches this usefile true boolean exc false for int idx 0 idx this excfile length idx if text index of this excfile idx 1 exc true this usefile false break return exc indexof excfile indexof the current implemenation assumes the user has checked the regular expressions so that they don t cancel each other the basic assumption is the method will return true if the text should be filtered if not it will return false which means it should not be filtered param text return boolean protected boolean filter pattern string text if this incptrn null return inc pattern text else if this excptrn null return exc pattern text return false filterpattern incpattern excpattern by default the method assumes the entry is not included unless it matches in that case it will return true param text return true if text is included protected boolean inc pattern string text this usefile false for int idx 0 idx this incpatterns size idx if j meter utils get matcher contains text pattern this incpatterns get idx this usefile true break return this usefile incpattern jmeterutils getmatcher the method assumes by default the text is not excluded if the text matches the pattern it will then return true param text return true if text is excluded protected boolean exc pattern string text this usefile true boolean exc false for int idx 0 idx this excpatterns size idx if j meter utils get matcher contains text pattern this excpatterns get idx exc true this usefile false break return exc excpattern jmeterutils getmatcher method uses index of to replace the old extension with the new extesion it might be good to use regular expression but for now this is a simple method the method isn t designed to replace multiple instances of the text since that isn t how file extensions work if the string contains more than one instance of the old extension only the first instance will be replaced param text return boolean public boolean replace extension string text int pt text index of this oldext if pt 1 int extsize this oldext length this newfile text substring 0 pt this newext text substring pt extsize return true else return false indexof replaceextension indexof the current implementation checks the boolean if the text should be used or not is filter string has to be called first see org apache jmeter protocol http util accesslog filter filter java lang string public string filter string text if this changeext if replace extension text return this newfile else return text else if this usefile return text else return null isfilter replaceextension create a new pattern object from the string param pattern return pattern public pattern create pattern string pattern try return j meter utils get pattern cache get pattern pattern perl5 compiler read only mask perl5 compiler singleline mask catch malformed cache pattern exception exception log error problem with pattern pattern exception return null createpattern jmeterutils getpatterncache getpattern perl5compiler read_only_mask perl5compiler singleline_mask malformedcachepatternexception see org apache jmeter protocol http util accesslog filter reset public void reset public abstract visualizer super error logging and success only logging are mutually exclusive error logging new j check box j meter utils get res string log errors only non nls 1 error logging add action listener new action listener public void action performed action event e if error logging is selected success only logging set selected false success only logging new j check box j meter utils get res string log success only non nls 1 success only logging add action listener new action listener public void action performed action event e if success only logging is selected error logging set selected false save config button new j button j meter utils get res string config save settings non nls 1 save config button add action listener new action listener public void action performed action event e save property dialog d new save property dialog gui package get instance get main frame j meter utils get res string sample result save configuration non nls 1 true collector get save config d pack component util center component in component gui package get instance get main frame d d set visible true file panel new file panel j meter utils get res string file visualizer output file jtl non nls 1 non nls 2 file panel add change listener this file panel add new j label j meter utils get res string log only non nls 1 file panel add error logging file panel add success only logging file panel add save config button abstractvisualizer errorlogging successonlylogging errorlogging jcheckbox jmeterutils getresstring log_errors_only errorlogging addactionlistener actionlistener actionperformed actionevent errorlogging isselected successonlylogging setselected successonlylogging jcheckbox jmeterutils getresstring log_success_only successonlylogging addactionlistener actionlistener actionperformed actionevent successonlylogging isselected errorlogging setselected saveconfigbutton jbutton jmeterutils getresstring config_save_settings saveconfigbutton addactionlistener actionlistener actionperformed actionevent savepropertydialog savepropertydialog guipackage getinstance getmainframe jmeterutils getresstring sample_result_save_configuration getsaveconfig componentutil centercomponentincomponent guipackage getinstance getmainframe setvisible filepanel filepanel jmeterutils getresstring file_visualizer_output_file filepanel addchangelistener filepanel jlabel jmeterutils getresstring log_only filepanel errorlogging filepanel successonlylogging filepanel saveconfigbutton error logging add action listener new action listener public void action performed action event e if error logging is selected success only logging set selected false errorlogging addactionlistener actionlistener actionperformed actionevent errorlogging isselected successonlylogging setselected success only logging add action listener new action listener public void action performed action event e if success only logging is selected error logging set selected false successonlylogging addactionlistener actionlistener actionperformed actionevent successonlylogging isselected errorlogging setselected save config button add action listener new action listener public void action performed action event e save property dialog d new save property dialog gui package get instance get main frame j meter utils get res string sample result save configuration non nls 1 true collector get save config d pack component util center component in component gui package get instance get main frame d d set visible true saveconfigbutton addactionlistener actionlistener actionperformed actionevent savepropertydialog savepropertydialog guipackage getinstance getmainframe jmeterutils getresstring sample_result_save_configuration getsaveconfig componentutil centercomponentincomponent guipackage getinstance getmainframe setvisible public boolean is stats return is stats isstats isstats gets the checkbox which selects whether or not only errors should be logged subclasses don t normally need to worry about this checkbox because it is automatically added to the gui in link make title panel and the behavior is handled in this base class return the error logging checkbox protected j check box get error logging checkbox return error logging maketitlepanel jcheckbox geterrorloggingcheckbox errorlogging provides access to the result collector model class for extending implementations using this method and set model result collector is only necessary if your visualizer requires a differently behaving result collector using these methods will allow maximum reuse of the methods provided by abstract visualizer in this event protected result collector get model return collector resultcollector setmodel resultcollector resultcollector abstractvisualizer resultcollector getmodel gets the file panel which allows the user to save results to a file subclasses don t normally need to worry about this panel because it is automatically added to the gui in link make title panel and the behavior is handled in this base class return the file panel allowing users to save results protected component get file panel return file panel maketitlepanel getfilepanel filepanel sets the filename which results will be saved to this will set the filename in the file panel subclasses don t normally need to call this method because configuration of the file panel is handled in this base class param filename the new filename see get file panel public void set file string filename todo does this method need to be public it isn t currently called outside of this class file panel set filename filename filepanel filepanel getfilepanel setfile filepanel setfilename gets the filename which has been entered in the file panel subclasses don t normally need to call this method because configuration of the file panel is handled in this base class return the current filename see get file panel public string get file todo does this method need to be public it isn t currently called outside of this class return file panel get filename filepanel filepanel getfilepanel getfile filepanel getfilename invoked when the target of the listener has changed its state this implementation assumes that the target is the file panel and will update the result collector for the new filename param e the event that has occurred public void state changed change event e log debug getting new collector collector result collector create test element collector load existing file filepanel statechanged changeevent resultcollector createtestelement loadexistingfile implements j metergui component create test element public test element create test element if collector null collector new result collector modify test element collector return test element collector clone jmeterguicomponent createtestelement testelement createtestelement resultcollector modifytestelement testelement implements j metergui component modify test element test element public void modify test element test element c configure test element abstract listener element c if c instanceof result collector result collector rc result collector c rc set error logging error logging is selected rc set success only logging success only logging is selected rc set filename get file collector rc jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement abstractlistenerelement resultcollector resultcollector resultcollector seterrorlogging errorlogging isselected setsuccessonlylogging successonlylogging isselected setfilename getfile overrides abstractj meter gui component configure test element public void configure test element el super configure el set file el get property as string result collector filename result collector rc result collector el error logging set selected rc is error logging success only logging set selected rc is success only logging if collector null collector new result collector collector set save config sample save configuration rc get save config clone abstractjmeterguicomponent testelement testelement setfile getpropertyasstring resultcollector resultcollector resultcollector errorlogging setselected iserrorlogging successonlylogging setselected issuccessonlylogging resultcollector setsaveconfig samplesaveconfiguration getsaveconfig this provides a convenience for extenders when they implement the link org apache jmeter gui j metergui component create test element method this method will set the name gui class and test class for the created test element it should be called by every extending class when creating test elements as that will best assure consistent behavior param mc the test element being created protected void configure test element abstract listener element mc todo should the method signature of this method be changed to match the super implementation using a test element parameter instead of abstract listener element this would require an instanceof check before adding the listener below but would also make the behavior a bit more obvious for sub classes the java rules dealing with this situation aren t always intuitive and a subclass may think it is calling this version of the method when it is really calling the superclass version instead super configure test element mc mc set listener this jmeterguicomponent createtestelement testelement configuretestelement abstractlistenerelement testelement abstractlistenerelement configuretestelement setlistener create a standard title section for j meter components this includes the title for the component and the name panel allowing the user to change the name for the component the abstract visualizer also adds the file panel allowing the user to save the results and the error logging checkbox allowing the user to choose whether or not only errors should be logged p this method is typically added to the top of the component at the beginning of the component s init method return a panel containing the component title name panel file panel and error logging checkbox protected container make title panel container panel super make title panel note the file panel already includes the error logging checkbox so we don t have to add it explicitly panel add get file panel return panel jmeter abstractvisualizer filepanel maketitlepanel maketitlepanel getfilepanel provides extending classes the opportunity to set the result collector model for the visualizer this is useful to allow maximum reuse of the methods from abstract visualizer param collector protected void set model result collector collector this collector collector resultcollector abstractvisualizer setmodel resultcollector public void clear gui super clear gui file panel clear gui cleargui cleargui filepanel cleargui private j text area script field script area public bean shell assertion gui init jtextarea scriptfield beanshellassertiongui public void configure test element element script field set text element get property as string bean shell assertion script filename set text element get property as string bean shell assertion filename parameters set text element get property as string bean shell assertion parameters reset interpreter set selected element get property as boolean bean shell assertion reset interpreter super configure element testelement scriptfield settext getpropertyasstring beanshellassertion settext getpropertyasstring beanshellassertion settext getpropertyasstring beanshellassertion resetinterpreter setselected getpropertyasboolean beanshellassertion reset_interpreter public test element create test element bean shell assertion sampler new bean shell assertion modify test element sampler return sampler testelement createtestelement beanshellassertion beanshellassertion modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element te te clear this configure test element te te set property bean shell assertion script script field get text te set property bean shell assertion filename filename get text te set property bean shell assertion parameters parameters get text te set property new boolean property bean shell assertion reset interpreter reset interpreter is selected testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement setproperty beanshellassertion scriptfield gettext setproperty beanshellassertion gettext setproperty beanshellassertion gettext setproperty booleanproperty beanshellassertion reset_interpreter resetinterpreter isselected public string get label resource return bsh assertion title non nls 1 getlabelresource bsh_assertion_title private j panel create filename panel todo ought to be a file chooser j label label new j label j meter utils get res string bsh script file non nls 1 filename new j text field 10 filename set name bean shell assertion filename label set label for filename j panel filename panel new j panel new border layout 5 0 filename panel add label border layout west filename panel add filename border layout center return filename panel jpanel createfilenamepanel filechooser jlabel jlabel jmeterutils getresstring bsh_script_file jtextfield setname beanshellassertion setlabelfor jpanel filenamepanel jpanel borderlayout filenamepanel borderlayout filenamepanel borderlayout filenamepanel private j panel create reset panel reset interpreter new j check box j meter utils get res string bsh script reset interpreter non nls 1 reset interpreter set name bean shell assertion parameters j panel reset interpreter panel new j panel new border layout reset interpreter panel add reset interpreter border layout west return reset interpreter panel jpanel createresetpanel resetinterpreter jcheckbox jmeterutils getresstring bsh_script_reset_interpreter resetinterpreter setname beanshellassertion jpanel resetinterpreterpanel jpanel borderlayout resetinterpreterpanel resetinterpreter borderlayout resetinterpreterpanel private j panel create parameter panel j label label new j label j meter utils get res string bsh script parameters non nls 1 parameters new j text field 10 parameters set name bean shell assertion parameters label set label for parameters j panel parameter panel new j panel new border layout 5 0 parameter panel add label border layout west parameter panel add parameters border layout center return parameter panel jpanel createparameterpanel jlabel jlabel jmeterutils getresstring bsh_script_parameters jtextfield setname beanshellassertion setlabelfor jpanel parameterpanel jpanel borderlayout parameterpanel borderlayout parameterpanel borderlayout parameterpanel private void init set layout new border layout 0 5 set border make border box box box create vertical box box add make title panel box add create reset panel box add create parameter panel box add create filename panel add box border layout north j panel panel create script panel add panel border layout center don t let the input field shrink too much add box create vertical strut panel get preferred size height border layout west setlayout borderlayout setborder makeborder createverticalbox maketitlepanel createresetpanel createparameterpanel createfilenamepanel borderlayout jpanel createscriptpanel borderlayout createverticalstrut getpreferredsize borderlayout private j panel create script panel script field new j text area script field set rows 4 script field set line wrap true script field set wrap style word true j label label new j label j meter utils get res string bsh assertion script non nls 1 label set label for script field j panel panel new j panel new border layout panel add label border layout north panel add new j scroll pane script field border layout center j text area explain new j text area j meter utils get res string bsh assertion script variables non nls 1 explain set line wrap true explain set editable false explain set background this get background panel add explain border layout south return panel jpanel createscriptpanel scriptfield jtextarea scriptfield setrows scriptfield setlinewrap scriptfield setwrapstyleword jlabel jlabel jmeterutils getresstring bsh_assertion_script setlabelfor scriptfield jpanel jpanel borderlayout borderlayout jscrollpane scriptfield borderlayout jtextarea jtextarea jmeterutils getresstring bsh_assertion_script_variables setlinewrap seteditable setbackground getbackground borderlayout public void clear gui super clear gui filename set text non nls 1 parameters set text non nls 1 script field set text non nls 1 reset interpreter set selected false cleargui cleargui settext settext scriptfield settext resetinterpreter setselected public view results full visualizer super log debug start view results full visualizer1 init log debug end view results full visualizer1 viewresultsfullvisualizer viewresultsfullvisualizer1 viewresultsfullvisualizer1 public void add sample result res update gui res sampleresult updategui public string get label resource return view results tree title non nls 1 getlabelresource view_results_tree_title update the visualizer with new data private synchronized void update gui sample result res log debug start update gui1 if log is debug enabled log debug update gui1 sample result res add sample default mutable tree node curr node new default mutable tree node res tree model insert node into curr node root root get child count add sub results curr node res add any assertion that failed as children of the sample node assertion result assertion results res get assertion results int assertion index curr node get child count for int j 0 j assertion results length j assertion result item assertion results j if item is failure item is error default mutable tree node assertion node new default mutable tree node item tree model insert node into assertion node curr node assertion index if root get child count 1 j tree expand path new tree path root log debug end update gui1 updategui sampleresult updategui1 isdebugenabled updategui1 defaultmutabletreenode currnode defaultmutabletreenode treemodel insertnodeinto currnode getchildcount addsubresults currnode assertionresult assertionresults getassertionresults assertionindex currnode getchildcount assertionresults assertionresult assertionresults isfailure iserror defaultmutabletreenode assertionnode defaultmutabletreenode treemodel insertnodeinto assertionnode currnode assertionindex getchildcount jtree expandpath treepath updategui1 private void add sub results default mutable tree node curr node sample result res sample result sub results res get sub results int leaf index 0 for int i 0 i sub results length i sample result child sub results i if log is debug enabled log debug update gui1 child sample result child default mutable tree node leaf node new default mutable tree node child tree model insert node into leaf node curr node leaf index add sub results leaf node child add any assertion that failed as children of the sample node assertion result assertion results child get assertion results int assertion index leaf node get child count for int j 0 j assertion results length j assertion result item assertion results j if item is failure item is error default mutable tree node assertion node new default mutable tree node item tree model insert node into assertion node leaf node assertion index addsubresults defaultmutabletreenode currnode sampleresult sampleresult subresults getsubresults leafindex subresults sampleresult subresults isdebugenabled updategui1 defaultmutabletreenode leafnode defaultmutabletreenode treemodel insertnodeinto leafnode currnode leafindex addsubresults leafnode assertionresult assertionresults getassertionresults assertionindex leafnode getchildcount assertionresults assertionresult assertionresults isfailure iserror defaultmutabletreenode assertionnode defaultmutabletreenode treemodel insertnodeinto assertionnode leafnode assertionindex clears the visualizer public synchronized void clear data log debug start clear1 if log is debug enabled log debug clear1 total child root get child count while root get child count 0 the child to be removed will always be 0 cos as the nodes are removed the nth node will become n 1 th tree model remove node from parent default mutable tree node root get child at 0 results set text response data non nls 1 sample data field set text request data non nls 1 log debug end clear1 cleardata isdebugenabled getchildcount getchildcount treemodel removenodefromparent defaultmutabletreenode getchildat settext sampledatafield settext returns the description of this visualizer return description of this visualizer public string to string string desc j meter utils get res string view results desc non nls 1 if log is debug enabled log debug to string1 returning description desc return desc tostring jmeterutils getresstring view_results_desc isdebugenabled tostring1 sets the right pane to correspond to the selected node of the left tree public void value changed tree selection event e log debug start value changed1 default mutable tree node node default mutable tree node j tree get last selected path component if log is debug enabled log debug value changed selected node node styled document stats doc stats get styled document try stats doc remove 0 stats doc get length sample data field set text non nls 1 results set text non nls 1 if node null object user object node get user object if user object instanceof sample result sample result res sample result user object we are displaying a sample result setup tab pane for sample result if log is debug enabled log debug value changed1 sample result res load time label log debug value changed1 load time res get time string sd res get sampler data if sd null string rh res get request headers if rh null string buffer sb new string buffer sd length rh length 20 sb append sd sb append n non nls 1 sb append j meter utils get res string view results request headers non nls 1 sb append n non nls 1 sb append rh sd sb to string sample data field set text sd string buffer stats buff new string buffer 200 stats buff append j meter utils get res string view results thread name append res get thread name append nl non nls 1 string start time date format format new date res get start time stats buff append j meter utils get res string view results sample start append start time append nl non nls 1 stats buff append j meter utils get res string view results load time append res get time append nl non nls 1 stats buff append j meter utils get res string view results latency append res get latency append nl non nls 1 stats buff append j meter utils get res string view results size in bytes append res get bytes append nl non nls 1 stats buff append j meter utils get res string view results sample count append res get sample count append nl non nls 1 stats buff append j meter utils get res string view results error count append res get error count append nl non nls 1 stats doc insert string stats doc get length stats buff to string null stats buff new string buffer reset for reuse string response code res get response code log debug value changed1 response code response code int response level 0 if response code null try response level integer parse int response code 100 catch number format exception number format exception no need to change the foreground color style style null switch response level case 3 style stats doc get style style redirect break case 4 style stats doc get style style client error break case 5 style stats doc get style style server error break stats buff append j meter utils get res string view results response code append response code append nl non nls 1 stats doc insert string stats doc get length stats buff to string style stats buff new string buffer 100 reset for reuse response message label string response msg str res get response message log debug value changed1 response message response msg str stats buff append j meter utils get res string view results response message append response msg str append nl non nls 1 stats buff append nl stats buff append j meter utils get res string view results response headers append nl non nls 1 stats buff append res get response headers append nl stats buff append nl final string sampler class res get class get name stats buff append sampler class substring 1 sampler class last index of append j meter utils get res string view results fields append nl non nls 1 stats buff append content type append res get content type append nl stats buff append data encoding append res get data encoding no default append nl stats doc insert string stats doc get length stats buff to string null stats buff null done get the text response and image icon to determine which is not null if sample result text equals res get data type equals null is ok string response get response as string res if command equals text command show text response response else if command equals html command show rendered response response res else if command equals json command show renderjson response response else if command equals xml command show renderxml response res else byte response bytes res get response data if response bytes null show image new image icon response bytes todo implement other non text types else if user object instanceof assertion result assertion result res assertion result user object we are displaying an assertion result setup tab pane for assertion result if log is debug enabled log debug value changed1 sample result res string buffer stats buff new string buffer 100 stats buff append j meter utils get res string view results assertion error append res is error append nl non nls 1 stats buff append j meter utils get res string view results assertion failure append res is failure append nl non nls 1 stats buff append j meter utils get res string view results assertion failure message append res get failure message append nl non nls 1 stats doc insert string stats doc get length stats buff to string null stats buff null catch bad location exception exc log error error setting statistics text exc stats set text log debug end value changed1 valuechanged treeselectionevent valuechanged1 defaultmutabletreenode defaultmutabletreenode jtree getlastselectedpathcomponent isdebugenabled valuechanged styleddocument statsdoc getstyleddocument statsdoc statsdoc getlength sampledatafield settext settext userobject getuserobject userobject sampleresult sampleresult sampleresult userobject sampleresult setuptabpaneforsampleresult isdebugenabled valuechanged1 valuechanged1 gettime getsamplerdata getrequestheaders stringbuffer stringbuffer jmeterutils getresstring view_results_request_headers tostring sampledatafield settext stringbuffer statsbuff stringbuffer statsbuff jmeterutils getresstring view_results_thread_name getthreadname starttime dateformat getstarttime statsbuff jmeterutils getresstring view_results_sample_start starttime statsbuff jmeterutils getresstring view_results_load_time gettime statsbuff jmeterutils getresstring view_results_latency getlatency statsbuff jmeterutils getresstring view_results_size_in_bytes getbytes statsbuff jmeterutils getresstring view_results_sample_count getsamplecount statsbuff jmeterutils getresstring view_results_error_count geterrorcount statsdoc insertstring statsdoc getlength statsbuff tostring statsbuff stringbuffer responsecode getresponsecode valuechanged1 responsecode responselevel responsecode responselevel parseint responsecode numberformatexception numberformatexception responselevel statsdoc getstyle style_redirect statsdoc getstyle style_client_error statsdoc getstyle style_server_error statsbuff jmeterutils getresstring view_results_response_code responsecode statsdoc insertstring statsdoc getlength statsbuff tostring statsbuff stringbuffer responsemsgstr getresponsemessage valuechanged1 responsemsgstr statsbuff jmeterutils getresstring view_results_response_message responsemsgstr statsbuff statsbuff jmeterutils getresstring view_results_response_headers statsbuff getresponseheaders statsbuff samplerclass getclass getname statsbuff samplerclass samplerclass lastindexof jmeterutils getresstring view_results_fields statsbuff contenttype getcontenttype statsbuff dataencoding getdataencodingnodefault statsdoc insertstring statsdoc getlength statsbuff tostring statsbuff sampleresult getdatatype getresponseasstring text_command showtextresponse html_command showrenderedresponse json_command showrenderjsonresponse xml_command showrenderxmlresponse responsebytes getresponsedata responsebytes showimage imageicon responsebytes userobject assertionresult assertionresult assertionresult userobject assertionresult setuptabpaneforassertionresult isdebugenabled valuechanged1 stringbuffer statsbuff stringbuffer statsbuff jmeterutils getresstring view_results_assertion_error iserror statsbuff jmeterutils getresstring view_results_assertion_failure isfailure statsbuff jmeterutils getresstring view_results_assertion_failure_message getfailuremessage statsdoc insertstring statsdoc getlength statsbuff tostring statsbuff badlocationexception settext valuechanged1 private void show image icon image image label set icon image results scroll pane set viewport view image label text button set enabled false html button set enabled false json button set enabled false xml button set enabled false showimage imagelabel seticon resultsscrollpane setviewportview imagelabel textbutton setenabled htmlbutton setenabled jsonbutton setenabled xmlbutton setenabled private void show text response string response results set content type text plain non nls 1 results set text response null response non nls 1 results set caret position 0 results scroll pane set viewport view results text button set enabled true html button set enabled true json button set enabled true xml button set enabled true showtextresponse setcontenttype settext setcaretposition resultsscrollpane setviewportview textbutton setenabled htmlbutton setenabled jsonbutton setenabled xmlbutton setenabled when posting json private static string prettyjson string json string buffer pretty new string buffer json length 2 educated guess final string tab non nls 1 string buffer index new string buffer string nl non nls 1 matcher value or pair value or pair pattern matcher json boolean misparse false for int i 0 i json length final char current char json char at i if current char current char pretty append nl append index append current char i index append tab misparse false else if current char current char if index length 0 index delete 0 tab length pretty append nl append index append current char i int j i while j json length character is whitespace json char at j j if j json length json char at j pretty append non nls 1 i j 1 misparse false else if value or pair find i value or pair group length 0 pretty append nl append index append value or pair group i value or pair end misparse false else if misparse pretty append nl append parse failed from pretty append current char i misparse true nl n non nls 1 return pretty to string stringbuffer stringbuffer stringbuffer stringbuffer valueorpair value_or_pair_pattern currentchar charat currentchar currentchar currentchar currentchar currentchar currentchar iswhitespace charat charat valueorpair valueorpair valueorpair valueorpair currentchar tostring private void show renderjson response string response results set content type text plain non nls 1 results set text response null prettyjson response results set caret position 0 results scroll pane set viewport view results text button set enabled true html button set enabled true json button set enabled true xml button set enabled true showrenderjsonresponse setcontenttype settext setcaretposition resultsscrollpane setviewportview textbutton setenabled htmlbutton setenabled jsonbutton setenabled xmlbutton setenabled private void show renderxml response sample result res results set content type text xml non nls 1 results set caret position 0 byte source res get response data final byte array input stream bais new byte array input stream source for int i 0 i source length xml pfx length i if j orphan utils starts with source xml pfx i bais skip i skip the leading bytes if any break component view results there is also a javax swing text document class org w3c dom document document null string writer sw new string writer tidy tidy x path util make tidy parser true true true sw document tidy parsedom bais null document normalize if tidy get parse errors 0 show error message dialog sw to string tidy tidy get parse errors errors tidy get parse warnings warnings j option pane warning message j panel dom tree panel new dom tree panel document view dom tree panel results scroll pane set viewport view view text button set enabled true html button set enabled true json button set enabled true xml button set enabled true showrenderxmlresponse sampleresult setcontenttype setcaretposition getresponsedata bytearrayinputstream bytearrayinputstream xml_pfx jorphanutils startswith xml_pfx stringwriter stringwriter xpathutil maketidyparser getparseerrors showerrormessagedialog tostring getparseerrors getparsewarnings joptionpane warning_message jpanel domtreepanel domtreepanel domtreepanel resultsscrollpane setviewportview textbutton setenabled htmlbutton setenabled jsonbutton setenabled xmlbutton setenabled private static string get response as string sample result res string response null if sample result text equals res get data type showing large strings can be very costly so we will avoid doing so if the response data is larger than 200k todo instead we could delay doing the result set text call until the user chooses the response data tab plus we could warn the user if this happens and revert the choice if he doesn t confirm he s ready to wait int len res get response data length if max display size 0 len max display size response j meter utils get res string view results response too large message non nls 1 len max max display size log warn response else response res get response data as string return response getresponseasstring sampleresult sampleresult getdatatype settext getresponsedata max_display_size max_display_size jmeterutils getresstring view_results_response_too_large_message max_display_size getresponsedataasstring display the response as text or as rendered html change the text on the button appropriate to the current display param e the action event being processed public void action performed action event e command e get action command if command null command equals text command command equals html command command equals json command command equals xml command text mode command equals text command default mutable tree node node default mutable tree node j tree get last selected path component if node null results set text return sample result res sample result node get user object string response get response as string res if command equals text command show text response response else if command equals html command show rendered response response res else if command equals json command show renderjson response response else if command equals xml command show renderxml response res actionevent actionperformed actionevent getactioncommand text_command html_command json_command xml_command textmode text_command defaultmutabletreenode defaultmutabletreenode jtree getlastselectedpathcomponent settext sampleresult sampleresult getuserobject getresponseasstring text_command showtextresponse html_command showrenderedresponse json_command showrenderjsonresponse xml_command showrenderxmlresponse private void show rendered response string response sample result res if response null results set text return int html index response index of html could be html lang non nls 1 look for a case variation if html index 0 html index response index of html ditto non nls 1 if we still can t find it just try using all of the text if html index 0 html index 0 string html response substring html index to disable downloading and rendering of images and frames enable the editor kit the stream property can then be must be done before set content type results set editor kit for content type text html download all is selected default html editor customised editor results set content type text html if download all is selected allow j meter to render frames and relative images must be done after set content type why results get document put property document stream description property res geturl get round problems parsing meta http equiv content type content text html charset utf 8 see http issues apache org bugzilla show bug cgi id 23315 is this due to a bug in java results get document put property ignore charset directive boolean true non nls 1 results set text html results set caret position 0 results scroll pane set viewport view results text button set enabled true html button set enabled true json button set enabled true xml button set enabled true showrenderedresponse sampleresult settext htmlindex indexof htmlindex htmlindex indexof htmlindex htmlindex htmlindex setcontenttype seteditorkitforcontenttype text_html downloadall isselected defaulthtmleditor customisededitor setcontenttype text_html downloadall isselected jmeter setcontenttype getdocument putproperty streamdescriptionproperty show_bug getdocument putproperty ignorecharsetdirective settext setcaretposition resultsscrollpane setviewportview textbutton setenabled htmlbutton setenabled jsonbutton setenabled xmlbutton setenabled private component create html or text pane button group group new button group text button new j radio button j meter utils get res string view results render text non nls 1 text button set action command text command text button add action listener this text button set selected text mode group add text button html button new j radio button j meter utils get res string view results render html non nls 1 html button set action command html command html button add action listener this html button set selected text mode group add html button json button new j radio button j meter utils get res string view results render json non nls 1 json button set action command json command json button add action listener this json button set selected text mode group add json button xml button new j radio button j meter utils get res string view results render xml non nls 1 xml button set action command xml command xml button add action listener this xml button set selected text mode group add xml button download all new j check box j meter utils get res string view results render embedded non nls 1 j panel pane new j panel pane add text button pane add html button pane add xml button pane add json button pane add download all return pane createhtmlortextpane buttongroup buttongroup textbutton jradiobutton jmeterutils getresstring view_results_render_text textbutton setactioncommand text_command textbutton addactionlistener textbutton setselected textmode textbutton htmlbutton jradiobutton jmeterutils getresstring view_results_render_html htmlbutton setactioncommand html_command htmlbutton addactionlistener htmlbutton setselected textmode htmlbutton jsonbutton jradiobutton jmeterutils getresstring view_results_render_json jsonbutton setactioncommand json_command jsonbutton addactionlistener jsonbutton setselected textmode jsonbutton xmlbutton jradiobutton jmeterutils getresstring view_results_render_xml xmlbutton setactioncommand xml_command xmlbutton addactionlistener xmlbutton setselected textmode xmlbutton downloadall jcheckbox jmeterutils getresstring view_results_render_embedded jpanel jpanel textbutton htmlbutton xmlbutton jsonbutton downloadall initialize this visualizer private void init set layout new border layout 0 5 set border make border add make title panel border layout north component left side create left panel right side new j tabbed pane add the common tab right side add tab j meter utils get res string view results tab sampler create response metadata panel non nls 1 create the panels for the other tabs request pane create request panel results pane create response data panel j split pane main split new j split pane j split pane horizontal split left side right side add main split border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout leftside createleftpanel rightside jtabbedpane rightside addtab jmeterutils getresstring view_results_tab_sampler createresponsemetadatapanel requestpane createrequestpanel resultspane createresponsedatapanel jsplitpane mainsplit jsplitpane jsplitpane horizontal_split leftside rightside mainsplit borderlayout private void setup tab pane for sample result set the title for the first tab right side set title at 0 j meter utils get res string view results tab sampler non nls 1 add the other tabs if not present if right side index of tab j meter utils get res string view results tab request 0 non nls 1 right side add tab j meter utils get res string view results tab request request pane non nls 1 if right side index of tab j meter utils get res string view results tab response 0 non nls 1 right side add tab j meter utils get res string view results tab response results pane non nls 1 setuptabpaneforsampleresult rightside settitleat jmeterutils getresstring view_results_tab_sampler rightside indexoftab jmeterutils getresstring view_results_tab_request rightside addtab jmeterutils getresstring view_results_tab_request requestpane rightside indexoftab jmeterutils getresstring view_results_tab_response rightside addtab jmeterutils getresstring view_results_tab_response resultspane private void setup tab pane for assertion result set the title for the first tab right side set title at 0 j meter utils get res string view results tab assertion non nls 1 remove the other tabs if present int request tab index right side index of tab j meter utils get res string view results tab request non nls 1 if request tab index 0 right side remove tab at request tab index int response tab index right side index of tab j meter utils get res string view results tab response non nls 1 if response tab index 0 right side remove tab at response tab index setuptabpaneforassertionresult rightside settitleat jmeterutils getresstring view_results_tab_assertion requesttabindex rightside indexoftab jmeterutils getresstring view_results_tab_request requesttabindex rightside removetabat requesttabindex responsetabindex rightside indexoftab jmeterutils getresstring view_results_tab_response responsetabindex rightside removetabat responsetabindex private component create left panel sample result root sample result new sample result root sample result set sample label root root sample result set successful true root new default mutable tree node root sample result tree model new default tree model root j tree new j tree tree model j tree set cell renderer new results node renderer j tree get selection model set selection mode tree selection model single tree selection j tree add tree selection listener this j tree set root visible false j tree set shows root handles true j scroll pane tree pane new j scroll pane j tree tree pane set preferred size new dimension 200 300 return tree pane createleftpanel sampleresult rootsampleresult sampleresult rootsampleresult setsamplelabel rootsampleresult setsuccessful defaultmutabletreenode rootsampleresult treemodel defaulttreemodel jtree jtree treemodel jtree setcellrenderer resultsnoderenderer jtree getselectionmodel setselectionmode treeselectionmodel single_tree_selection jtree addtreeselectionlistener jtree setrootvisible jtree setshowsroothandles jscrollpane treepane jscrollpane jtree treepane setpreferredsize treepane private component create response metadata panel stats new j text pane stats set editable false stats set background get background add styles to use for different types of status messages styled document doc styled document stats get document style style doc add style style redirect null style constants set foreground style redirect color style doc add style style client error null style constants set foreground style client error color style doc add style style server error null style constants set foreground style server error color j scroll pane pane make scroll pane stats pane set border border factory create empty border 2 2 2 2 return pane createresponsemetadatapanel jtextpane seteditable setbackground getbackground styleddocument styleddocument getdocument addstyle style_redirect styleconstants setforeground redirect_color addstyle style_client_error styleconstants setforeground client_error_color addstyle style_server_error styleconstants setforeground server_error_color jscrollpane makescrollpane setborder borderfactory createemptyborder private j panel create request panel sample data field new j text area sample data field set editable false sample data field set line wrap true sample data field set wrap style word true j panel pane new j panel new border layout 0 5 pane add make scroll pane sample data field return pane jpanel createrequestpanel sampledatafield jtextarea sampledatafield seteditable sampledatafield setlinewrap sampledatafield setwrapstyleword jpanel jpanel borderlayout makescrollpane sampledatafield private j panel create response data panel results new j editor pane results set editable false results scroll pane make scroll pane results image label new j label j panel panel new j panel new border layout panel add results scroll pane border layout center panel add create html or text pane border layout south return panel jpanel createresponsedatapanel jeditorpane seteditable resultsscrollpane makescrollpane imagelabel jlabel jpanel jpanel borderlayout resultsscrollpane borderlayout createhtmlortextpane borderlayout private static class results node renderer extends default tree cell renderer public component get tree cell renderer component j tree tree object value boolean sel boolean expanded boolean leaf int row boolean focus super get tree cell renderer component tree value sel expanded leaf row focus boolean failure true object user object default mutable tree node value get user object if user object instanceof sample result failure sample result user object is successful else if user object instanceof assertion result assertion result assertion assertion result user object failure assertion is error assertion is failure set the status for the node if failure this set foreground color red this set icon image failure else this set icon image success return this resultsnoderenderer defaulttreecellrenderer gettreecellrenderercomponent jtree gettreecellrenderercomponent userobject defaultmutabletreenode getuserobject userobject sampleresult sampleresult userobject issuccessful userobject assertionresult assertionresult assertionresult userobject iserror isfailure setforeground seticon imagefailure seticon imagesuccess private static final view factory default factory new localhtml factory public view factory get view factory return default factory viewfactory defaultfactory localhtmlfactory viewfactory getviewfactory defaultfactory public view create element elem object o elem get attributes get attribute style constants name attribute if o instanceof html tag html tag kind html tag o if kind html tag frame return new component view elem else if kind html tag img return new component view elem return super create elem getattributes getattribute styleconstants nameattribute componentview componentview public dom tree panel org w3c dom document document super new grid layout 1 0 try node first element get first element document default mutable tree node top new xml default mutable tree node first element domj tree new j tree top domj tree get selection model set selection mode tree selection model single tree selection domj tree set shows root handles true j scroll pane domj scroll pane new j scroll pane domj tree domj tree set autoscrolls true this add domj scroll pane tool tip manager shared instance register component domj tree domj tree set cell renderer new dom tree renderer catch sax exception e log warn e domtreepanel gridlayout firstelement getfirstelement defaultmutabletreenode xmldefaultmutabletreenode firstelement domjtree jtree domjtree getselectionmodel setselectionmode treeselectionmodel single_tree_selection domjtree setshowsroothandles jscrollpane domjscrollpane jscrollpane domjtree domjtree setautoscrolls domjscrollpane tooltipmanager sharedinstance registercomponent domjtree domjtree setcellrenderer domtreerenderer saxexception skip all dtd nodes all prolog nodes they dont support in tree view we let user to insert them however in dom tree view we dont display it param root return private node get first element node parent node list child nodes parent get child nodes node to return parent must return a valid node or may generate an npe for int i 0 i child nodes get length i node child node child nodes item i to return child node if child node get node type node element node break return to return domtreeview getfirstelement nodelist childnodes getchildnodes toreturn childnodes getlength childnode childnodes toreturn childnode childnode getnodetype element_node toreturn private static class dom tree renderer extends default tree cell renderer public component get tree cell renderer component j tree tree object value boolean sel boolean expanded boolean leaf int row boolean phas focus super get tree cell renderer component tree value sel expanded leaf row phas focus default mutable tree node value tree node default mutable tree node value set tool tip text gethtml value tree node to string br 100 non nls 1 return this domtreerenderer defaulttreecellrenderer gettreecellrenderercomponent jtree phasfocus gettreecellrenderercomponent phasfocus defaultmutabletreenode valuetreenode defaultmutabletreenode settooltiptext valuetreenode tostring get the html param str param separator param max char return private string gethtml string str string separator int max char string buffer str buf new string buffer html body bgcolor yellow b non nls 1 char chars str to char array for int i 0 i chars length i if i max char 0 i 0 str buf append separator str buf append encode chars i str buf append b body html non nls 1 return str buf to string maxchar maxchar stringbuffer strbuf stringbuffer tochararray maxchar strbuf strbuf strbuf strbuf tostring private string encode char c string to return string value of c switch c case non nls 1 to return lt non nls 1 break case non nls 1 to return gt non nls 1 break case non nls 1 to return apos non nls 1 break case non nls 1 to return quot non nls 1 break return to return toreturn valueof toreturn toreturn toreturn toreturn toreturn private static void show error message dialog string message string title int message type j option pane show message dialog null message title message type showerrormessagedialog messagetype joptionpane showmessagedialog messagetype constructor for the remove object public report remove reportremove gets the action names attribute of the remove object return the action names value public set get action names return commands actionnames actionnames getactionnames public void do action action event e report action router get instance action performed new action event e get source e getid report check dirty remove report gui package gui package report gui package get instance report tree node nodes gui package get tree listener get selected nodes tree path new tree path save parent node for later gui package get tree listener removed selected node for int i nodes length 1 i 0 i remove node nodes i gui package get tree listener getj tree set selection path new tree path gui package update current gui doaction actionevent reportactionrouter getinstance actionperformed actionevent getsource reportcheckdirty reportguipackage guipackage reportguipackage getinstance reporttreenode guipackage gettreelistener getselectednodes treepath newtreepath guipackage gettreelistener removedselectednode removenode guipackage gettreelistener getjtree setselectionpath newtreepath guipackage updatecurrentgui public static void remove node report tree node node test element test element node get test element if test element can remove report gui package get instance get tree model remove node from parent node report gui package get instance remove node test element else string message test element get class get name is busy j option pane show message dialog null message cannot remove item j option pane error message removenode reporttreenode testelement testelement gettestelement testelement canremove reportguipackage getinstance gettreemodel removenodefromparent reportguipackage getinstance removenode testelement testelement getclass getname joptionpane showmessagedialog joptionpane error_message public class report tree model extends default tree model public report tree model super new report tree node new report gui create test element null init tree reporttreemodel defaulttreemodel reporttreemodel reporttreenode reportgui createtestelement inittree returns a list of tree nodes that hold objects of the given class type if none are found an empty list is returned public list get nodes of type class type list node list new linked list traverse and find type report tree node this get root node list return node list getnodesoftype nodelist linkedlist traverseandfind reporttreenode getroot nodelist nodelist get the node for a given test element object public report tree node get node of test element user object return traverse and find user object report tree node get root testelement reporttreenode getnodeof testelement userobject traverseandfind userobject reporttreenode getroot adds the sub tree at the given node returns a boolean indicating whether the added sub tree was a full test plan public hash tree add sub tree hash tree sub tree report tree node current throws illegal user action exception iterator iter sub tree list iterator while iter has next test element item test element iter next if item instanceof report plan current report tree node report tree node get root get child at 0 test element current get user object add test element item report plan current get user object set name item get name add sub tree sub tree get tree item current else if sub tree get tree item null add sub tree sub tree get tree item add component item current return get current sub tree current hashtree addsubtree hashtree subtree reporttreenode illegaluseractionexception subtree hasnext testelement testelement reportplan reporttreenode reporttreenode getroot getchildat testelement getuserobject addtestelement reportplan getuserobject setname getname addsubtree subtree gettree subtree gettree addsubtree subtree gettree addcomponent getcurrentsubtree public report tree node add component test element component report tree node node throws illegal user action exception if node get user object instanceof abstract config gui throw new illegal user action exception this node cannot hold sub elements component set property test element gui class name updater get current name component get property as string test element gui class report gui package get instance update current node j metergui component guicomp report gui package get instance get gui component guicomp configure component guicomp modify test element component report gui package get instance get current gui put the gui object back to the way it was report tree node new node new report tree node component this this check the state of the test element and if returns false it disable the loaded node try if component get property test element enabled instanceof null property component get property as boolean test element enabled new node set enabled true else new node set enabled false catch exception e new node set enabled true this insert node into new node node node get child count return new node reporttreenode addcomponent testelement reporttreenode illegaluseractionexception getuserobject abstractconfiggui illegaluseractionexception setproperty testelement gui_class nameupdater getcurrentname getpropertyasstring testelement gui_class reportguipackage getinstance updatecurrentnode jmeterguicomponent reportguipackage getinstance getgui modifytestelement reportguipackage getinstance getcurrentgui reporttreenode newnode reporttreenode testelement getproperty testelement nullproperty getpropertyasboolean testelement newnode setenabled newnode setenabled newnode setenabled insertnodeinto newnode getchildcount newnode public void remove node from parent report tree node node if node get user object instanceof report plan super remove node from parent node removenodefromparent reporttreenode getuserobject reportplan removenodefromparent private void traverse and find class type report tree node node list node list if type is instance node get user object node list add node enumeration enum node node children while enum node has more elements report tree node child report tree node enum node next element traverse and find type child node list traverseandfind reporttreenode nodelist isinstance getuserobject nodelist enumnode enumnode hasmoreelements reporttreenode reporttreenode enumnode nextelement traverseandfind nodelist private report tree node traverse and find test element user object report tree node node if user object node get user object return node enumeration enum node node children while enum node has more elements report tree node child report tree node enum node next element report tree node result traverse and find user object child if result null return result return null reporttreenode traverseandfind testelement userobject reporttreenode userobject getuserobject enumnode enumnode hasmoreelements reporttreenode reporttreenode enumnode nextelement reporttreenode traverseandfind userobject public hash tree get current sub tree report tree node node listed hash tree hash tree new listed hash tree node enumeration enum node node children while enum node has more elements report tree node child report tree node enum node next element hash tree add node get current sub tree child return hash tree hashtree getcurrentsubtree reporttreenode listedhashtree hashtree listedhashtree enumnode enumnode hasmoreelements reporttreenode reporttreenode enumnode nextelement hashtree getcurrentsubtree hashtree public hash tree get report plan return get current sub tree report tree node report tree node this get root get child at 0 hashtree getreportplan getcurrentsubtree reporttreenode reporttreenode getroot getchildat public void clear test plan super remove node from parent report tree node get child get root 0 init tree cleartestplan removenodefromparent reporttreenode getchild getroot inittree private void init tree test element rp new report gui create test element this insert node into new report tree node rp this report tree node get root 0 inittree testelement reportgui createtestelement insertnodeinto reporttreenode reporttreenode getroot default constructor the label and the text field are left empty public j labeled text field this 20 jlabeledtextfield constructs a new component with the label displaying the passed text param p label the text to in the label public j labeled text field string p label this p label 20 plabel jlabeledtextfield plabel plabel public j labeled text field string p label int size super m text field create text field size m label new j label p label m label set label for m text field init jlabeledtextfield plabel mtextfield createtextfield mlabel jlabel plabel mlabel setlabelfor mtextfield public j labeled text field string p label color bk super m text field create text field 20 m label new j label p label m label set background bk m label set label for m text field this set background bk init jlabeledtextfield plabel mtextfield createtextfield mlabel jlabel plabel mlabel setbackground mlabel setlabelfor mtextfield setbackground public list get component list list comps new linked list comps add m label comps add m text field return comps getcomponentlist linkedlist mlabel mtextfield public void set enabled boolean enable super set enabled enable m text field set enabled enable setenabled setenabled mtextfield setenabled protected j text field create text field int size return new j text field size jtextfield createtextfield jtextfield initialises all of the components on this panel private void init set layout new border layout 5 0 register the handler for focus listening this handler will only notify the registered when the text changes from when the focus is gained to when it is lost m text field add focus listener this add the sub components add m label border layout west add m text field border layout center setlayout borderlayout mtextfield addfocuslistener mlabel borderlayout mtextfield borderlayout callback method when the focus to the text field component is lost param p focus event the focus event that occured public void focus lost focus event p focus event compare if the value has changed since we received focus if old value equals m text field get text notify change listeners pfocusevent focuslost focusevent pfocusevent oldvalue mtextfield gettext notifychangelisteners catch what the value was when focus was gained public void focus gained focus event p focus event old value m text field get text focusgained focusevent pfocusevent oldvalue mtextfield gettext set the text displayed in the label param p label the new label text public void set label string p label m label set text p label plabel setlabel plabel mlabel settext plabel set the text displayed in the text field param p text the new text to display in the text field public void set text string p text m text field set text p text ptext settext ptext mtextfield settext ptext returns the text in the text field return the text in the text field public string get text return m text field get text gettext mtextfield gettext returns the text of the label return the text of the label public string get label return m label get text getlabel mlabel gettext registers the text to display in a tool tip the text displays when the cursor lingers over the component param text the string to display if the text is null the tool tip is turned off for this component public void set tool tip text string text m text field set tool tip text text settooltiptext mtextfield settooltiptext returns the tooltip string that has been set with set tool tip text return the text of the tool tip public string get tool tip text if m text field null necessary to avoid npe when testing serialisation return null return m text field get tool tip text settooltiptext gettooltiptext mtextfield mtextfield gettooltiptext adds a change listener that will be notified when the text in the text field is changed the change event that will be passed to registered listeners will contain this object as the source allowing the new text to be extracted using the link get text get text method param p change listener the listener to add public void add change listener change listener p change listener m change listeners add p change listener changeevent gettext gettext pchangelistener addchangelistener changelistener pchangelistener mchangelisteners pchangelistener removes a change listener param p change listener the change listener to remove public void remove change listener change listener p change listener m change listeners remove p change listener pchangelistener removechangelistener changelistener pchangelistener mchangelisteners pchangelistener notify all registered change listeners that the text in the text field has changed protected void notify change listeners change event ce new change event this for int index 0 index m change listeners size index change listener m change listeners get index state changed ce notifychangelisteners changeevent changeevent mchangelisteners changelistener mchangelisteners statechanged get access to buffer static class loopback output stream extends byte array output stream byte get buffer return buf loopbackoutputstream bytearrayoutputstream getbuffer loopback output stream os public synchronized int read buf os get buffer make sure buffer details count buf length track the output return super read loopbackoutputstream getbuffer public synchronized int read byte b int off int len buf os get buffer count buf length return super read b off len getbuffer public loop back input stream loopback output stream os super os get buffer os os loopbackinputstream loopbackoutputstream _os _os getbuffer _os private loopbackhttp socket throws io exception os new loopback output stream preload the output so that can be read back as http os write http 1 1 200 ok r n content type text plain r n r n get bytes loopbackhttpsocket ioexception loopbackoutputstream ncontent getbytes public loopbackhttp socket string host int port inet address local address int local port int timeout throws io exception this loopbackhttpsocket inetaddress localaddress localport ioexception public loopbackhttp socket string host int port inet address local addr int local port throws io exception this loopbackhttpsocket inetaddress localaddr localport ioexception public loopbackhttp socket string host int port throws unknown host exception io exception this loopbackhttpsocket unknownhostexception ioexception override so we can intercept the stream public output stream get output stream throws io exception return os outputstream getoutputstream ioexception override so we can intercept the stream public input stream get input stream throws io exception return new loop back input stream os inputstream getinputstream ioexception loopbackinputstream public j labeled radio super this add m label jlabeledradio mlabel public j labeled radio string label string items m label set text label init items null jlabeledradio mlabel settext public j labeled radio string label string items string selected item m label set text label init items selected item jlabeledradio selecteditem mlabel settext selecteditem method is responsible for creating the j radio buttons and adding them to the button group param items private void init string items string selected this add m label for int idx 0 idx items length idx j radio button btn new j radio button items idx btn set action command items idx btn add action listener this add the button to the button group this b group add btn add the button this add btn if selected null selected equals items idx btn set selected true jradiobuttons buttongroup mlabel jradiobutton jradiobutton setactioncommand addactionlistener bgroup setselected set items will set the radio button items the implementation first removes the old j radio button then it creates new ones param items public void set items string items enumeration en this b group get elements while en has more elements j component comp j component en next element this b group remove j radio button comp this remove comp init items null setitems jradiobutton setitems bgroup getelements hasmoreelements jcomponent jcomponent nextelement bgroup jradiobutton the implementation will get the text value from the selected radio button in the j button group public string get text return this b group get selection get action command jbuttongroup gettext bgroup getselection getactioncommand the implementation will iterate through the radio buttons and find the match it then sets it to selected and sets all other radion buttons as not selected public void set text string text enumeration en this b group get elements while en has more elements j radio button jrb j radio button en next element if jrb get text equals text this b group set selected jrb get model true else this b group set selected jrb get model false settext bgroup getelements hasmoreelements jradiobutton jradiobutton nextelement gettext bgroup setselected getmodel bgroup setselected getmodel see org apache jorphan gui j labeled field set label java lang string public void set label string p label this m label set text p label jlabeledfield setlabel setlabel plabel mlabel settext plabel see org apache jorphan gui j labeled field add change listener javax swing event change listener public void add change listener change listener p change listener this m change listeners add p change listener jlabeledfield addchangelistener changelistener addchangelistener changelistener pchangelistener mchangelisteners pchangelistener notify all registered change listeners that the text in the text field has changed private void notify change listeners change event ce new change event this for int index 0 index m change listeners size index change listener m change listeners get index state changed ce notifychangelisteners changeevent changeevent mchangelisteners changelistener mchangelisteners statechanged method will return all the label and j radio buttons button group is excluded from the list public list get component list list comps new linked list comps add m label enumeration en this b group get elements while en has more elements comps add en next element return comps jradiobuttons buttongroup getcomponentlist linkedlist mlabel bgroup getelements hasmoreelements nextelement when a radio button is clicked an action event is triggered public void action performed action event e this notify change listeners actionevent actionperformed actionevent notifychangelisteners for int a 0 a lib dirs length a file lib jars lib dirs a list files new filename filter public boolean accept file dir string name only accept jar files return name ends with jar non nls 1 libdirs libjars libdirs listfiles filenamefilter endswith prevent instantiation private new driver newdriver add a url to the loader classpath only does not update the system classpath param path to be added public static void addurl string path file furl new file path try loader addurl furl touri tourl see java bug 4496398 catch malformedurl exception e e print stack trace malformedurlexception printstacktrace add a url to the loader classpath only does not update the system classpath param url public static void addurl url url loader addurl url add a directory or jar to the loader and system classpaths param path to add to the loader and system classpath throws malformedurl exception public static void add path string path throws malformedurl exception file file new file path ensure that directory ur ls end in if file is directory path ends with non nls 1 file new file path non nls 1 loader addurl file touri tourl see java bug 4496398 string buffer sb new string buffer system get property java class path sb append classpath separator sb append path class finder needs this system set property java class path sb to string malformedurlexception addpath malformedurlexception urls isdirectory endswith stringbuffer stringbuffer getproperty java_class_path classpath_separator classfinder setproperty java_class_path tostring get the directory where j meter is installed this is the absolute path name return the directory where j meter is installed public static string getj meter dir return jm dir jmeter jmeter getjmeterdir jmdir the main program which actually runs j meter param args the command line arguments public static void main string args thread current thread set context class loader loader if system get property log4j configuration null non nls 1 non nls 2 file conf new file jm dir bin file separator log4j conf non nls 1 non nls 2 system set property log4j configuration file conf try class initial class if args null args length 0 args 0 equals report non nls 1 initial class loader load class org apache jmeter j meter report non nls 1 else initial class loader load class org apache jmeter j meter non nls 1 object instance initial class new instance method startup initial class get method start new class new string 0 get class non nls 1 startup invoke instance new object args catch throwable e e print stack trace system err println j meter home directory was detected as jm dir jmeter currentthread setcontextclassloader getproperty jmdir setproperty initialclass initialclass loadclass jmeterreport initialclass loadclass jmeter initialclass newinstance initialclass getmethod getclass printstacktrace jmeter jmdir see org apache jmeter gui action command do action action event public void do action action event e if help window null help window new j dialog new frame independent frame to allow it to be overlaid by the main frame j meter utils get res string help non nls 1 false help window get content pane set layout new grid layout 1 1 component util center component in window help window 60 help window get content pane remove all help window get content pane add scroller help window show if e get source instanceof string string source string e get source reset page source 0 help doc scroll to reference source 1 else reset page help page help doc scroll to reference report gui package get instance get tree listener get current node get doc anchor doaction actionevent doaction actionevent helpwindow helpwindow jdialog jmeterutils getresstring helpwindow getcontentpane setlayout gridlayout componentutil centercomponentinwindow helpwindow helpwindow getcontentpane removeall helpwindow getcontentpane helpwindow getsource getsource resetpage helpdoc scrolltoreference resetpage help_page helpdoc scrolltoreference reportguipackage getinstance gettreelistener getcurrentnode getdocanchor private void reset page string source if current page equals source try help doc set page source current page source catch io exception err log error err to string j meter utils report error to user problem loading a help page see log for details current page resetpage currentpage helpdoc setpage currentpage ioexception tostring jmeterutils reporterrortouser currentpage see org apache jmeter gui action command get action names public set get action names return commands getactionnames getactionnames public void warning sax parse exception exception throws sax exception log warn parsing warning n line exception get line number n uri exception get system id n message exception get message throw new sax exception warning encountered saxparseexception saxexception getlinenumber getsystemid getmessage saxexception public void error sax parse exception exception throws sax exception log error parsing warning n line exception get line number n uri exception get system id n message exception get message throw new sax exception error encountered saxparseexception saxexception getlinenumber getsystemid getmessage saxexception public void fatal error sax parse exception exception throws sax exception log error parsing warning n line exception get line number n uri exception get system id n message exception get message throw new sax exception fatal error encountered fatalerror saxparseexception saxexception getlinenumber getsystemid getmessage saxexception constructor for j unit test sampler gui public j unit test sampler gui super init junittestsamplergui junittestsamplergui public string get label resource return junit request non nls 1 getlabelresource junit_request initialize the gui components and layout private void init set layout new border layout 0 5 set border make border add make title panel border layout north add create class panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout createclasspanel borderlayout private j panel create class panel methodlist new java util array list try find all the classes which extend junit framework test case classlist class finder find classes that extend spaths new class test case class catch io exception e log error exception getting interfaces e j label label new j label j meter utils get res string protocol java classname non nls 1 classname combo new j combo box classlist to array classname combo add action listener this classname combo set name classnamecombo classname combo set editable false label set label for classname combo if filter null filter size 0 method name new j combo box filter filter array methodlist else method name new j combo box methodlist to array method name add action listener this method name set name methodcombo method label set label for method name vertical panel panel new vertical panel panel add filterpkg panel add label filterpkg add change listener this if classname combo null panel add classname combo constructor label set text panel add constructor label panel add method label if method name null panel add method name panel add success msg panel add success code panel add failure msg panel add failure code panel add error msg panel add error code panel add do setup panel add append error panel add append exc return panel jpanel createclasspanel arraylist testcase classfinder findclassesthatextend testcase ioexception jlabel jlabel jmeterutils getresstring protocol_java_classname classnamecombo jcombobox toarray classnamecombo addactionlistener classnamecombo setname classnamecombo seteditable setlabelfor classnamecombo methodname jcombobox filterarray methodname jcombobox toarray methodname addactionlistener methodname setname methodlabel setlabelfor methodname verticalpanel verticalpanel addchangelistener classnamecombo classnamecombo constructorlabel settext constructorlabel methodlabel methodname methodname successmsg successcode failuremsg failurecode errormsg errorcode dosetup appenderror appendexc private void init gui todo unfinished append error set selected false append exc set selected false do setup set selected false filterpkg set text non nls 1 constructor label set text non nls 1 success code set text j meter utils get res string junit success default code non nls 1 success msg set text j meter utils get res string junit success default msg non nls 1 failure code set text j meter utils get res string junit failure default code non nls 1 failure msg set text j meter utils get res string junit failure default msg non nls 1 error msg set text j meter utils get res string junit error default msg non nls 1 error code set text j meter utils get res string junit error default code non nls 1 initgui appenderror setselected appendexc setselected dosetup setselected settext constructorlabel settext successcode settext jmeterutils getresstring junit_success_default_code successmsg settext jmeterutils getresstring junit_success_default_msg failurecode settext jmeterutils getresstring junit_failure_default_code failuremsg settext jmeterutils getresstring junit_failure_default_msg errormsg settext jmeterutils getresstring junit_error_default_msg errorcode settext jmeterutils getresstring junit_error_default_code public void clear gui super clear gui init gui cleargui cleargui initgui implements j meter gui component create test element public test element create test element j unit sampler sampler new j unit sampler modify test element sampler return sampler jmeterguicomponent createtestelement testelement createtestelement junitsampler junitsampler modifytestelement implements j meter gui component modify test element test element public void modify test element test element el j unit sampler sampler j unit sampler el configure test element sampler if classname combo get selected item null classname combo get selected item instanceof string sampler set classname string classname combo get selected item sampler set constructor string constructor label get text if method name get selected item null object mobj method name get selected item sampler set method string mobj sampler set filter string filterpkg get text sampler set success success msg get text sampler set success code success code get text sampler set failure failure msg get text sampler set failure code failure code get text sampler set do not set up tear down do setup is selected sampler set append error append error is selected sampler set append exception append exc is selected jmeterguicomponent modifytestelement testelement modifytestelement testelement junitsampler junitsampler configuretestelement classnamecombo getselecteditem classnamecombo getselecteditem setclassname classnamecombo getselecteditem setconstructorstring constructorlabel gettext methodname getselecteditem methodname getselecteditem setmethod setfilterstring gettext setsuccess successmsg gettext setsuccesscode successcode gettext setfailure failuremsg gettext setfailurecode failurecode gettext setdonotsetupteardown dosetup isselected setappenderror appenderror isselected setappendexception appendexc isselected overrides abstractj meter gui component configure test element public void configure test element el super configure el j unit sampler sampler j unit sampler el classname combo set selected item sampler get classname instantiate class method name set selected item sampler get method filterpkg set text sampler get filter string constructor label set text sampler get constructor string if sampler get success code length 0 success code set text sampler get success code else success code set text j meter utils get res string junit success default code non nls 1 if sampler get success length 0 success msg set text sampler get success else success msg set text j meter utils get res string junit success default msg non nls 1 if sampler get failure code length 0 failure code set text sampler get failure code else failure code set text j meter utils get res string junit failure default code non nls 1 if sampler get failure length 0 failure msg set text sampler get failure else failure msg set text j meter utils get res string junit failure default msg non nls 1 if sampler get error length 0 error msg set text sampler get error else error msg set text j meter utils get res string junit error default msg non nls 1 if sampler get error code length 0 error code set text sampler get error code else error code set text j meter utils get res string junit error default code non nls 1 do setup set selected sampler get do not set up tear down append error set selected sampler get append error append exc set selected sampler get append exception abstractjmeterguicomponent testelement testelement junitsampler junitsampler classnamecombo setselecteditem getclassname instantiateclass methodname setselecteditem getmethod settext getfilterstring constructorlabel settext getconstructorstring getsuccesscode successcode settext getsuccesscode successcode settext jmeterutils getresstring junit_success_default_code getsuccess successmsg settext getsuccess successmsg settext jmeterutils getresstring junit_success_default_msg getfailurecode failurecode settext getfailurecode failurecode settext jmeterutils getresstring junit_failure_default_code getfailure failuremsg settext getfailure failuremsg settext jmeterutils getresstring junit_failure_default_msg geterror errormsg settext geterror errormsg settext jmeterutils getresstring junit_error_default_msg geterrorcode errorcode settext geterrorcode errorcode settext jmeterutils getresstring junit_error_default_code dosetup setselected getdonotsetupteardown appenderror setselected getappenderror appendexc setselected getappendexception public void instantiate class string class name string classname combo get selected item if class name null testclass test case j unit sampler get class instance class name constructor label get text if testclass null clear method combo configure method combo instantiateclass classname classnamecombo getselecteditem classname testcase junitsampler getclassinstance classname constructorlabel gettext clearmethodcombo configuremethodcombo public void show error dialog j option pane show confirm dialog this j meter utils get res string junit constructor error non nls 1 warning j option pane ok cancel option j option pane error message showerrordialog joptionpane showconfirmdialog jmeterutils getresstring junit_constructor_error joptionpane ok_cancel_option joptionpane error_message public void configure method combo if testclass null clear method combo string names get method names get methods testclass methodlist for int idx 0 idx names length idx method name add item names idx methodlist add names idx method name repaint configuremethodcombo clearmethodcombo getmethodnames getmethods methodname additem methodname public void clear method combo method name remove all items methodlist clear clearmethodcombo methodname removeallitems public method get methods object obj list list method meths obj get class get methods for int idx 0 idx meths length idx if meths idx get name starts with prefix meths idx get name equals onetimesetup meths idx get name equals onetimeteardown meths idx get name equals suite list add meths idx if list size 0 method rmeth new method list size return method list to array rmeth return new method 0 getmethods getclass getmethods getname startswith getname getname getname toarray public string get method names method meths string names new string meths length for int idx 0 idx meths length idx names idx meths idx get name return names getmethodnames getname public class filter classes class clz if clz null clz length 0 class nclz null return nclz return clz filterclasses handle action events for this component this method currently handles events for the classname combo box param evt the action event to be handled public void action performed action event evt if evt get source classname combo instantiate class actionevent actionperformed actionevent getsource classnamecombo instantiateclass the current implementation checks to see if the source of the event is the filterpkg field public void state changed change event event if event get source filterpkg filter set packges j orphan utils split filterpkg get text non nls 1 classname combo remove all items change the classname drop down object clist filter filter array classlist for int idx 0 idx clist length idx classname combo add item clist idx statechanged changeevent getsource setpackges jorphanutils gettext classnamecombo removeallitems filterarray classnamecombo additem no arg constructor see java lang object object public module controller super modulecontroller public object clone module controller clone module controller super clone if selected node null this restore selected clone selected node selected node todo j meter tree node selected node clone return clone modulecontroller modulecontroller selectednode restoreselected selectednode selectednode jmetertreenode selectednode sets the link j meter tree node which represents the controller which this object is pointing to used for building the test case upon execution param tn j meter tree node see org apache jmeter gui tree j meter tree node public void set selected node j meter tree node tn selected node tn set node path jmetertreenode jmetertreenode jmetertreenode setselectednode jmetertreenode selectednode setnodepath gets the link j meter tree node for the controller return j meter tree node public j meter tree node get selected node if selected node null restore selected return selected node jmetertreenode jmetertreenode jmetertreenode getselectednode selectednode restoreselected selectednode private void set node path list node path new array list if selected node null tree node path selected node get path for int i 0 i path length i node path add j meter tree node path i get name node path add selected node get name set property new collection property node path node path setnodepath nodepath arraylist selectednode treenode selectednode getpath nodepath jmetertreenode getname nodepath selectednode getname setproperty collectionproperty node_path nodepath public list get node path j meter property prop get property node path if prop instanceof null property return list collection property prop get object value return null getnodepath jmeterproperty getproperty node_path nullproperty collectionproperty getobjectvalue private void restore selected gui package gp gui package get instance if gp null j meter tree node root j meter tree node gp get tree model get root resolve replacement sub tree root restoreselected guipackage guipackage getinstance jmetertreenode jmetertreenode gettreemodel getroot resolvereplacementsubtree compute the replacement tree param context public void resolve replacement sub tree j meter tree node context if selected node null list node path list get node path if node path list null node path list size 0 traverse context node path list 1 resolvereplacementsubtree jmetertreenode selectednode nodepathlist getnodepath nodepathlist nodepathlist nodepathlist private void traverse j meter tree node node list node path int level if node null node path size level for int i 0 i node get child count i j meter tree node cur j meter tree node node get child at i if cur get name equals node path get level to string if node path size level 1 selected node cur traverse cur node path level 1 jmetertreenode nodepath nodepath getchildcount jmetertreenode jmetertreenode getchildat getname nodepath tostring nodepath selectednode nodepath copies the controller s subelements into the execution tree public hash tree get replacement sub tree hash tree tree new listed hash tree if selected node null if selected node is enabled selected node clone tree node selected node selected node set enabled true tree add selected node create sub tree tree selected node return tree hashtree getreplacementsubtree hashtree listedhashtree selectednode selectednode isenabled selectednode clonetreenode selectednode selectednode setenabled selectednode createsubtree selectednode private void create sub tree hash tree tree j meter tree node node enumeration e node children while e has more elements j meter tree node sub node j meter tree node e next element tree add sub node create sub tree tree get tree sub node sub node createsubtree hashtree jmetertreenode hasmoreelements jmetertreenode subnode jmetertreenode nextelement subnode createsubtree gettree subnode subnode private static j meter tree node clone tree node j meter tree node node j meter tree node tree node j meter tree node node clone tree node set user object test element node get user object clone clone children tree node node return tree node jmetertreenode clonetreenode jmetertreenode jmetertreenode treenode jmetertreenode treenode setuserobject testelement getuserobject clonechildren treenode treenode private static void clone children j meter tree node to j meter tree node from enumeration enumr from children while enumr has more elements j meter tree node child j meter tree node enumr next element j meter tree node child clone j meter tree node child clone child clone set user object test element child get user object clone to add child clone clone children j meter tree node to get last child child clonechildren jmetertreenode jmetertreenode hasmoreelements jmetertreenode jmetertreenode nextelement jmetertreenode childclone jmetertreenode childclone setuserobject testelement getuserobject childclone clonechildren jmetertreenode getlastchild needed for serialization tests deprecated only for use in unit testing public monitor graph log warn only for use in unit testing model null monitorgraph public monitor graph monitor accum model model this model model repaint monitorgraph monitoraccummodel public void set health boolean health this draw health health sethealth drawhealth public void set load boolean load this draw load load setload drawload public void set mem boolean mem this draw memory mem setmem drawmemory public void set thread boolean thread this draw thread thread setthread drawthread the method will first check to see if the graph is visible if it is it will repaint the graph public void update gui final monitor model model if this is showing this current model repaint updategui monitormodel isshowing pain component is responsible for drawing the actual graph this is because of how screen works tried to use clipping but i don t understand it well enough to get the desired effect public void paint component graphics g super paint component g if this current null synchronized model list samples model get all samples this current geturl int size samples size synchronized samples iterator e if size get width e samples list iterator size get width else e samples iterator monitor model last null for int i 0 e has next i monitor model s monitor model e next if last null last s draw sample i s g last last s paincomponent paintcomponent paintcomponent getallsamples getwidth listiterator getwidth monitormodel hasnext monitormodel monitormodel drawsample update gui will call repaint public void update gui repaint updategui updategui clear will repaint the graph public void clear data paint component get graphics this repaint cleardata paintcomponent getgraphics private void draw sample int x monitor model model graphics g monitor model last double width get width double height get height 10 0 int xaxis int width x width int lastx int width x 1 width draw grid only when x is 1 if we didn t the grid line would draw over the data lines making it look bad if draw ygrid x 1 int q1 int height 0 25 int q2 int height 0 50 int q3 int height 0 75 g set color color light gray g draw line 0 q1 get width q1 g draw line 0 q2 get width q2 g draw line 0 q3 get width q3 if draw xgrid x 1 int x1 int width 0 25 int x2 int width 0 50 int x3 int width 0 75 g draw line x1 0 x1 get height g draw line x2 0 x2 get height g draw line x3 0 x3 get height g draw line get width 0 get width get height if draw health int hly int height height model get health 3 0 int lasty int height height last get health 3 0 g set color color green g draw line lastx lasty xaxis hly if draw load int ldy int height height model get load 100 0 int lastldy int height height last get load 100 0 g set color color blue g draw line lastx lastldy xaxis ldy if draw memory int mmy int height height model get memload 100 0 int lastmmy int height height last get memload 100 0 g set color color orange g draw line lastx lastmmy xaxis mmy if draw thread int thy int height height model get threadload 100 0 int lastthy int height height last get threadload 100 0 g set color color red g draw line lastx lastthy xaxis thy drawsample monitormodel monitormodel getwidth getheight drawygrid setcolor lightgray drawline getwidth drawline getwidth drawline getwidth drawxgrid drawline getheight drawline getheight drawline getheight drawline getwidth getwidth getheight drawhealth gethealth gethealth setcolor drawline drawload getload getload setcolor drawline drawmemory getmemload getmemload setcolor drawline drawthread getthreadload getthreadload setcolor drawline private static final boolean save out j meter utils get prop default testsaveservice saveout false public test save service string name super name saveout jmeterutils getpropdefault testsaveservice super name public void test propfile throws exception assert true property version mismatch save service check property version assert true property file version mismatch save service check file version testpropfile asserttrue saveservice checkpropertyversion asserttrue saveservice checkfileversion public void test versions throws exception assert true unexpected version found save service check versions testversions asserttrue saveservice checkversions public void test load and save throws exception byte original new byte 1000000 boolean failed false did a test fail for int i 0 i files length i input stream in new file input stream new file testfiles files i int len in read original in close in new byte array input stream original 0 len hash tree tree save service load tree in in close byte array output stream out new byte array output stream 1000000 save service save tree tree out out close make sure all the data is flushed out we only check the length of the result comparing the actual result out to byte array original will usually fail because the order of the properties within each test element may change comparing the lengths should be enough to detect most problem cases int outsz out size allow for input in crlf and output in lf only int lines 0 byte ba out to byte array for int j 0 j ba length j if ba j n lines if len outsz len outsz lines failed true system out println system out println loading file testfiles files i and saving it back changes its size from len to outsz system out println diff len outsz lines lines if save out string outfile testfiles files i out system out println write outfile file output stream outf new file output stream new file outfile outf write out to byte array outf close system out println wrote outfile note this test will fail if a property is added or removed to any of the components used in the test files the way to solve this is to appropriately change the test file if failed todo make these separate tests fail one or more failures detected testloadandsave inputstream fileinputstream bytearrayinputstream hashtree saveservice loadtree bytearrayoutputstream bytearrayoutputstream saveservice savetree tobytearray tobytearray saveout fileoutputstream fileoutputstream tobytearray default constructor public cookie panel init cookiepanel public string get label resource return cookie manager title non nls 1 getlabelresource cookie_manager_title public void action performed action event e string action e get action command if action equals delete command if table model get row count 0 if a table cell is being edited we must cancel the editing before deleting the row if cookie table is editing table cell editor cell editor cookie table get cell editor cookie table get editing row cookie table get editing column cell editor cancel cell editing int row selected cookie table get selected row if row selected 1 table model remove row row selected table model fire table data changed disable the delete and save buttons if no rows remaining after delete if table model get row count 0 delete button set enabled false save button set enabled false table still contains one or more rows so highlight select the appropriate one else int row to select row selected if row selected table model get row count row to select row selected 1 cookie table set row selection interval row to select row to select else if action equals add command if a table cell is being edited we should accept the current value and stop the editing before adding a new row if cookie table is editing table cell editor cell editor cookie table get cell editor cookie table get editing row cookie table get editing column cell editor stop cell editing table model add new row table model fire table data changed enable the delete and save buttons if they are currently disabled if delete button is enabled delete button set enabled true if save button is enabled save button set enabled true highlight select the appropriate row int row to select table model get row count 1 cookie table set row selection interval row to select row to select else if action equals load command try final string txt txt non nls 1 final j file chooser chooser file dialoger prompt to open file txt if chooser null cookie manager manager new cookie manager manager add file chooser get selected file get absolute path for int i 0 i manager get cookie count i add cookie to table manager get i table model fire table data changed if table model get row count 0 delete button set enabled true save button set enabled true catch io exception ex log error ex else if action equals save command try final j file chooser chooser file dialoger prompt to save file cookies txt non nls 1 if chooser null cookie manager create test element save chooser get selected file get absolute path catch io exception ex log error ex actionperformed actionevent getactioncommand delete_command tablemodel getrowcount cookietable isediting tablecelleditor celleditor cookietable getcelleditor cookietable geteditingrow cookietable geteditingcolumn celleditor cancelcellediting rowselected cookietable getselectedrow rowselected tablemodel removerow rowselected tablemodel firetabledatachanged tablemodel getrowcount deletebutton setenabled savebutton setenabled rowtoselect rowselected rowselected tablemodel getrowcount rowtoselect rowselected cookietable setrowselectioninterval rowtoselect rowtoselect add_command cookietable isediting tablecelleditor celleditor cookietable getcelleditor cookietable geteditingrow cookietable geteditingcolumn celleditor stopcellediting tablemodel addnewrow tablemodel firetabledatachanged deletebutton isenabled deletebutton setenabled savebutton isenabled savebutton setenabled rowtoselect tablemodel getrowcount cookietable setrowselectioninterval rowtoselect rowtoselect load_command _txt jfilechooser filedialoger prompttoopenfile _txt cookiemanager cookiemanager addfile getselectedfile getabsolutepath getcookiecount addcookietotable tablemodel firetabledatachanged tablemodel getrowcount deletebutton setenabled savebutton setenabled ioexception save_command jfilechooser filedialoger prompttosavefile cookiemanager createtestelement getselectedfile getabsolutepath ioexception private void add cookie to table cookie cookie table model add row new object cookie get name cookie get value cookie get domain cookie get path boolean value of cookie get secure addcookietotable tablemodel addrow getname getvalue getdomain getpath valueof getsecure modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element cm if cookie table is editing cookie table get cell editor stop cell editing cm clear configure test element cm if cm instanceof cookie manager cookie manager cookie manager cookie manager cm for int i 0 i table model get row count i cookie cookie create cookie table model get row data i cookie manager add cookie cookie manager set clear each iteration clear each iteration is selected cookie manager set cookie policy policy get text testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement cookietable isediting cookietable getcelleditor stopcellediting configuretestelement cookiemanager cookiemanager cookiemanager cookiemanager tablemodel getrowcount createcookie tablemodel getrowdata cookiemanager cookiemanager setcleareachiteration cleareachiteration isselected cookiemanager setcookiepolicy gettext implements j metergui component clear gui public void clear gui super clear gui table model clear data clear each iteration set selected false policy set selected index policies length 1 delete button set enabled false save button set enabled false jmeterguicomponent cleargui cleargui cleargui tablemodel cleardata cleareachiteration setselected setselectedindex deletebutton setenabled savebutton setenabled private cookie create cookie object row data cookie cookie new cookie string row data 0 string row data 1 string row data 2 string row data 3 boolean row data 4 boolean value 0 non expiring return cookie createcookie rowdata rowdata rowdata rowdata rowdata rowdata booleanvalue private void populate table cookie manager manager table model clear data property iterator iter manager get cookies iterator while iter has next add cookie to table cookie iter next get object value populatetable cookiemanager tablemodel cleardata propertyiterator getcookies hasnext addcookietotable getobjectvalue public test element create test element cookie manager cookie manager new cookie manager modify test element cookie manager return cookie manager testelement createtestelement cookiemanager cookiemanager cookiemanager modifytestelement cookiemanager cookiemanager public void configure test element el super configure el cookie manager cookie manager cookie manager el populate table cookie manager clear each iteration set selected cookie manager get clear each iteration policy set text cookie manager get policy testelement cookiemanager cookiemanager cookiemanager populatetable cookiemanager cleareachiteration setselected cookiemanager getcleareachiteration settext cookiemanager getpolicy shows the main cookie configuration panel private void init table model new power table model column resource names column classes clear each iteration new j check box j meter utils get res string clear cookies per iter false non nls 1 policy new j labeled choice j meter utils get res string cookie manager policy non nls 1 policies policy set text cookie manager default policy set layout new border layout set border make border j panel north panel new j panel north panel set layout new vertical layout 5 vertical layout both north panel add make title panel north panel add clear each iteration north panel add policy add north panel border layout north add create cookie table panel border layout center tablemodel powertablemodel column_resource_names columnclasses cleareachiteration jcheckbox jmeterutils getresstring clear_cookies_per_iter jlabeledchoice jmeterutils getresstring cookie_manager_policy settext cookiemanager default_policy setlayout borderlayout setborder makeborder jpanel northpanel jpanel northpanel setlayout verticallayout verticallayout northpanel maketitlepanel northpanel cleareachiteration northpanel northpanel borderlayout createcookietablepanel borderlayout public j panel create cookie table panel create the j table that holds one cookie per row cookie table new j table table model cookie table get table header set default renderer new header as property renderer cookie table set selection mode list selection model single selection cookie table set preferred scrollable viewport size new dimension 100 70 j panel button panel create button panel j panel panel new j panel new border layout 0 5 panel set border border factory create titled border border factory create etched border j meter utils get res string cookies stored non nls 1 panel add new j scroll pane cookie table border layout center panel add button panel border layout south return panel jpanel createcookietablepanel jtable cookietable jtable tablemodel cookietable gettableheader setdefaultrenderer headeraspropertyrenderer cookietable setselectionmode listselectionmodel single_selection cookietable setpreferredscrollableviewportsize jpanel buttonpanel createbuttonpanel jpanel jpanel borderlayout setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring cookies_stored jscrollpane cookietable borderlayout buttonpanel borderlayout private j button create button string res name char mnemonic string command boolean enabled j button button new j button j meter utils get res string res name button set mnemonic mnemonic button set action command command button set enabled enabled button add action listener this return button jbutton createbutton resname jbutton jbutton jmeterutils getresstring resname setmnemonic setactioncommand setenabled addactionlistener private j panel create button panel boolean table empty table model get row count 0 add button create button add a add command true non nls 1 delete button create button delete d delete command table empty non nls 1 load button create button load l load command true non nls 1 save button create button save s save command table empty non nls 1 j panel button panel new j panel button panel add add button button panel add delete button button panel add load button button panel add save button return button panel jpanel createbuttonpanel tableempty tablemodel getrowcount addbutton createbutton add_command deletebutton createbutton delete_command tableempty loadbutton createbutton load_command savebutton createbutton save_command tableempty jpanel buttonpanel jpanel buttonpanel addbutton buttonpanel deletebutton buttonpanel loadbutton buttonpanel savebutton buttonpanel public j meter variables preload variables jmetervariables preloadvariables private void preload variables for int i 0 i pre load length i string property pre load i string value j meter utils get property property if value null variables put property value preloadvariables pre_load pre_load jmeterutils getproperty public string get thread name return thread current thread get name getthreadname currentthread getname public int get iteration return iteration getiteration public void inc iteration iteration inciteration does not appear to be used public void initialize variables clear preload variables preloadvariables public object remove string key return variables remove key public void put string key string value variables put key value public void put object string key object value variables put key value putobject public void put all map vars variables put all vars putall putall public void put all j meter variables vars put all vars variables putall jmetervariables putall returns null values if variable doesn t exist users of this must check for null public string get string key return string variables get key public object get object string key return variables get key getobject public iterator get iterator return collections unmodifiable map variables entry set iterator getiterator unmodifiablemap entryset used by debug sampler public set entry set return collections unmodifiable map variables entry set debugsampler entryset unmodifiablemap entryset private transient node xml node public xml default mutable tree node log warn constructor only intended for use in testing non nls 1 xmlnode xmldefaultmutabletreenode public xml default mutable tree node node root throws sax exception super root get node name init attribute node root this init root root xmldefaultmutabletreenode saxexception getnodename initattributenode initroot public xml default mutable tree node string name node xml node super name this xml node xml node xmldefaultmutabletreenode xmlnode xmlnode xmlnode init root param root throws sax exception private void init root node xml root throws sax exception node list child nodes xml root get child nodes for int i 0 i child nodes get length i node child node child nodes item i init node child node this saxexception initroot xmlroot saxexception nodelist childnodes xmlroot getchildnodes childnodes getlength childnode childnodes initnode childnode init node param node param m tree node throws sax exception private void init node node node xml default mutable tree node m tree node throws sax exception switch node get node type case node element node init element node node m tree node break case node text node init text node text node m tree node break case node cdata section node initcdata section node cdata section node m tree node break case node comment node init comment node comment node m tree node break default if other node type we will just skip it break mtreenode saxexception initnode xmldefaultmutabletreenode mtreenode saxexception getnodetype element_node initelementnode mtreenode text_node inittextnode mtreenode cdata_section_node initcdatasectionnode cdatasection mtreenode comment_node initcommentnode mtreenode init element node param node param m tree node throws sax exception private void init element node node node default mutable tree node m tree node throws sax exception string node name node get node name node list child nodes node get child nodes xml default mutable tree node child tree node new xml default mutable tree node node name node m tree node add child tree node init attribute node node child tree node for int i 0 i child nodes get length i node child node child nodes item i init node child node child tree node mtreenode saxexception initelementnode defaultmutabletreenode mtreenode saxexception nodename getnodename nodelist childnodes getchildnodes xmldefaultmutabletreenode childtreenode xmldefaultmutabletreenode nodename mtreenode childtreenode initattributenode childtreenode childnodes getlength childnode childnodes initnode childnode childtreenode init attribute node param node param m tree node throws sax exception private void init attribute node node node default mutable tree node m tree node throws sax exception named node map nm node get attributes for int i 0 i nm get length i attr nm node attr nm item i string value nm node get name nm node get value non nls 1 non nls 2 xml default mutable tree node attribute node new xml default mutable tree node value nm node m tree node add attribute node mtreenode saxexception initattributenode defaultmutabletreenode mtreenode saxexception namednodemap getattributes getlength nmnode nmnode getname nmnode getvalue xmldefaultmutabletreenode attributenode xmldefaultmutabletreenode nmnode mtreenode attributenode init comment node param node param m tree node throws sax exception private void init comment node comment node default mutable tree node m tree node throws sax exception string data node get data if data null data length 0 string value node get data non nls 1 non nls 2 xml default mutable tree node comment node new xml default mutable tree node value node m tree node add comment node mtreenode saxexception initcommentnode defaultmutabletreenode mtreenode saxexception getdata getdata xmldefaultmutabletreenode commentnode xmldefaultmutabletreenode mtreenode commentnode init cdata section node param node param m tree node throws sax exception private void initcdata section node cdata section node default mutable tree node m tree node throws sax exception string data node get data if data null data length 0 string value cdata node get data non nls 1 non nls 2 xml default mutable tree node comment node new xml default mutable tree node value node m tree node add comment node cdatasection mtreenode saxexception initcdatasectionnode cdatasection defaultmutabletreenode mtreenode saxexception getdata getdata xmldefaultmutabletreenode commentnode xmldefaultmutabletreenode mtreenode commentnode init the text node param node param m tree node throws sax exception private void init text node text node default mutable tree node m tree node throws sax exception string text node get node value trim if text null text length 0 xml default mutable tree node text node new xml default mutable tree node text node m tree node add text node textnode mtreenode saxexception inittextnode defaultmutabletreenode mtreenode saxexception getnodevalue xmldefaultmutabletreenode textnode xmldefaultmutabletreenode mtreenode textnode get the xml node return the xml node public node getxml node return xml node getxmlnode xmlnode private object values public property public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception string property name compound variable values 0 execute string property default property name if values length 2 we have a 3rd parameter property default compound variable values 2 execute string property value j meter utils get prop default property name property default if values length 1 string variable name compound variable values 1 execute if variable name length 0 allow for empty name final j meter variables variables get variables if variables null variables put variable name property value return property value sampleresult previousresult currentsampler invalidvariableexception propertyname compoundvariable propertydefault propertyname propertydefault compoundvariable propertyvalue jmeterutils getpropdefault propertyname propertydefault variablename compoundvariable variablename jmetervariables getvariables variablename propertyvalue propertyvalue public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters min parameter count max parameter count values parameters to array setparameters invalidvariableexception checkparametercount min_parameter_count max_parameter_count toarray public string get reference key return key getreferencekey public list get argument desc return desc getargumentdesc private transient test element saved value null public test element property string name test element value super name this value value testelement savedvalue testelementproperty testelement public test element property super testelementproperty determines if two test elements are equal return true if the value is not null and equals the other objects value false otherwise even if both values are null public boolean equals object o if o instanceof test element property if this o return true if value null return value equals j meter property o get object value return false testelementproperty jmeterproperty getobjectvalue public int hash code return value null 0 value hash code hashcode hashcode non javadoc get string value public string get string value return value to string getstringvalue getstringvalue tostring public void set object value object v if v instanceof test element value test element v setobjectvalue testelement testelement non javadoc get object value public object get object value return value getobjectvalue getobjectvalue public test element get element return value testelement getelement public void set element test element el value el setelement testelement public object clone test element property prop test element property super clone prop value test element value clone return prop testelementproperty testelementproperty testelement public void merge in j meter property prop if is equal type prop value add test element test element prop get object value mergein jmeterproperty isequaltype addtestelement testelement getobjectvalue public void recover running version test element owner if saved value null value saved value value recover running version recoverrunningversion testelement savedvalue savedvalue recoverrunningversion public void set running version boolean running version super set running version running version value set running version running version if running version saved value value else saved value null setrunningversion runningversion setrunningversion runningversion setrunningversion runningversion runningversion savedvalue savedvalue see multi property add property j meter property public void add property j meter property prop value set property prop multiproperty addproperty jmeterproperty addproperty jmeterproperty setproperty see multi property clear public void clear value clear multiproperty see multi property iterator public property iterator iterator return value property iterator multiproperty propertyiterator propertyiterator public void do action action event e throws illegal user action exception j meter tree node node gui package get instance get tree listener get current node test element te test element node get user object if action names what class equals e get action command string gui class name te get property as string test element gui class system out println te get class get name system out println gui class name else if action names debug on equals e get action command logging manager set priority full name debug te get class get name non nls 1 else if action names debug off equals e get action command logging manager set priority full name info te get class get name non nls 1 doaction actionevent illegaluseractionexception jmetertreenode guipackage getinstance gettreelistener getcurrentnode testelement testelement getuserobject actionnames what_class getactioncommand guiclassname getpropertyasstring testelement gui_class getclass getname guiclassname actionnames debug_on getactioncommand loggingmanager setpriorityfullname getclass getname actionnames debug_off getactioncommand loggingmanager setpriorityfullname getclass getname provide the list of action names that are available in this command public set get action names return command set getactionnames commandset to do constructor description public ldap ext test sampler gui init todo ldapexttestsamplergui a newly created component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui param element the test element to configure public void configure test element element super configure element ldap default panel configure element testelement testelement ldapdefaultpanel public test element create test element ldap ext sampler sampler new ldap ext sampler modify test element sampler return sampler testelement createtestelement ldapextsampler ldapextsampler modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element sampler sampler clear ldap ext sampler sampler add test element ldap default panel create test element this configure test element sampler testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement ldapextsampler addtestelement ldapdefaultpanel createtestelement configuretestelement implements j metergui component clear gui public void clear gui super clear gui ldap default panel clear gui jmeterguicomponent cleargui cleargui cleargui ldapdefaultpanel cleargui public string get label resource return ldapext testing title non nls 1 getlabelresource ldapext_testing_title private void init set layout new border layout 0 5 set border make border add make title panel border layout north main panel j panel main panel new j panel new border layout 0 5 ldap default panel new ldap ext config gui false main panel add ldap default panel add main panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout jpanel mainpanel jpanel borderlayout ldapdefaultpanel ldapextconfiggui mainpanel ldapdefaultpanel mainpanel borderlayout public menu info string display label string class full name label display label class name class full name gui comp null menuinfo displaylabel classfullname displaylabel classname classfullname guicomp public menu info j metergui component item string class full name label item get static label class name class full name gui comp item menuinfo jmeterguicomponent classfullname getstaticlabel classname classfullname guicomp public string get label if gui comp null return gui comp get static label return label getlabel guicomp guicomp getstaticlabel public string get class name return class name getclassname classname public class test interleave control extends j meter test case public test interleave control string name super name testinterleavecontrol jmetertestcase testinterleavecontrol public void test processing throws exception test log debug testing interleave controller 1 generic controller controller new generic controller interleave control sub 1 new interleave control sub 1 set style interleave control ignore sub controllers sub 1 add test element new test sampler one sub 1 add test element new test sampler two controller add test element sub 1 controller add test element new test sampler three loop controller sub 2 new loop controller sub 2 set loops 3 generic controller sub 3 new generic controller sub 2 add test element new test sampler four sub 3 add test element new test sampler five sub 3 add test element new test sampler six sub 2 add test element sub 3 sub 2 add test element new test sampler seven controller add test element sub 2 string interleave order new string one two string order new string dummy three four five six seven four five six seven four five six seven int counter 14 controller set running version true sub 1 set running version true sub 2 set running version true sub 3 set running version true controller initialize for int i 0 i 4 i assert equals 14 counter counter 0 test element sampler null while sampler controller next null if counter 0 assert equals interleave order i 2 sampler get name else assert equals order counter sampler get name counter testprocessing testlog genericcontroller genericcontroller interleavecontrol sub_1 interleavecontrol sub_1 setstyle interleavecontrol ignore_sub_controllers sub_1 addtestelement testsampler sub_1 addtestelement testsampler addtestelement sub_1 addtestelement testsampler loopcontroller sub_2 loopcontroller sub_2 setloops genericcontroller sub_3 genericcontroller sub_2 addtestelement testsampler sub_3 addtestelement testsampler sub_3 addtestelement testsampler sub_2 addtestelement sub_3 sub_2 addtestelement testsampler addtestelement sub_2 interleaveorder setrunningversion sub_1 setrunningversion sub_2 setrunningversion sub_3 setrunningversion assertequals testelement assertequals interleaveorder getname assertequals getname public void test processing6 throws exception test log debug testing interleave controller 6 generic controller controller new generic controller interleave control sub 1 new interleave control controller add test element new test sampler one sub 1 set style interleave control ignore sub controllers controller add test element sub 1 loop controller sub 2 new loop controller sub 1 add test element sub 2 sub 2 set loops 3 int counter 1 controller set running version true sub 1 set running version true sub 2 set running version true controller initialize for int i 0 i 4 i assert equals 1 counter counter 0 test element sampler null while sampler controller next null assert equals one sampler get name counter testprocessing6 testlog genericcontroller genericcontroller interleavecontrol sub_1 interleavecontrol addtestelement testsampler sub_1 setstyle interleavecontrol ignore_sub_controllers addtestelement sub_1 loopcontroller sub_2 loopcontroller sub_1 addtestelement sub_2 sub_2 setloops setrunningversion sub_1 setrunningversion sub_2 setrunningversion assertequals testelement assertequals getname public void test processing2 throws exception test log debug testing interleave controller 2 generic controller controller new generic controller interleave control sub 1 new interleave control sub 1 set style interleave control ignore sub controllers sub 1 add test element new test sampler one sub 1 add test element new test sampler two controller add test element sub 1 controller add test element new test sampler three loop controller sub 2 new loop controller sub 2 set loops 3 generic controller sub 3 new generic controller sub 2 add test element new test sampler four sub 3 add test element new test sampler five sub 3 add test element new test sampler six sub 2 add test element sub 3 sub 2 add test element new test sampler seven sub 1 add test element sub 2 string order new string one three two three four three one three two three five three one three two three six three one three int counter 0 controller set running version true sub 1 set running version true sub 2 set running version true sub 3 set running version true controller initialize while counter order length test element sampler null while sampler controller next null assert equals failed on counter order counter sampler get name counter testprocessing2 testlog genericcontroller genericcontroller interleavecontrol sub_1 interleavecontrol sub_1 setstyle interleavecontrol ignore_sub_controllers sub_1 addtestelement testsampler sub_1 addtestelement testsampler addtestelement sub_1 addtestelement testsampler loopcontroller sub_2 loopcontroller sub_2 setloops genericcontroller sub_3 genericcontroller sub_2 addtestelement testsampler sub_3 addtestelement testsampler sub_3 addtestelement testsampler sub_2 addtestelement sub_3 sub_2 addtestelement testsampler sub_1 addtestelement sub_2 setrunningversion sub_1 setrunningversion sub_2 setrunningversion sub_3 setrunningversion testelement assertequals getname public void test processing3 throws exception test log debug testing interleave controller 3 generic controller controller new generic controller interleave control sub 1 new interleave control sub 1 set style interleave control use sub controllers sub 1 add test element new test sampler one sub 1 add test element new test sampler two controller add test element sub 1 controller add test element new test sampler three loop controller sub 2 new loop controller sub 2 set loops 3 generic controller sub 3 new generic controller sub 2 add test element new test sampler four sub 3 add test element new test sampler five sub 3 add test element new test sampler six sub 2 add test element sub 3 sub 2 add test element new test sampler seven sub 1 add test element sub 2 string order new string one three two three four five six seven four five six seven four five six seven three one three two three int counter 0 controller set running version true sub 1 set running version true sub 2 set running version true sub 3 set running version true controller initialize while counter order length test element sampler null while sampler controller next null assert equals failed on counter order counter sampler get name counter testprocessing3 testlog genericcontroller genericcontroller interleavecontrol sub_1 interleavecontrol sub_1 setstyle interleavecontrol use_sub_controllers sub_1 addtestelement testsampler sub_1 addtestelement testsampler addtestelement sub_1 addtestelement testsampler loopcontroller sub_2 loopcontroller sub_2 setloops genericcontroller sub_3 genericcontroller sub_2 addtestelement testsampler sub_3 addtestelement testsampler sub_3 addtestelement testsampler sub_2 addtestelement sub_3 sub_2 addtestelement testsampler sub_1 addtestelement sub_2 setrunningversion sub_1 setrunningversion sub_2 setrunningversion sub_3 setrunningversion testelement assertequals getname public void test processing4 throws exception test log debug testing interleave controller 4 generic controller controller new generic controller interleave control sub 1 new interleave control sub 1 set style interleave control ignore sub controllers controller add test element sub 1 generic controller sub 2 new generic controller sub 2 add test element new test sampler one sub 2 add test element new test sampler two sub 1 add test element sub 2 generic controller sub 3 new generic controller sub 3 add test element new test sampler three sub 3 add test element new test sampler four sub 1 add test element sub 3 string order new string one three two four int counter 0 controller set running version true sub 1 set running version true sub 2 set running version true sub 3 set running version true controller initialize while counter order length test element sampler null while sampler controller next null assert equals failed on counter order counter sampler get name counter testprocessing4 testlog genericcontroller genericcontroller interleavecontrol sub_1 interleavecontrol sub_1 setstyle interleavecontrol ignore_sub_controllers addtestelement sub_1 genericcontroller sub_2 genericcontroller sub_2 addtestelement testsampler sub_2 addtestelement testsampler sub_1 addtestelement sub_2 genericcontroller sub_3 genericcontroller sub_3 addtestelement testsampler sub_3 addtestelement testsampler sub_1 addtestelement sub_3 setrunningversion sub_1 setrunningversion sub_2 setrunningversion sub_3 setrunningversion testelement assertequals getname public void test processing5 throws exception test log debug testing interleave controller 5 generic controller controller new generic controller interleave control sub 1 new interleave control sub 1 set style interleave control use sub controllers controller add test element sub 1 generic controller sub 2 new generic controller sub 2 add test element new test sampler one sub 2 add test element new test sampler two sub 1 add test element sub 2 generic controller sub 3 new generic controller sub 3 add test element new test sampler three sub 3 add test element new test sampler four sub 1 add test element sub 3 string order new string one two three four int counter 0 controller set running version true sub 1 set running version true sub 2 set running version true sub 3 set running version true controller initialize while counter order length test element sampler null while sampler controller next null assert equals failed on counter order counter sampler get name counter testprocessing5 testlog genericcontroller genericcontroller interleavecontrol sub_1 interleavecontrol sub_1 setstyle interleavecontrol use_sub_controllers addtestelement sub_1 genericcontroller sub_2 genericcontroller sub_2 addtestelement testsampler sub_2 addtestelement testsampler sub_1 addtestelement sub_2 genericcontroller sub_3 genericcontroller sub_3 addtestelement testsampler sub_3 addtestelement testsampler sub_1 addtestelement sub_3 setrunningversion sub_1 setrunningversion sub_2 setrunningversion sub_3 setrunningversion testelement assertequals getname constructor for the file panel object public directory panel title init filepanel directorypanel public directory panel string title this title title init directorypanel public directory panel string title string filetype color bk this title filetype this background bk init directorypanel public directory panel string title string filetype this title this filetype filetype directorypanel constructor for the file panel object public directory panel change listener l string title this title title init listeners add l filepanel directorypanel changelistener public void add change listener change listener l listeners add l addchangelistener changelistener private void init set background this background set border border factory create titled border title add box create horizontal strut 5 add filename add box create horizontal strut 5 filename add action listener this add browse browse set action command browse browse add action listener this setbackground setborder borderfactory createtitledborder createhorizontalstrut createhorizontalstrut addactionlistener setactioncommand addactionlistener if the gui needs to enable disable the file panel call the method param enable public void enable file boolean enable browse set enabled enable filename set enabled enable filepanel enablefile setenabled setenabled gets the filename attribute of the file panel object return the filename value public string get filename return filename get text filepanel getfilename gettext sets the filename attribute of the file panel object param f the new filename value public void set filename string f filename set text f filepanel setfilename settext private void fire file changed iterator iter listeners iterator while iter has next change listener iter next state changed new change event this firefilechanged hasnext changelistener statechanged changeevent public void action performed action event e if e get action command equals browse j file chooser chooser directory dialoger prompt to open file if chooser get selected file null filename set text chooser get selected file get path fire file changed else fire file changed actionperformed actionevent getactioncommand jfilechooser directorydialoger prompttoopenfile getselectedfile settext getselectedfile getpath firefilechanged firefilechanged public class header as property renderer extends default table cell renderer public header as property renderer super headeraspropertyrenderer defaulttablecellrenderer headeraspropertyrenderer public component get table cell renderer component j table table object value boolean is selected boolean has focus int row int column if table null j table header header table get table header if header null set foreground header get foreground set background header get background set font header get font set text get text value row column set border ui manager get border table header cell border set horizontal alignment j label center return this gettablecellrenderercomponent jtable isselected hasfocus jtableheader gettableheader setforeground getforeground setbackground getbackground setfont getfont settext gettext setborder uimanager getborder tableheader cellborder sethorizontalalignment jlabel get the text for the value as the translation of the resource name param value param column param row return the text protected string get text object value int row int column if value null return return j meter utils get res string value to string gettext jmeterutils getresstring tostring public j meter jmeter starts up j meter in gui mode private void start gui string test file plugin manager install this true j meter tree model tree model new j meter tree model j meter tree listener tree lis new j meter tree listener tree model tree lis set action handler action router get instance notused gui package gui pack gui package get instance tree lis tree model main frame main new main frame action router get instance tree model tree lis component util center component in window main 80 main show action router get instance action performed new action event main 1 action names add all if test file null file input stream reader null try file f new file test file log info loading file f reader new file input stream f hash tree tree save service load tree reader gui package get instance set test plan file f get absolute path load insert loaded tree 1 tree catch conversion exception e log error failure loading test file e j meter utils report error to user save service c eto string e catch exception e log error failure loading test file e j meter utils report error to user e to string finally j orphan utils close quietly reader jmeter startgui testfile pluginmanager jmetertreemodel treemodel jmetertreemodel jmetertreelistener treelis jmetertreelistener treemodel treelis setactionhandler actionrouter getinstance guipackage guipack guipackage getinstance treelis treemodel mainframe mainframe actionrouter getinstance treemodel treelis componentutil centercomponentinwindow actionrouter getinstance actionperformed actionevent actionnames add_all testfile fileinputstream testfile fileinputstream hashtree saveservice loadtree guipackage getinstance settestplanfile getabsolutepath insertloadedtree conversionexception jmeterutils reporterrortouser saveservice cetostring jmeterutils reporterrortouser tostring jorphanutils closequietly takes the command line arguments and uses them to determine how to startup j meter public void start string args cl args parser parser new cl args parser args options string error parser get error string if error null check option combinations boolean gui parser get argument by id nongui opt null boolean remote start parser get argument by id remote opt null parser get argument by id remote opt param null if gui remote start error r and r are only valid in non gui mode if null error system err println error error system out println usage system out println cl util describe options options to string return try initialize properties parser also initialises j meter logging the following is needed for http client originally tried doing this in http sampler2 but it appears that it was done too late when running in gui mode set the commons logging default to avalon logkit if not already defined if system get property org apache commons logging log null non nls 1 system set property org apache commons logging log non nls 1 org apache commons logging impl log kit logger non nls 1 log info j meter utils getj meter copyright log info version j meter utils getj meter version log property java version non nls 1 log property java vm name non nls 1 log property os name non nls 1 log property os arch non nls 1 log property os version non nls 1 log property file encoding non nls 1 log info default locale locale get default get display name log info j meter locale j meter utils get locale get display name log info j meter home j meter utils getj meter home log property user dir non nls 1 log info pwd new file get canonical path non nls 1 log info ip j meter utils get local hostip name j meter utils get local host name full name j meter utils get local host full name set proxy parser update class loader if log is debug enabled string jcp system get property java class path non nls 1 string bits jcp split file path separator log debug class path for int i 0 i bits length i log debug bits i log debug jcp set some hopefully useful properties long now system current time millis j meter utils set property start ms long to string now non nls 1 date today new date now so it agrees with above todo perhaps should share code with time function for this j meter utils set property start ymd new simple date format yyyym mdd format today non nls 1 non nls 2 j meter utils set property start hms new simple date format h hmmss format today non nls 1 non nls 2 if parser get argument by id version opt null system out println j meter utils getj meter copyright system out println version j meter utils getj meter version else if parser get argument by id help opt null system out println j meter utils get resource file as text org apache jmeter help txt non nls 1 else if parser get argument by id server opt null start the server start server j meter utils get prop default server port 0 non nls 1 start optional servers else string test file null cl option test file opt parser get argument by id testfile opt if test file opt null test file test file opt get argument if use last jmx equals test file test file load recent project get recent file 0 most recent if parser get argument by id nongui opt null start gui test file start optional servers else cl option rem parser get argument by id remote opt param if rem null rem parser get argument by id remote opt cl option jtl parser get argument by id logfile opt string jtl file null if jtl null jtl file processlast jtl get argument jtl non nls 1 start non gui test file jtl file rem start optional servers catch illegal user action exception e system out println e get message system out println incorrect usage system out println cl util describe options options to string catch throwable e if log null log fatal error an error occurred e else e print stack trace system out println an error occurred e get message system exit 1 jmeter clargsparser clargsparser geterrorstring getargumentbyid nongui_opt remotestart getargumentbyid remote_opt getargumentbyid remote_opt_param remotestart clutil describeoptions tostring initializeproperties jmeter httpclient httpsampler2 getproperty setproperty logkitlogger jmeterutils getjmetercopyright jmeterutils getjmeterversion logproperty logproperty logproperty logproperty logproperty logproperty getdefault getdisplayname jmeter jmeterutils getlocale getdisplayname jmeterhome jmeterutils getjmeterhome logproperty getcanonicalpath jmeterutils getlocalhostip jmeterutils getlocalhostname fullname jmeterutils getlocalhostfullname setproxy updateclassloader isdebugenabled getproperty pathseparator classpath currenttimemillis jmeterutils setproperty tostring __time jmeterutils setproperty simpledateformat yyyymmdd jmeterutils setproperty simpledateformat hhmmss getargumentbyid version_opt jmeterutils getjmetercopyright jmeterutils getjmeterversion getargumentbyid help_opt jmeterutils getresourcefileastext getargumentbyid server_opt startserver jmeterutils getpropdefault server_port startoptionalservers testfile cloption testfileopt getargumentbyid testfile_opt testfileopt testfile testfileopt getargument use_last_jmx testfile testfile loadrecentproject getrecentfile getargumentbyid nongui_opt startgui testfile startoptionalservers cloption getargumentbyid remote_opt_param getargumentbyid remote_opt cloption getargumentbyid logfile_opt jtlfile jtlfile getargument startnongui testfile jtlfile startoptionalservers illegaluseractionexception getmessage clutil describeoptions tostring fatalerror printstacktrace getmessage update classloader if necessary private void update class loader update path search paths non nls 1 non nls 2 update path user classpath file path separator non nls 1 updateclassloader updatepath search_paths updatepath pathseparator private void update path string property string sep string userpath j meter utils get prop default property non nls 1 if userpath length 0 return log info property userpath non nls 1 string tokenizer tok new string tokenizer userpath sep while tok has more tokens string path tok next token file f new file path if f can read f is directory log warn can t read path else log info adding to classpath path try new driver add path path catch malformedurl exception e log warn error adding path e get localized message updatepath jmeterutils getpropdefault stringtokenizer stringtokenizer hasmoretokens nexttoken canread isdirectory newdriver addpath malformedurlexception getlocalizedmessage private void start optional servers int bshport j meter utils get prop default beanshell server port 0 non nls 1 string bshfile j meter utils get prop default beanshell server file non nls 1 non nls 2 if bshport 0 log info starting beanshell server bshport bshfile runnable t new bean shell server bshport bshfile t run should we run a beanshell script on startup string bshinit j meter utils get property beanshell init file non nls 1 if bshinit null log info run beanshell on file bshinit try bean shell interpreter bsi new bean shell interpreter bshinit log bsi source bshinit catch class not found exception e log warn could not start beanshell e get localized message catch j meter exception e log warn could not process beanshell file e get localized message int mirror port j meter utils get prop default mirror server port 0 non nls 1 if mirror port 0 log info starting mirror server mirror port try object instance class tools construct org apache jmeter protocol http control http mirror control non nls 1 mirror port class tools invoke instance start http mirror catch j meter exception e log warn could not start mirror server e startoptionalservers jmeterutils getpropdefault jmeterutils getpropdefault beanshellserver jmeterutils getproperty beanshellinterpreter beanshellinterpreter classnotfoundexception getlocalizedmessage jmeterexception getlocalizedmessage mirrorport jmeterutils getpropdefault mirrorport mirrorport classtools httpmirrorcontrol mirrorport classtools starthttpmirror jmeterexception sets a proxy server for the jvm if the command line arguments are specified private void set proxy cl args parser parser throws illegal user action exception if parser get argument by id proxy username null properties jmeter props j meter utils getj meter properties if parser get argument by id proxy password null string u p authenticator set default new proxy authenticator u parser get argument by id proxy username get argument p parser get argument by id proxy password get argument log info set proxy login u p jmeter props set property http proxy user u for httpclient jmeter props set property http proxy pass p for httpclient else string u authenticator set default new proxy authenticator u parser get argument by id proxy username get argument log info set proxy login u jmeter props set property http proxy user u if parser get argument by id proxy host null parser get argument by id proxy port null string h parser get argument by id proxy host get argument string p parser get argument by id proxy port get argument system set property http proxy host h non nls 1 system set property https proxy host h non nls 1 system set property http proxy port p non nls 1 system set property https proxy port p non nls 1 log info set http s proxy host h port p else if parser get argument by id proxy host null parser get argument by id proxy port null throw new illegal user action exception j meter utils get res string proxy cl error non nls 1 if parser get argument by id nonproxy hosts null string n parser get argument by id nonproxy hosts get argument system set property http non proxy hosts n non nls 1 system set property https non proxy hosts n non nls 1 log info set http s non proxy hosts n setproxy clargsparser illegaluseractionexception getargumentbyid proxy_username jmeterprops jmeterutils getjmeterproperties getargumentbyid proxy_password setdefault proxyauthenticator getargumentbyid proxy_username getargument getargumentbyid proxy_password getargument jmeterprops setproperty http_proxy_user jmeterprops setproperty http_proxy_pass setdefault proxyauthenticator getargumentbyid proxy_username getargument jmeterprops setproperty http_proxy_user getargumentbyid proxy_host getargumentbyid proxy_port getargumentbyid proxy_host getargument getargumentbyid proxy_port getargument setproperty proxyhost setproperty proxyhost setproperty proxyport setproperty proxyport proxyhost getargumentbyid proxy_host getargumentbyid proxy_port illegaluseractionexception jmeterutils getresstring proxy_cl_error getargumentbyid nonproxy_hosts getargumentbyid nonproxy_hosts getargument setproperty nonproxyhosts setproperty nonproxyhosts nonproxyhosts private void initialize properties cl args parser parser if parser get argument by id propfile opt null j meter utils loadj meter properties parser get argument by id propfile opt get argument else j meter utils loadj meter properties new driver getj meter dir file separator bin file separator non nls 1 jmeter properties non nls 1 if parser get argument by id jmlogfile opt null string jmlogfile parser get argument by id jmlogfile opt get argument jmlogfile processlast jmlogfile log non nls 1 j meter utils set property logging manager log file jmlogfile j meter utils init logging j meter utils init locale bug 33845 allow direct override of home dir if parser get argument by id jmeter home opt null j meter utils setj meter home new driver getj meter dir else j meter utils setj meter home parser get argument by id jmeter home opt get argument properties jmeter props j meter utils getj meter properties remote props new properties add local j meter properties if the file is found string user prop j meter utils get prop default user properties non nls 1 if user prop length 0 non nls 1 file input stream fis null try file file j meter utils find file user prop if file can read log info loading user properties from file get canonical path fis new file input stream file properties tmp new properties tmp load fis jmeter props put all tmp logging manager set logging levels tmp do what would be done earlier catch io exception e log warn error loading user property file user prop e finally j orphan utils close quietly fis add local system properties if the file is found string sys prop j meter utils get prop default system properties non nls 1 if sys prop length 0 file input stream fis null try file file j meter utils find file sys prop if file can read log info loading system properties from file get canonical path fis new file input stream file system get properties load fis catch io exception e log warn error loading system property file sys prop e finally j orphan utils close quietly fis process command line property definitions these can potentially occur multiple times list cl options parser get arguments int size cl options size for int i 0 i size i cl option option cl option cl options get i string name option get argument 0 string value option get argument 1 file input stream fis null switch option get descriptor get id should not have any text arguments case cl option text argument throw new illegal argument exception unknown arg option get argument case propfile2 opt bug 33920 allow multiple props try fis new file input stream new file name properties tmp new properties tmp load fis jmeter props put all tmp logging manager set logging levels tmp do what would be done earlier catch file not found exception e log warn can t find additional property file name e catch io exception e log warn error loading additional property file name e finally j orphan utils close quietly fis break case system propfile log info setting system properties from file name try fis new file input stream new file name system get properties load fis catch io exception e log warn cannot find system property file e get localized message finally j orphan utils close quietly fis break case system property if value length 0 set it log info setting system property name value system get properties set property name value else reset it log warn removing system property name system get properties remove name break case jmeter property if value length 0 set it log info setting j meter property name value jmeter props set property name value else reset it log warn removing j meter property name jmeter props remove name break case jmeter global prop if value length 0 set it log info setting global property name value remote props set property name value else file prop file new file name if prop file can read log info setting global properties from the file name try fis new file input stream prop file remote props load fis catch file not found exception e log warn could not find properties file e get localized message catch io exception e log warn could not load properties file e get localized message finally j orphan utils close quietly fis break case loglevel if value length 0 set category log info log level name value logging manager set priority value name else set root level log warn log level name logging manager set priority name break case remote stop remote stop true break string sample variables string jmeter props get sample event sample variables if sample variables null remote props put sample event sample variables sample variables initializeproperties clargsparser getargumentbyid propfile_opt jmeterutils loadjmeterproperties getargumentbyid propfile_opt getargument jmeterutils loadjmeterproperties newdriver getjmeterdir getargumentbyid jmlogfile_opt getargumentbyid jmlogfile_opt getargument jmeterutils setproperty loggingmanager log_file jmeterutils initlogging jmeterutils initlocale getargumentbyid jmeter_home_opt jmeterutils setjmeterhome newdriver getjmeterdir jmeterutils setjmeterhome getargumentbyid jmeter_home_opt getargument jmeterprops jmeterutils getjmeterproperties remoteprops jmeter userprop jmeterutils getpropdefault userprop fileinputstream jmeterutils findfile userprop canread getcanonicalpath fileinputstream jmeterprops putall loggingmanager setlogginglevels ioexception userprop jorphanutils closequietly sysprop jmeterutils getpropdefault sysprop fileinputstream jmeterutils findfile sysprop canread getcanonicalpath fileinputstream getproperties ioexception sysprop jorphanutils closequietly cloptions getarguments cloptions cloption cloption cloptions getargument getargument fileinputstream getdescriptor getid cloption text_argument illegalargumentexception getargument propfile2_opt fileinputstream jmeterprops putall loggingmanager setlogginglevels filenotfoundexception ioexception jorphanutils closequietly system_propfile fileinputstream getproperties ioexception getlocalizedmessage jorphanutils closequietly system_property getproperties setproperty getproperties jmeter_property jmeter jmeterprops setproperty jmeter jmeterprops jmeter_global_prop remoteprops setproperty propfile propfile canread fileinputstream propfile remoteprops filenotfoundexception getlocalizedmessage ioexception getlocalizedmessage jorphanutils closequietly loglevel loggingmanager setpriority loglevel loggingmanager setpriority remote_stop remotestop sample_variables jmeterprops sampleevent sample_variables sample_variables remoteprops sampleevent sample_variables sample_variables private string processlast string jmlogfile string suffix if use last jmx equals jmlogfile use last jmx concat suffix equals jmlogfile string last load recent project get recent file 0 most recent final string jmx suffix jmx non nls 1 if last to upper case locale english ends with jmx suffix jmlogfile last substring 0 last length jmx suffix length concat suffix return jmlogfile use_last_jmx use_last_jmx loadrecentproject getrecentfile jmx_suffix touppercase endswith jmx_suffix jmx_suffix private void start server int port try remotej meter engine impl start server port catch exception ex log error giving up as server failed with ex system err println server failed to start ex system exit 1 give up startserver remotejmeterengineimpl startserver private void start non gui string test file string log file cl option remote start throws illegal user action exception add a system property so samplers can check to see if j meter is running in non gui mode system set property jmeter non gui true non nls 1 j meter driver new j meter todo why does it create a new instance driver remote props this remote props driver remote stop this remote stop driver parent this plugin manager install this false string remote hosts string null if remote start null remote hosts string remote start get argument if remote hosts string null remote hosts string j meter utils get prop default remote hosts non nls 1 127 0 0 1 non nls 1 if test file null throw new illegal user action exception non gui runs require a test plan if log file null driver run non gui test file null remote start null remote hosts string else driver run non gui test file log file remote start null remote hosts string startnongui testfile logfile cloption remotestart illegaluseractionexception jmeter nongui setproperty jmeter_non_gui jmeter jmeter remoteprops remoteprops remotestop remotestop pluginmanager remote_hosts_string remotestart remote_hosts_string remotestart getargument remote_hosts_string remote_hosts_string jmeterutils getpropdefault remote_hosts testfile illegaluseractionexception logfile runnongui testfile remotestart remote_hosts_string runnongui testfile logfile remotestart remote_hosts_string run test in batch mode private void run non gui string test file string log file boolean remote start string remote hosts string file input stream reader null try file f new file test file if f exists f is file println could not open test file return file server get file server set basedir f get absolute path reader new file input stream f log info loading file f hash tree tree save service load tree reader j meter tree model tree model new j meter tree model new object create non gui version to avoid headless problems j meter tree node root j meter tree node tree model get root tree model add sub tree tree root hack to resolve module controllers in non gui mode search by class replaceable controllers new search by class replaceable controller class tree traverse replaceable controllers collection replaceable controllers res replaceable controllers get search results for iterator iter replaceable controllers res iterator iter has next replaceable controller replaceable controller replaceable controller iter next replaceable controller resolve replacement sub tree root remove the disabled items for gui runs this is done in start java convert sub tree tree if log file null result collector logger new result collector logger set filename log file tree add tree get array 0 logger string summariser name j meter utils get prop default summariser name non nls 1 if summariser name length 0 log info creating summariser summariser name println creating summariser summariser name summariser summer new summariser summariser name tree add tree get array 0 summer list engines new linked list tree add tree get array 0 new listen to test parent remote start remote stop engines null println created the tree successfully using test file j meter engine engine null if remote start engine new standardj meter engine engine configure tree long now system current time millis println starting the test new date now now engine run test else java util string tokenizer st new java util string tokenizer remote hosts string non nls 1 while st has more elements string el string st next element println configuring remote engine for el log info configuring remote engine for el engines add do remote init el trim tree println starting remote engines long now system current time millis println starting the test new date now now iterator iter engines iterator while iter has next engine j meter engine iter next if engine null engine run test println remote engines have been started catch exception e system out println error in nongui driver e to string log error e finally j orphan utils close quietly reader runnongui testfile logfile remotestart remote_hosts_string fileinputstream testfile isfile testfile fileserver getfileserver setbasedir getabsolutepath fileinputstream hashtree saveservice loadtree jmetertreemodel treemodel jmetertreemodel jmetertreenode jmetertreenode treemodel getroot treemodel addsubtree modulecontrollers searchbyclass replaceablecontrollers searchbyclass replaceablecontroller replaceablecontrollers replaceablecontrollersres replaceablecontrollers getsearchresults replaceablecontrollersres hasnext replaceablecontroller replaceablecontroller replaceablecontroller replaceablecontroller resolvereplacementsubtree convertsubtree logfile resultcollector resultcollector setfilename logfile getarray summarisername jmeterutils getpropdefault summarisername summarisername summarisername summarisername getarray linkedlist getarray listentotest remotestart remotestop testfile jmeterengine remotestart standardjmeterengine currenttimemillis runtest stringtokenizer stringtokenizer remote_hosts_string hasmoreelements nextelement doremoteinit currenttimemillis hasnext jmeterengine runtest nonguidriver tostring jorphanutils closequietly refactored from abstract action java param tree public static void convert sub tree hash tree tree iterator iter new linked list tree list iterator while iter has next object o iter next if o instanceof test element test element item test element o if item is enabled if item instanceof replaceable controller replaceable controller rc todo this bit of code needs to be tidied up unfortunately module controller is in components not core if item get class get name equals org apache jmeter control module controller bug 47165 rc replaceable controller item else hack force the controller to load its tree rc replaceable controller item clone hash tree sub tree tree get tree item if sub tree null hash tree replacement tree rc get replacement sub tree if replacement tree null convert sub tree replacement tree tree replace item rc tree set rc replacement tree else null sub tree convert sub tree tree get tree item else not replaceable controller convert sub tree tree get tree item else not enabled tree remove item else not a test element j meter tree node item j meter tree node o if item is enabled replacement only needs to occur when starting the engine see standardj meter engine run if item get user object instanceof replaceable controller replaceable controller rc replaceable controller item get test element hash tree sub tree tree get tree item if sub tree null hash tree replacement tree rc get replacement sub tree if replacement tree null convert sub tree replacement tree tree replace item rc tree set rc replacement tree else not a replaceable controller convert sub tree tree get tree item test element test element item get test element tree replace item test element else not enabled tree remove item abstractaction convertsubtree hashtree linkedlist hasnext testelement testelement testelement isenabled replaceablecontroller replaceablecontroller modulecontroller getclass getname modulecontroller replaceablecontroller replaceablecontroller hashtree subtree gettree subtree hashtree replacementtree getreplacementsubtree replacementtree convertsubtree replacementtree replacementtree subtree convertsubtree gettree convertsubtree gettree testelement jmetertreenode jmetertreenode isenabled standardjmeterengine getuserobject replaceablecontroller replaceablecontroller replaceablecontroller gettestelement hashtree subtree gettree subtree hashtree replacementtree getreplacementsubtree replacementtree convertsubtree replacementtree replacementtree replaceablecontroller convertsubtree gettree testelement testelement gettestelement testelement private j meter engine do remote init string host name hash tree test tree j meter engine engine null try engine new clientj meter engine host name catch exception e log fatal error failure connecting to remote host e system err println failure connecting to remote host e return null engine configure test tree if remote props is empty engine set properties remote props return engine jmeterengine doremoteinit hostname hashtree testtree jmeterengine clientjmeterengine hostname fatalerror testtree remoteprops isempty setproperties remoteprops private list engines public listen to test j meter parent list engines parent parent this engines engines listentotest jmeter _parent public synchronized void test ended string host started long now system current time millis log info finished remote host host now if started 0 thread stop soon new thread this stop soon start testended currenttimemillis stopsoon stopsoon public void test ended long now system current time millis println tidying up new date now now println end of run testended currenttimemillis public synchronized void test started string host started long now system current time millis log info started remote host host now teststarted currenttimemillis public void test started long now system current time millis log info j meter utils get res string running test now non nls 1 teststarted currenttimemillis jmeterutils getresstring running_test this is a hack to allow listeners a chance to close their files must implement a queue for sample responses tied to the engine and the engine won t deliver test ended signal till all sample responses have been delivered should also improve performance of remote j meter testing public void run long now system current time millis println tidying up new date now now note although it should not be necessary to call system exit here in the case of a remote test a timer thread seems to be generated by the naming lookup method and it does not die if engines null it will be null unless remote stop true system out println exitting remote servers iterator it engines iterator while it has next j meter engine e j meter engine it next e exit try thread sleep 5000 allow listeners to close files catch interrupted exception ignored println end of run system exit 0 testended jmeter currenttimemillis remotestop hasnext jmeterengine jmeterengine interruptedexception see test listener test iteration start loop iteration event public void test iteration start loop iteration event event ignored testlistener testiterationstart loopiterationevent testiterationstart loopiterationevent private static void println string str system out println str public string get icon mappings final string default icon prop org apache jmeter images icon properties non nls 1 string icon prop j meter utils get prop default jmeter icons default icon prop non nls 1 properties p j meter utils load properties icon prop if p null icon prop equals default icon prop log info icon prop not found using default icon prop icon prop default icon prop p j meter utils load properties icon prop if p null log info icon prop not found using inbuilt icon set return default icons log info loaded icon properties from icon prop string iconlist new string p size 3 enumeration pe p keys int i 0 while pe has more elements string key string pe next element string icons j orphan utils split p get property key non nls 1 iconlist i 0 key iconlist i 1 icons 0 if icons length 1 iconlist i 2 icons 1 i return iconlist geticonmappings defaulticonprop iconprop jmeterutils getpropdefault defaulticonprop jmeterutils loadproperties iconprop iconprop defaulticonprop iconprop defaulticonprop iconprop defaulticonprop jmeterutils loadproperties iconprop iconprop default_icons iconprop hasmoreelements nextelement jorphanutils getproperty public string get resource bundles return new string 0 getresourcebundles check if j meter is running in non gui mode return true if j meter is running in non gui mode public static boolean is nongui return true equals system get property j meter jmeter non gui non nls 1 jmeter jmeter isnongui getproperty jmeter jmeter_non_gui private void log property string prop log info prop system get property prop non nls 1 logproperty getproperty log info prop system get property prop non nls 1 private void log property string prop string separator log info prop separator system get property prop non nls 1 getproperty logproperty getproperty no arg constructor public int sum intsum execute the function see function execute sample result sampler public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception j meter variables vars get variables int sum 0 string var name compound variable values values length 1 execute for int i 0 i values length 1 i sum integer parse int compound variable values i execute try sum integer parse int var name var name null there is no variable name catch number format exception ignored string total string integer to string sum if vars null var name null vars will be null on test plan vars put var name trim total string return total string sampleresult sampleresult previousresult currentsampler invalidvariableexception jmetervariables getvariables varname compoundvariable parseint compoundvariable parseint varname varname numberformatexception totalstring tostring varname testplan varname totalstring totalstring set the parameters for the function see function set parameters collection public synchronized void set parameters collection parameters throws invalid variable exception check min parameter count parameters 2 values parameters to array setparameters setparameters invalidvariableexception checkminparametercount toarray get the invocation key for this function see function get reference key public string get reference key return key getreferencekey getreferencekey get the description of this function see function get argument desc public list get argument desc return desc getargumentdesc getargumentdesc private j meter context jmctx null public test jexl function string name super name jmetercontext testjexlfunction public void set up function new jexl function result new sample result jmctx j meter context service get context string data the quick brown fox result set response data data get bytes vars new j meter variables jmctx set variables vars jmctx set previous result result params new linked list setup jexlfunction sampleresult jmetercontextservice getcontext setresponsedata getbytes jmetervariables setvariables setpreviousresult linkedlist public void test parameter count throws exception check invalid parameter counts function 1 2 testparametercount checkinvalidparametercounts public void test sum throws exception params add new compound variable 1 2 3 function set parameters params string ret function execute result null assert equals 6 ret testsum compoundvariable setparameters assertequals public void test sum var throws exception params add new compound variable 1 2 3 params add new compound variable total function set parameters params string ret function execute result null assert equals 6 ret assert equals 6 vars get total testsumvar compoundvariable compoundvariable setparameters assertequals assertequals public void test replace1 throws exception params add new compound variable sample result get response data as string replace all t t function set parameters params string ret function execute result null assert equals the quick brown fox ret testreplace1 compoundvariable sampleresult getresponsedataasstring replaceall setparameters assertequals public void test replace2 throws exception vars put url query cgi s1 1 amp s2 2 amp s3 3 params add new compound variable vars get url replace all amp params add new compound variable url function set parameters params string ret function execute result null assert equals query cgi s1 1 s2 2 s3 3 ret assert equals ret vars get object url testreplace2 compoundvariable replaceall compoundvariable setparameters assertequals assertequals getobject public bean shell interpreter throws class not found exception init file null logger null init beanshellinterpreter classnotfoundexception initfile param init initialisation file param log logger to pass to interpreter public bean shell interpreter string init logger log throws class not found exception init file init logger log init _log beanshellinterpreter _log classnotfoundexception initfile _log called from ctor so must be private or final but it does not seem useful elsewhere private void init throws class not found exception if bsh class null throw new class not found exception bsh interpreter try bsh instance bsh class new instance catch instantiation exception e log error can t instantiate bean shell e throw new class not found exception can t instantiate bean shell e catch illegal access exception e log error can t instantiate bean shell e throw new class not found exception can t instantiate bean shell e if logger null do this before starting the script try set log logger non nls 1 catch j meter exception e log warn can t set logger variable e if init file null init file length 0 string file to use init file check file so we can distinguish file error from script error file in new file file to use if in exists cannot find the file locally so try the bin directory file to use j meter utils getj meter home file separator bin non nls 1 file separator init file in new file file to use if in exists log warn cannot find init file init file if in can read log warn cannot read init file file to use try source file to use catch j meter exception e log warn cannot source init file file to use e classnotfoundexception bshclass classnotfoundexception bsh_interpreter bshinstance bshclass newinstance instantiationexception beanshell classnotfoundexception beanshell illegalaccessexception beanshell classnotfoundexception beanshell jmeterexception initfile initfile filetouse initfile filetouse filetouse jmeterutils getjmeterhome initfile filetouse initfile canread filetouse filetouse jmeterexception filetouse resets the bean shell interpreter throws class not found exception if interpreter cannot be instantiated public void reset throws class not found exception init beanshell classnotfoundexception classnotfoundexception private object bsh invoke method m object o boolean should log throws j meter exception object r null final string error string error invoking bsh method try r m invoke bsh instance o catch illegal argument exception e programming error final string message error string m get name log error message throw new j meter error message e catch illegal access exception e also programming error final string message error string m get name log error message throw new j meter error message e catch invocation target exception e can occur at run time could be caused by the bsh exceptions eval error parse exception or target error string message error string m get name throwable cause e get cause if cause null message t cause get localized message if should log log error message throw new j meter exception message e return r bshinvoke shouldlog jmeterexception errorstring bshinstance illegalargumentexception errorstring getname jmetererror illegalaccessexception errorstring getname jmetererror invocationtargetexception evalerror parseexception targeterror errorstring getname getcause getlocalizedmessage shouldlog jmeterexception public object eval string s throws j meter exception return bsh invoke bsh eval new object s true jmeterexception bshinvoke bsheval public object eval no log string s throws j meter exception return bsh invoke bsh eval new object s false evalnolog jmeterexception bshinvoke bsheval public object set string s object o throws j meter exception return bsh invoke bsh set new object s o true jmeterexception bshinvoke bshset public object set string s boolean b throws j meter exception return bsh invoke bsh set new object s boolean value of b true jmeterexception bshinvoke bshset valueof public object source string s throws j meter exception return bsh invoke bsh source new object s true jmeterexception bshinvoke bshsource public object get string s throws j meter exception return bsh invoke bsh get new object s true jmeterexception bshinvoke bshget for use by unit tests public static boolean is interpreter present return bsh class null isinterpreterpresent bshclass public test while controller string name super name testwhilecontroller public void set up jmctx j meter context service get context jmctx set variables new j meter variables jmvars jmctx get variables setup jmetercontextservice getcontext setvariables jmetervariables getvariables private void set last sample status boolean status jmvars put j meter thread last sample ok boolean to string status setlastsamplestatus jmeterthread last_sample_ok tostring private void set running test element el property iterator pi el property iterator while pi has next pi next set running version true setrunning testelement propertyiterator propertyiterator hasnext setrunningversion get next sample and its name private string next name generic controller c sampler s c next if s null return null return s get name nextname genericcontroller getname while blank previous sample ok should loop until false public void test blank prevok throws exception log info test blank prevok runtest prevok testblankprevok testblankprevok runtestprevok while last previous sample ok should loop until false public void test last prevok throws exception log info testlast prevok runtest prevok last testlastprevok testlastprevok runtestprevok while last previous sample ok should loop until false public void test other prevok throws exception log info test other prevok runtest prevok other testotherprevok testotherprevok runtestprevok private void runtest prevok string type throws exception generic controller controller new generic controller while controller while cont new while controller set last sample status true while cont set condition type while cont add test element new test sampler one while cont add test element new test sampler two while cont add test element new test sampler three controller add test element while cont controller add test element new test sampler four controller initialize assert equals one next name controller assert equals two next name controller assert equals three next name controller assert equals one next name controller assert equals two next name controller assert equals three next name controller assert equals one next name controller set last sample status false if type equals other while cont set condition false assert equals two next name controller assert equals three next name controller set last sample status true if type equals other while cont set condition other assert equals one next name controller assert equals two next name controller assert equals three next name controller set last sample status false if type equals other while cont set condition false assert equals four next name controller assert null next name controller set last sample status true if type equals other while cont set condition other assert equals one next name controller runtestprevok genericcontroller genericcontroller whilecontroller while_cont whilecontroller setlastsamplestatus while_cont setcondition while_cont addtestelement testsampler while_cont addtestelement testsampler while_cont addtestelement testsampler addtestelement while_cont addtestelement testsampler assertequals nextname assertequals nextname assertequals nextname assertequals nextname assertequals nextname assertequals nextname assertequals nextname setlastsamplestatus while_cont setcondition assertequals nextname assertequals nextname setlastsamplestatus while_cont setcondition assertequals nextname assertequals nextname assertequals nextname setlastsamplestatus while_cont setcondition assertequals nextname assertnull nextname setlastsamplestatus while_cont setcondition assertequals nextname while blank previous sample failed should run once public void test blank prev failed throws exception log info test blank prev failed generic controller controller new generic controller controller set running version true while controller while cont new while controller set last sample status false while cont set condition while cont add test element new test sampler one while cont add test element new test sampler two controller add test element while cont controller add test element new test sampler three controller initialize assert equals one next name controller assert equals two next name controller assert equals three next name controller assert null next name controller run entire test again assert equals one next name controller assert equals two next name controller assert equals three next name controller assert null next name controller testblankprevfailed testblankprevfailed genericcontroller genericcontroller setrunningversion whilecontroller while_cont whilecontroller setlastsamplestatus while_cont setcondition while_cont addtestelement testsampler while_cont addtestelement testsampler addtestelement while_cont addtestelement testsampler assertequals nextname assertequals nextname assertequals nextname assertnull nextname assertequals nextname assertequals nextname assertequals nextname assertnull nextname public void test variable1 throws exception generic controller controller new generic controller while controller while cont new while controller set last sample status false while cont set condition var jmvars put var value replacer vr new value replacer vr replace values while cont set running while cont controller add test element new test sampler before controller add test element while cont while cont add test element new test sampler one while cont add test element new test sampler two generic controller simple new generic controller while cont add test element simple simple add test element new test sampler three simple add test element new test sampler four controller add test element new test sampler after controller initialize for int i 1 i 3 i assert equals loop i before next name controller assert equals loop i one next name controller assert equals loop i two next name controller assert equals loop i three next name controller assert equals loop i four next name controller assert equals loop i after next name controller assert null loop i next name controller jmvars put var last should not enter the loop for int i 1 i 3 i assert equals loop i before next name controller assert equals loop i after next name controller assert null loop i next name controller jmvars put var for int i 1 i 3 i assert equals loop i before next name controller if i 1 assert equals loop i one next name controller assert equals loop i two next name controller assert equals loop i three next name controller jmvars put var last should not enter the loop next time assert equals loop i four next name controller assert equals loop i after next name controller assert null loop i next name controller testvariable1 genericcontroller genericcontroller whilecontroller while_cont whilecontroller setlastsamplestatus while_cont setcondition valuereplacer valuereplacer replacevalues while_cont setrunning while_cont addtestelement testsampler addtestelement while_cont while_cont addtestelement testsampler while_cont addtestelement testsampler genericcontroller genericcontroller while_cont addtestelement addtestelement testsampler addtestelement testsampler addtestelement testsampler assertequals nextname assertequals nextname assertequals nextname assertequals nextname assertequals nextname assertequals nextname assertnull nextname assertequals nextname assertequals nextname assertnull nextname assertequals nextname assertequals nextname assertequals nextname assertequals nextname assertequals nextname assertequals nextname assertnull nextname test with simple controller as first item public void test variable2 throws exception generic controller controller new generic controller while controller while cont new while controller set last sample status false while cont set condition var jmvars put var value replacer vr new value replacer vr replace values while cont set running while cont controller add test element new test sampler before controller add test element while cont generic controller simple new generic controller while cont add test element simple simple add test element new test sampler one simple add test element new test sampler two while cont add test element new test sampler three while cont add test element new test sampler four controller add test element new test sampler after controller initialize for int i 1 i 3 i assert equals loop i before next name controller assert equals loop i one next name controller assert equals loop i two next name controller assert equals loop i three next name controller assert equals loop i four next name controller assert equals loop i after next name controller assert null loop i next name controller jmvars put var last should not enter the loop for int i 1 i 3 i assert equals loop i before next name controller assert equals loop i after next name controller assert null loop i next name controller jmvars put var for int i 1 i 3 i assert equals loop i before next name controller if i 1 assert equals loop i one next name controller assert equals loop i two next name controller jmvars put var last should not enter the loop next time but should continue to the end of the loop assert equals loop i three next name controller assert equals loop i four next name controller assert equals loop i after next name controller assert null loop i next name controller simplecontroller testvariable2 genericcontroller genericcontroller whilecontroller while_cont whilecontroller setlastsamplestatus while_cont setcondition valuereplacer valuereplacer replacevalues while_cont setrunning while_cont addtestelement testsampler addtestelement while_cont genericcontroller genericcontroller while_cont addtestelement addtestelement testsampler addtestelement testsampler while_cont addtestelement testsampler while_cont addtestelement testsampler addtestelement testsampler assertequals nextname assertequals nextname assertequals nextname assertequals nextname assertequals nextname assertequals nextname assertnull nextname assertequals nextname assertequals nextname assertnull nextname assertequals nextname assertequals nextname assertequals nextname assertequals nextname assertequals nextname assertequals nextname assertnull nextname while last previous sample failed should not run public void testlast prev failed throws exception log info test last prev failed run test prev failed last testlastprevfailed testlastprevfailed runtestprevfailed while false previous sample failed should not run public void testfalse prev failed throws exception log info test false prev failed run test prev failed false testfalseprevfailed testfalseprevfailed runtestprevfailed private void run test prev failed string s throws exception generic controller controller new generic controller while controller while cont new while controller set last sample status false while cont set condition s while cont add test element new test sampler one while cont add test element new test sampler two controller add test element while cont controller add test element new test sampler three controller initialize assert equals three next name controller assert null next name controller assert equals three next name controller assert null next name controller runtestprevfailed genericcontroller genericcontroller whilecontroller while_cont whilecontroller setlastsamplestatus while_cont setcondition while_cont addtestelement testsampler while_cont addtestelement testsampler addtestelement while_cont addtestelement testsampler assertequals nextname assertnull nextname assertequals nextname assertnull nextname public void test last failed blank throws exception run test last failed testlastfailedblank runtestlastfailed public void test last failed last throws exception run test last failed last testlastfailedlast runtestlastfailed should behave the same for blank and last because success on input private void run test last failed string s throws exception generic controller controller new generic controller controller add test element new test sampler 1 while controller while cont new while controller controller add test element while cont while cont set condition s generic controller sub new generic controller while cont add test element sub sub add test element new test sampler 2 sub add test element new test sampler 3 controller add test element new test sampler 4 set last sample status true controller initialize assert equals 1 next name controller assert equals 2 next name controller set last sample status false assert equals 3 next name controller assert equals 4 next name controller assert null next name controller runtestlastfailed genericcontroller genericcontroller addtestelement testsampler whilecontroller while_cont whilecontroller addtestelement while_cont while_cont setcondition genericcontroller genericcontroller while_cont addtestelement addtestelement testsampler addtestelement testsampler addtestelement testsampler setlastsamplestatus assertequals nextname assertequals nextname setlastsamplestatus assertequals nextname assertequals nextname assertnull nextname tests for stack overflow bug 33954 public void test always failok throws exception run test always fail true should be ok testalwaysfailok runtestalwaysfail public void test always failbad throws exception run test always fail false testalwaysfailbad runtestalwaysfail private void run test always fail boolean other loop controller controller new loop controller controller set continue forever true controller set loops 1 while controller while cont new while controller set last sample status false while cont set condition false while cont add test element new test sampler one while cont add test element new test sampler two controller add test element while cont if other controller add test element new test sampler three controller initialize try if other assert equals three next name controller else assert null next name controller catch stack overflow error e e print stack trace fail e to string runtestalwaysfail loopcontroller loopcontroller setcontinueforever setloops whilecontroller while_cont whilecontroller setlastsamplestatus while_cont setcondition while_cont addtestelement testsampler while_cont addtestelement testsampler addtestelement while_cont addtestelement testsampler assertequals nextname assertnull nextname stackoverflowerror printstacktrace tostring private j text field suffix public param modifier gui init jtextfield _suffix parammodifiergui public string get label resource return html parameter mask non nls 1 getlabelresource html_parameter_mask public void configure test element el super configure el param modifier model param modifier el update gui model testelement parammodifier parammodifier updategui public test element create test element param modifier modifier new param modifier modify test element modifier return modifier testelement createtestelement parammodifier parammodifier modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element m configure test element m if m instanceof param modifier param modifier modifier param modifier m param mask mask modifier get mask mask set field name fieldname get text mask set prefix prefix get text mask set lower bound long parse long lowerbound get text mask set increment long parse long increment get text mask set upper bound long parse long upperbound get text mask set suffix suffix get text testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement parammodifier parammodifier parammodifier parammask getmask setfieldname _fieldname gettext setprefix _prefix gettext setlowerbound parselong _lowerbound gettext setincrement parselong _increment gettext setupperbound parselong _upperbound gettext setsuffix _suffix gettext implements j metergui component clear gui public void clear gui super clear gui fieldname set text non nls 1 prefix set text non nls 1 lowerbound set text zero upperbound set text 10 non nls 1 increment set text 1 non nls 1 suffix set text non nls 1 jmeterguicomponent cleargui cleargui cleargui _fieldname settext _prefix settext _lowerbound settext _upperbound settext _increment settext _suffix settext public void focus gained focus event evt focusgained focusevent public void focus lost focus event evt string name component evt get source get name if evt is temporary return else if name equals lowerbound check text field evt zero else if name equals upperbound check text field evt zero else if name equals increment check text field evt zero focuslost focusevent getsource getname istemporary checktextfield checktextfield checktextfield private void init called from ctor so must not be overridable set layout new border layout set border make border add make title panel border layout north add get parameter mask panel border layout center this updateui setlayout borderlayout setborder makeborder maketitlepanel borderlayout getparametermaskpanel borderlayout private void update gui param modifier model fieldname set text model get mask get field name prefix set text model get mask get prefix lowerbound set text long to string model get mask get lower bound upperbound set text long to string model get mask get upper bound increment set text long to string model get mask get increment suffix set text model get mask get suffix updategui parammodifier _fieldname settext getmask getfieldname _prefix settext getmask getprefix _lowerbound settext tostring getmask getlowerbound _upperbound settext tostring getmask getupperbound _increment settext tostring getmask getincrement _suffix settext getmask getsuffix private j panel create labeled field string label res name j text field field j label label new j label j meter utils get res string label res name label set label for field j panel panel new j panel new border layout panel add label border layout north panel add field border layout center return panel jpanel createlabeledfield labelresname jtextfield jlabel jlabel jmeterutils getresstring labelresname setlabelfor jpanel jpanel borderlayout borderlayout borderlayout private j panel get parameter mask panel horizontal panel panel new horizontal panel 10 horizontal panel top alignment panel set border border factory create titled border border factory create etched border j meter utils get res string html parameter mask non nls 1 fieldname new j text field 10 fieldname set name name panel add create labeled field name fieldname non nls 1 resource name prefix new j text field 5 prefix set name prefix panel add create labeled field id prefix prefix non nls 1 resource name lowerbound new j text field zero 5 lowerbound add focus listener this lowerbound set name lowerbound panel add create labeled field lower bound lowerbound non nls 1 resource name upperbound new j text field 10 5 upperbound add focus listener this upperbound set name upperbound panel add create labeled field upper bound upperbound non nls 1 resource name increment new j text field 1 3 increment add focus listener this increment set name increment panel add create labeled field increment increment non nls 1 resource name suffix new j text field 5 suffix set name suffix panel add create labeled field id suffix suffix non nls 1 resource name j panel main panel new j panel new border layout main panel add panel border layout north return main panel jpanel getparametermaskpanel horizontalpanel horizontalpanel horizontalpanel top_alignment setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring html_parameter_mask _fieldname jtextfield _fieldname setname createlabeledfield _fieldname _prefix jtextfield _prefix setname createlabeledfield id_prefix _prefix _lowerbound jtextfield _lowerbound addfocuslistener _lowerbound setname createlabeledfield lower_bound _lowerbound _upperbound jtextfield _upperbound addfocuslistener _upperbound setname createlabeledfield upper_bound _upperbound _increment jtextfield _increment addfocuslistener _increment setname createlabeledfield _increment _suffix jtextfield _suffix setname createlabeledfield id_suffix _suffix jpanel mainpanel jpanel borderlayout mainpanel borderlayout mainpanel used to validate a text field that requires a code long code input returns the code long code if valid else creates a pop up error message and throws a number format exception return the number entered in the text field private long check text field focus event evt string default value j text field temp j text field evt get source boolean pass true long long val 0 try long val long parse long temp get text catch number format exception err j option pane show message dialog this this field must have a long value value required j option pane error message temp set text default value temp request focus return long val numberformatexception checktextfield focusevent defaultvalue jtextfield jtextfield getsource longval longval parselong gettext numberformatexception joptionpane showmessagedialog joptionpane error_message settext defaultvalue requestfocus longval param properties to save the properties to save to set public void set save config sample save configuration properties to save this save config properties to save propertiestosave propertiestosave setsaveconfig samplesaveconfiguration propertiestosave saveconfig propertiestosave public sample save configuration get save config return save config samplesaveconfiguration getsaveconfig saveconfig private static method init nano time method try return system class get method nano time null catch no such method exception e return null initnanotimemethod getmethod nanotime nosuchmethodexception private static boolean have nano time return nano time method null havenanotime nanotimemethod private static long nano time long result null try result long nano time method invoke null null catch illegal access exception e throw new runtime exception e catch invocation target exception e throw new runtime exception e return result long value nanotime nanotimemethod illegalaccessexception runtimeexception invocationtargetexception runtimeexception longvalue public sample result time 0 sampleresult construct a parent result for an already existing result essentially cloning it param res existing sample result public sample result sample result res todo why not just copy all the fields do we need the calculations that some of the set methods perform todo why are the following not copied assertion results bytes idle time latency parent pause time result file name sample count sampler data save config stop test stop thread sub results thread name set start time res get start time set end time res get start time was set elapsed 0 which is the same as set start time set end time now set sample label res get sample label set request headers res get request headers set response data res get response data set response code res get response code set successful res is successful set response message res get response message set data type res get data type set response headers res get response headers set content type res get content type set data encoding res get data encoding no default seturl res geturl set group threads res get group threads set all threads res get all threads add sub result res this will add res get time to get time sampleresult sampleresult assertionresults idletime pausetime resultfilename samplecount samplerdata saveconfig stoptest stopthread subresults threadname setstarttime getstarttime setendtime getstarttime setelapsed setstarttime setendtime setsamplelabel getsamplelabel setrequestheaders getrequestheaders setresponsedata getresponsedata setresponsecode getresponsecode setsuccessful issuccessful setresponsemessage getresponsemessage setdatatype getdatatype setresponseheaders getresponseheaders setcontenttype getcontenttype setdataencoding getdataencodingnodefault setgroupthreads getgroupthreads setallthreads getallthreads addsubresult gettime gettime public boolean is stamped at start return start time stamp isstampedatstart starttimestamp create a sample with a specific elapsed time but don t allow the times to be changed later only used by http sample result param elapsed time param atend create the sample finishing now else starting now protected sample result long elapsed boolean atend long now current time in ms if atend set times now elapsed now else set times now now elapsed httpsampleresult sampleresult currenttimeinms settimes settimes create a sample with specific start and end times for test purposes but don t allow the times to be changed later used by stat visualizer model test param start start time param end end time public static sample result create test sample long start long end sample result res new sample result res set start time start res set end time end return res statvisualizermodel sampleresult createtestsample sampleresult sampleresult setstarttime setendtime create a sample with a specific elapsed time for test purposes but don t allow the times to be changed later param elapsed desired elapsed time public static sample result create test sample long elapsed long now current time in ms return create test sample now now elapsed sampleresult createtestsample currenttimeinms createtestsample allow users to create a sample with specific timestamp and elapsed times for cloning purposes but don t allow the times to be changed later currently used by old save service csv save service and statistical sample result param stamp this may be a start time or an end time param elapsed public sample result long stamp long elapsed stamp and time stamp elapsed oldsaveservice csvsaveservice statisticalsampleresult sampleresult stampandtime private static long sample ns clock in ms return nano time 1000000 samplensclockinms nanotime helper method to get 1 ms resolution timing public static long current time in ms if have nano time long elapsed in ms sample ns clock in ms reference time ns clock return reference time ms clock elapsed in ms else return system current time millis currenttimeinms havenanotime elapsedinms samplensclockinms referencetimensclock referencetimemsclock elapsedinms currenttimemillis helper method to maintain timestamp relationships private void stamp and time long stamp long elapsed if start time stamp start time stamp end time stamp elapsed else start time stamp elapsed end time stamp time stamp stamp time elapsed stampandtime starttimestamp starttime endtime starttime endtime timestamp public void set stamp and time long stamp long elapsed if start time 0 end time 0 throw new runtime exception calling set stamp and time after start end times have been set stamp and time stamp elapsed setstampandtime starttime endtime runtimeexception setstampandtime stampandtime method to set the elapsed time for a sample retained for backward compatibility with 3rd party add ons it is assumed that the method is only called at the end of a sample and that time stamps are end times also used by sample result converter when creating results from files must not be used in conjunction with sample start end deprecated use sample start and sample end instead param elapsed time in milliseconds public void set time long elapsed if start time 0 end time 0 throw new runtime exception calling set time after start end times have been set long now current time in ms set times now elapsed now timestamps sampleresultconverter samplestart samplestart sampleend settime starttime endtime runtimeexception settime currenttimeinms settimes set the marked flag to show that the result has been written to the file param filename return true if the result was previously marked public synchronized boolean mark file string filename return files add filename markfile public string get response code return response code getresponsecode responsecode set response code to ok i e 200 public void set response codeok response code ok setresponsecodeok responsecode public void set response code string code response code code setresponsecode responsecode public boolean is response codeok return response code equals ok isresponsecodeok responsecode return response code equals ok public string get response message return response message responsecode getresponsemessage responsemessage public void set response message string msg response message msg setresponsemessage responsemessage public void set response messageok response message ok non nls 1 setresponsemessageok responsemessage public string get thread name return thread name getthreadname threadname public void set thread name string thread name this thread name thread name setthreadname threadname threadname threadname get the sample timestamp which may be either the start time or the end time see get start time see get end time return time stamp in milliseconds public long get time stamp return time stamp getstarttime getendtime timestamp gettimestamp timestamp public string get sample label return label getsamplelabel get the sample label for use in summary reports etc param include group whether to include the thread group name return the label public string get sample label boolean include group if include group string buffer sb new string buffer thread name substring 0 thread name last index of non nls 1 return sb append append label to string non nls 1 return label includegroup getsamplelabel includegroup includegroup stringbuffer stringbuffer threadname threadname lastindexof tostring public void set sample label string label this label label setsamplelabel public void add assertion result assertion result assert result if assertion results null assertion results new array list assertion results add assert result addassertionresult assertionresult assertresult assertionresults assertionresults arraylist assertionresults assertresult gets the assertion results associated with this sample return an array containing the assertion results for this sample returns empty array if there are no assertion results public assertion result get assertion results if assertion results null return empty ar return assertion result assertion results to array new assertion result 0 assertionresult getassertionresults assertionresults empty_ar assertionresult assertionresults toarray assertionresult public void add sub result sample result sub result string tn get thread name if tn length 0 tn thread current thread get name todo do this more efficiently this set thread name tn sub result set thread name tn if sub results null sub results new array list sub results add sub result extend the time to the end of the added sample set end time math max get end time sub result get end time include the byte count for the added sample set bytes get bytes sub result get bytes sub result set parent this addsubresult sampleresult subresult getthreadname currentthread getname setthreadname subresult setthreadname subresults subresults arraylist subresults subresult setendtime getendtime subresult getendtime setbytes getbytes subresult getbytes subresult setparent add a subresult read from a results file as for add sub result except that the fields don t need to be accumulated param sub result public void store sub result sample result sub result if sub results null sub results new array list sub results add sub result sub result set parent this addsubresult subresult storesubresult sampleresult subresult subresults subresults arraylist subresults subresult subresult setparent gets the subresults associated with this sample return an array containing the subresults for this sample returns an empty array if there are no subresults public sample result get sub results if sub results null return empty sr return sample result sub results to array new sample result 0 sampleresult getsubresults subresults empty_sr sampleresult subresults toarray sampleresult public void configure configuration info time info get attribute as long total time 0l getattributeaslong total_time sets the response data attribute of the sample result object if the parameter is null then the response data is set to an empty byte array this ensures that get response data can never be null param response the new response data value public void set response data byte response response data response null empty ba response responsedata sampleresult responsedata getresponsedata responsedata setresponsedata responsedata empty_ba sets the response data attribute of the sample result object should only be called after setting the data encoding if necessary param response the new response data value string deprecated only intended for use from bean shell code public void set response data string response try response data response get bytes get data encoding with default catch unsupported encoding exception e log warn could not convert string using default encoding e get localized message response data response get bytes responsedata sampleresult dataencoding responsedata beanshell setresponsedata responsedata getbytes getdataencodingwithdefault unsupportedencodingexception getlocalizedmessage responsedata getbytes gets the response data attribute of the sample result object p note that some samplers may not store all the data in which case get response data length will be incorrect instead always use link get bytes to obtain the sample result byte count p return the response data value cannot be null public byte get response data return response data responsedata sampleresult getresponsedata getbytes responsedata getresponsedata responsedata gets the response data of the sample result object as a string return the response data value as a string converted according to the encoding public string get response data as string try return new string response data get data encoding with default catch unsupported encoding exception e log warn using platform default as get data encoding with default caused e return new string response data responsedata sampleresult responsedata getresponsedataasstring responsedata getdataencodingwithdefault unsupportedencodingexception getdataencodingwithdefault responsedata public void set sampler data string s sampler data s setsamplerdata samplerdata public string get sampler data return sampler data getsamplerdata samplerdata get the time it took this sample to occur return elapsed time in milliseonds public long get time return time gettime public boolean is successful return success issuccessful public void set data type string data type this data type data type setdatatype datatype datatype datatype public string get data type return data type getdatatype datatype extract and save the data encoding and data type from the parameter provided does not save the full content type see set content type string which should be used to save the full content type string param ct content type may be null public void set encoding and type string ct if ct null extract charset and store as data encoding n b the meta tag meta http equiv content type content text html charset foobar is now processed by http sample result get data encoding with default final string cs pfx charset non nls 1 int cset ct to lower case java util locale english index of cs pfx if cset 0 todo assumes charset is not followed by anything else string char set ct substring cset cs pfx length check for quoted string if char set starts with non nls 1 set data encoding char set substring 1 char set length 1 remove quotes else set data encoding char set if is binary type ct set data type binary else set data type text dataencoding datatype setcontenttype setencodingandtype dataencoding httpsampleresult getdataencodingwithdefault cs_pfx tolowercase indexof cs_pfx charset cs_pfx charset startswith setdataencoding charset charset setdataencoding charset isbinarytype setdatatype setdatatype private static boolean is binary type string ct for int i 0 i binary types length i if ct starts with binary types i return true return false isbinarytype binary_types startswith binary_types sets the successful attribute of the sample result object param success the new successful value public void set successful boolean success this success success sampleresult setsuccessful returns the display name return display name of this sample result public string to string return get sample label tostring getsamplelabel returns the data encoding or the default if no data encoding was provided deprecated use get data encoding with default or get data encoding no default as needed public string get data encoding if data encoding null return data encoding return default encoding dataencoding dataencoding getdataencodingwithdefault getdataencodingnodefault getdataencoding dataencoding dataencoding default_encoding returns the data encoding or the default if no data encoding was provided return the value of the data encoding or default encoding public string get data encoding with default if data encoding null data encoding length 0 return data encoding return default encoding dataencoding dataencoding dataencoding default_encoding getdataencodingwithdefault dataencoding dataencoding dataencoding default_encoding returns the data encoding may be null or the empty string return the value of the data encoding public string get data encoding no default return data encoding dataencoding dataencoding getdataencodingnodefault dataencoding sets the data encoding param data encoding the data encoding to set e g iso 8895 1 utf 8 public void set data encoding string data encoding this data encoding data encoding dataencoding dataencoding dataencoding setdataencoding dataencoding dataencoding dataencoding return whether to stop the test public boolean is stop test return stop test isstoptest stoptest return whether to stop the test now public boolean is stop test now return stop test now isstoptestnow stoptestnow return whether to stop this thread public boolean is stop thread return stop thread isstopthread stopthread public void set stop test boolean b stop test b setstoptest stoptest public void set stop test now boolean b stop test now b setstoptestnow stoptestnow public void set stop thread boolean b stop thread b setstopthread stopthread return the request headers public string get request headers return request headers getrequestheaders requestheaders return the response headers public string get response headers return response headers getresponseheaders responseheaders param string request headers public void set request headers string string request headers string setrequestheaders requestheaders param string response headers public void set response headers string string response headers string setresponseheaders responseheaders return the full content type e g text html charset utf 8 public string get content type return content type getcontenttype contenttype get the media type from the content type return the media type e g text html without charset if any public string get media type return j orphan utils trim content type to lower case java util locale english getmediatype jorphanutils contenttype tolowercase stores the content type string e g text xml charset utf 8 see set encoding and type string which can be used to extract the charset param string public void set content type string string content type string setencodingandtype setcontenttype contenttype return idle time public long get idle time return idle time idletime getidletime idletime return the end time public long get end time return end time getendtime endtime return the start time public long get start time return start time getstarttime starttime protected final void set start time long start start time start if start time stamp time stamp start time setstarttime starttime starttimestamp timestamp starttime protected void set end time long end end time end if start time stamp time stamp end time if start time 0 log error set end time must be called after set start time new throwable invalid call sequence todo should this throw an error else time end time start time idle time setendtime endtime starttimestamp timestamp endtime starttime setendtime setstarttime endtime starttime idletime private void set times long start long end set start time start set end time end settimes setstarttime setendtime record the start time of a sample public void sample start if start time 0 set start time current time in ms else log error sample start called twice new throwable invalid call sequence samplestart starttime setstarttime currenttimeinms samplestart record the end time of a sample and calculate the elapsed time public void sample end if end time 0 set end time current time in ms else log error sample end called twice new throwable invalid call sequence sampleend endtime setendtime currenttimeinms sampleend pause a sample public void sample pause if pause time 0 log error sample pause called twice new throwable invalid call sequence pause time current time in ms samplepause pausetime samplepause pausetime currenttimeinms resume a sample public void sample resume if pause time 0 log error sample resume without sample pause new throwable invalid call sequence idle time current time in ms pause time pause time 0 sampleresume pausetime sampleresume samplepause idletime currenttimeinms pausetime pausetime when a sampler is working as a monitor param monitor public void set monitor boolean monitor is monitor monitor setmonitor ismonitor if the sampler is a monitor method will return true return true if the sampler is a monitor public boolean is monitor return is monitor ismonitor ismonitor for the jms sampler it can perform multiple samples for greater degree of accuracy param count public void set sample count int count sample count count setsamplecount samplecount return the sample count by default the value is 1 return the sample count public int get sample count return sample count getsamplecount samplecount returns the count of errors return 0 or 1 if the sample failed public int get error count return success 0 1 geterrorcount public void set error count int i for reading from csv files ignored currently seterrorcount in the event the sampler does want to pass back the actual contents we still want to calculate the throughput the bytes is the bytes of the response data param length public void set bytes int length bytes length setbytes return the bytes returned by the response return byte count public int get bytes return bytes 0 response data length bytes getbytes responsedata return returns the latency public long get latency return latency getlatency set the time to the first response public void latency end latency current time in ms start time idle time latencyend currenttimeinms starttime idletime this is only intended for use by sample result converter param latency the latency to set public void set latency long latency this latency latency sampleresultconverter setlatency this is only intended for use by sample result converter param time stamp the time stamp to set public void set time stamp long time stamp this time stamp time stamp sampleresultconverter timestamp timestamp settimestamp timestamp timestamp timestamp private url location public void seturl url location this location location public url geturl return location get a string representation of the url if defined return external form of url or empty string if url is null public string get url as string return location null location to external form externalform geturlasstring toexternalform return returns the parent public sample result get parent return parent sampleresult getparent param parent the parent to set public void set parent sample result parent this parent parent setparent sampleresult public string get result file name return result file name getresultfilename resultfilename public void set result file name string result file name this result file name result file name setresultfilename resultfilename resultfilename resultfilename public int get group threads return group threads getgroupthreads groupthreads public void set group threads int n this group threads n setgroupthreads groupthreads public int get all threads return all threads getallthreads allthreads public void set all threads int n this all threads n setallthreads allthreads public class random order controller gui extends logic controller gui public string get label resource return random order control title non nls 1 randomordercontrollergui logiccontrollergui getlabelresource random_order_control_title public test element create test element random order controller ic new random order controller modify test element ic return ic testelement createtestelement randomordercontroller randomordercontroller modifytestelement see org apache jmeter gui j metergui component modify test element org apache jmeter testelement test element public void modify test element test element ic configure test element ic jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement public test action gui super target test action thread action test action pause duration string non nls 1 init testactiongui testaction testaction durationstring public string get label resource return test action title non nls 1 getlabelresource test_action_title public void configure test element element super configure element test action ta test action element target ta get target if target test action thread target box set selected item thread target else target box set selected item test target action ta get action if action test action pause pause button set selected true else if action test action stop now stop now button set selected true else stop button set selected true duration string ta get duration as string duration field set text duration string testelement testaction testaction gettarget testaction targetbox setselecteditem threadtarget targetbox setselecteditem testtarget getaction testaction pausebutton setselected testaction stop_now stopnowbutton setselected stopbutton setselected durationstring getdurationasstring durationfield settext durationstring see org apache jmeter gui j metergui component create test element public test element create test element test action ta new test action modify test element ta return ta jmeterguicomponent createtestelement testelement createtestelement testaction testaction modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element element super configure test element element test action ta test action element ta set action action ta set target target ta set duration duration string testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement testaction testaction setaction settarget setduration durationstring implements j metergui component clear gui public void clear gui super clear gui target box set selected index 0 duration string non nls 1 duration field set text non nls 1 pause button set selected true action test action pause target test action thread jmeterguicomponent cleargui cleargui cleargui targetbox setselectedindex durationstring durationfield settext pausebutton setselected testaction testaction private void init set layout new vertical layout 5 vertical layout both vertical layout top set border make border add make title panel target horizontal panel target panel new horizontal panel target panel add new j label target label default combo box model target model new default combo box model target model add element thread target target model add element test target target box new j combo box target model target box add action listener new action listener public void action performed action event e if string target box get selected item equals thread target target test action thread else target test action test target panel add target box add target panel action horizontal panel action panel new horizontal panel button group action buttons new button group pause button new j radio button pause action true pause button add change listener new change listener public void state changed change event e if pause button is selected action test action pause duration field set enabled true stop button new j radio button stop action false stop button add change listener new change listener public void state changed change event e if stop button is selected action test action stop duration field set enabled false stop now button new j radio button stop now action false stop now button add change listener new change listener public void state changed change event e if stop now button is selected action test action stop now duration field set enabled false action buttons add pause button action buttons add stop button action buttons add stop now button action panel add new j label action label action panel add pause button action panel add stop button action panel add stop now button add action panel duration horizontal panel duration panel new horizontal panel duration field new j text field 15 duration field set text duration field add focus listener new focus listener public void focus lost focus event e duration string duration field get text public void focus gained focus event e duration panel add new j label duration label duration panel add duration field add duration panel setlayout verticallayout verticallayout verticallayout setborder makeborder maketitlepanel horizontalpanel targetpanel horizontalpanel targetpanel jlabel targetlabel defaultcomboboxmodel targetmodel defaultcomboboxmodel targetmodel addelement threadtarget targetmodel addelement testtarget targetbox jcombobox targetmodel targetbox addactionlistener actionlistener actionperformed actionevent targetbox getselecteditem threadtarget testaction testaction targetpanel targetbox targetpanel horizontalpanel actionpanel horizontalpanel buttongroup actionbuttons buttongroup pausebutton jradiobutton pauseaction pausebutton addchangelistener changelistener statechanged changeevent pausebutton isselected testaction durationfield setenabled stopbutton jradiobutton stopaction stopbutton addchangelistener changelistener statechanged changeevent stopbutton isselected testaction durationfield setenabled stopnowbutton jradiobutton stopnowaction stopnowbutton addchangelistener changelistener statechanged changeevent stopnowbutton isselected testaction stop_now durationfield setenabled actionbuttons pausebutton actionbuttons stopbutton actionbuttons stopnowbutton actionpanel jlabel actionlabel actionpanel pausebutton actionpanel stopbutton actionpanel stopnowbutton actionpanel horizontalpanel durationpanel horizontalpanel durationfield jtextfield durationfield settext durationfield addfocuslistener focuslistener focuslost focusevent durationstring durationfield gettext focusgained focusevent durationpanel jlabel durationlabel durationpanel durationfield durationpanel target box add action listener new action listener public void action performed action event e if string target box get selected item equals thread target target test action thread else target test action test targetbox addactionlistener actionlistener actionperformed actionevent targetbox getselecteditem threadtarget testaction testaction pause button add change listener new change listener public void state changed change event e if pause button is selected action test action pause duration field set enabled true pausebutton addchangelistener changelistener statechanged changeevent pausebutton isselected testaction durationfield setenabled stop button add change listener new change listener public void state changed change event e if stop button is selected action test action stop duration field set enabled false stopbutton addchangelistener changelistener statechanged changeevent stopbutton isselected testaction durationfield setenabled stop now button add change listener new change listener public void state changed change event e if stop now button is selected action test action stop now duration field set enabled false stopnowbutton addchangelistener changelistener statechanged changeevent stopnowbutton isselected testaction stop_now durationfield setenabled duration field set text duration field add focus listener new focus listener public void focus lost focus event e duration string duration field get text durationfield settext durationfield addfocuslistener focuslistener focuslost focusevent durationstring durationfield gettext public void focus gained focus event e focusgained focusevent interface has name string get name hasname getname interface has string string get string string s hasstring getstring class test1 implements has name private final string name public test1 this hasname this public test1 string s name s name s public string get name return name getname return name public string get string string s return s getstring class test1a extends test1 test1a super 1a super 1a test1a string s super 1a s super 1a s public string get name return super get name getname getname static class test2 implements has name has string private final string name public test2 this hasname hasstring this public test2 string s name s name s public string get name return name getname return name public string get string string s return s getstring public test functor string arg0 super arg0 testfunctor public void set up logging manager set priority fatal error logging manager remove prefix functor class get name setup loggingmanager setpriority fatal_error loggingmanager removeprefix getname public void test name throws exception functor f1 new functor get name functor f2 new functor get name functor f1a new functor get name test1 t1 new test1 t1 test2 t2 new test2 t2 test1a t1a new test1a aa assert equals t1 f1 invoke t1 assert equals t1 f1 invoke try f1 invoke t2 fail should have generated error catch j meter error e assert equals t2 f2 invoke t2 assert equals t2 f2 invoke assert equals 1a aa f1a invoke t1a assert equals 1a aa f1a invoke try f1a invoke t1 can t call invoke using super class fail should have generated error catch j meter error e ok currently to invoke using sub class assert equals 1a aa f1 invoke t1a assert equals 1a aa f1 invoke n b returns different result from before testname getname getname getname assertequals assertequals jmetererror assertequals assertequals assertequals assertequals jmetererror assertequals assertequals public void test name types throws exception functor f new functor get string new class string class functor f2 new functor get string args will be provided later test1 t1 new test1 t1 assert equals x1 f invoke t1 new string x1 try assert equals x1 f invoke t1 fail should have generated an exception catch j meter error ok assert equals x2 f2 invoke t1 new string x2 try assert equals x2 f2 invoke t1 fail should have generated an exception catch j meter error ok testnametypes getstring getstring assertequals assertequals jmetererror assertequals assertequals jmetererror public void test object name throws exception test1 t1 new test1 t1 test2 t2 new test2 t2 functor f1 new functor t1 get name assert equals t1 f1 invoke t1 assert equals t1 f1 invoke t2 should use original object testobjectname getname assertequals assertequals check how class definition behaves public void test class throws exception test1 t1 new test1 t1 test1 t1a new test1a t1a test2 t2 new test2 t2 functor f1 new functor has name class get name assert equals t1 f1 invoke t1 assert equals 1a t1a f1 invoke t1a assert equals t2 f1 invoke t2 try f1 invoke fail should have failed catch illegal state exception ok functor f2 new functor has string class get string assert equals xyz f2 invoke t2 new string xyz try f2 invoke t1 new string xyz fail should have failed catch j meter error ok functor f3 new functor t2 get string assert equals xyz f3 invoke t2 new object xyz properties p new properties p put name value functor fk new functor map entry class get key functor fv new functor map entry class get value object o p entry set iterator next assert equals name fk invoke o assert equals value fv invoke o testclass hasname getname assertequals assertequals assertequals illegalstateexception hasstring getstring assertequals jmetererror getstring assertequals getkey getvalue entryset assertequals assertequals public void test bad parameters throws exception try new functor null fail should have generated illegal argument exception catch illegal argument exception ok try new functor null new class fail should have generated illegal argument exception catch illegal argument exception ok try new functor null new object fail should have generated illegal argument exception catch illegal argument exception ok try new functor string class null fail should have generated illegal argument exception catch illegal argument exception ok try new functor new object null fail should have generated illegal argument exception catch illegal argument exception ok try new functor new object null new class fail should have generated illegal argument exception catch illegal argument exception ok try new functor new object null new object fail should have generated illegal argument exception catch illegal argument exception ok testbadparameters illegalargumentexception illegalargumentexception illegalargumentexception illegalargumentexception illegalargumentexception illegalargumentexception illegalargumentexception illegalargumentexception illegalargumentexception illegalargumentexception illegalargumentexception illegalargumentexception illegalargumentexception illegalargumentexception public void test illegal state throws exception functor f new functor method try f invoke fail should have generated illegal state exception catch illegal state exception ok try f invoke new object fail should have generated illegal state exception catch illegal state exception ok testillegalstate illegalstateexception illegalstateexception illegalstateexception illegalstateexception public class rate renderer extends number renderer public rate renderer string format super format raterenderer numberrenderer raterenderer public void set value object value if value null value instanceof double set text n a todo should this just call super return double rate double value double value if rate double max value set text n a todo should this just call super return string unit sec if rate 1 0 rate 60 0 unit min if rate 1 0 rate 60 0 unit hour set text formatter format rate unit setvalue settext doublevalue max_value settext settext j meter utils get prop default jmeter httpsampler http sampler java non nls 1 private http sampler factory not intended to be instantiated jmeterutils getpropdefault http_sampler_java httpsamplerfactory create a new instance of the default sampler return instance of default sampler public static http sampler base new instance return new instance default classname httpsamplerbase newinstance newinstance default_classname create a new instance of the required sampler type param alias http sampler or http sampler apache return the appropriate sampler throws unsupported operation exception if alias is not recognised public static http sampler base new instance string alias if alias length 0 alias default classname if alias equals http sampler java return new http sampler if alias equals http sampler apache return new http sampler2 throw new unsupported operation exception cannot create class alias http_sampler http_sampler_apache unsupportedoperationexception httpsamplerbase newinstance default_classname http_sampler_java httpsampler http_sampler_apache httpsampler2 unsupportedoperationexception dummy for j unit test public test beangui log warn constructor only for use in testing non nls 1 test bean class null customizer class null junit testbeangui testbeanclass customizerclass public test beangui class test bean class super log debug testing class test bean class get name a quick verification just in case if test bean class is assignable from test bean class error e new error log error this should never happen e throw e programming error bail out this test bean class test bean class get the bean info try bean info introspector get bean info test bean class catch introspection exception e log error can t get bean info for test bean class get name e throw new error e to string programming error don t continue customizer class bean info get bean descriptor get customizer class creation of the customizer and gui initialization is delayed until the first configure call we don t need all that just to find out the static label menu categories etc initialized false testbeangui testbeanclass testbeanclass getname testbean isassignablefrom testbeanclass testbeanclass testbeanclass beaninfo beaninfo getbeaninfo testbeanclass introspectionexception beaninfo testbeanclass getname tostring customizerclass beaninfo getbeandescriptor getcustomizerclass private customizer create customizer try return customizer customizer class new instance catch instantiation exception e log error could not instantiate customizer of class customizer class e throw new error e to string catch illegal access exception e log error could not instantiate customizer of class customizer class e throw new error e to string createcustomizer customizerclass newinstance instantiationexception customizerclass tostring illegalaccessexception customizerclass tostring public string get static label if bean info null return null non nls 1 return bean info get bean descriptor get display name getstaticlabel beaninfo beaninfo getbeandescriptor getdisplayname public test element create test element try test element element test element test bean class new instance configure element super clear set name enabled modify test element element put the default values back into the new element return element catch instantiation exception e log error can t create test element e throw new error e to string programming error don t continue catch illegal access exception e log error can t create test element e throw new error e to string programming error don t continue testelement createtestelement testelement testelement testbeanclass newinstance modifytestelement instantiationexception tostring illegalaccessexception tostring public void modify test element test element element fetch data from screen fields if customizer instanceof generic test bean customizer generic test bean customizer gtbc generic test bean customizer customizer gtbc save gui fields configure test element element copy all property values from the map into the element property descriptor props bean info get property descriptors for int i 0 i props length i string name props i get name object value property map get name log debug modify name to value if value null object value not un defined props i get value bean info support not undefined if value not un defined null boolean value not un defined boolean value set property in element element name props i get value bean info support default else element remove property name else set property in element element name property map get name modifytestelement testelement generictestbeancustomizer generictestbeancustomizer generictestbeancustomizer saveguifields configuretestelement propertydescriptor beaninfo getpropertydescriptors getname propertymap valuenotundefined getvalue beaninfosupport not_undefined valuenotundefined valuenotundefined booleanvalue setpropertyinelement getvalue beaninfosupport removeproperty setpropertyinelement propertymap param element param name private void set property in element test element element string name object value j meter property jprop abstract property create property value jprop set name name element set property jprop setpropertyinelement testelement jmeterproperty abstractproperty createproperty setname setproperty public j popup menu create popup menu if timer class is assignable from test bean class return menu factory get default timer menu else if sampler class is assignable from test bean class return menu factory get default sampler menu else if config test element class is assignable from test bean class return menu factory get default config element menu else if assertion class is assignable from test bean class return menu factory get default assertion menu else if post processor class is assignable from test bean class pre processor class is assignable from test bean class return menu factory get default extractor menu else if visualizer class is assignable from test bean class return menu factory get default visualizer menu else return menu factory get default controller menu jpopupmenu createpopupmenu isassignablefrom testbeanclass menufactory getdefaulttimermenu isassignablefrom testbeanclass menufactory getdefaultsamplermenu configtestelement isassignablefrom testbeanclass menufactory getdefaultconfigelementmenu isassignablefrom testbeanclass menufactory getdefaultassertionmenu postprocessor isassignablefrom testbeanclass preprocessor isassignablefrom testbeanclass menufactory getdefaultextractormenu isassignablefrom testbeanclass menufactory getdefaultvisualizermenu menufactory getdefaultcontrollermenu public void configure test element element if initialized init clear gui super configure element copy all property values into the map for property iterator jprops element property iterator jprops has next j meter property jprop jprops next property map put jprop get name jprop get object value if customizer null customizer set object property map else if initialized remove customizer index in panel customizer c customizer customizers get element if c null c create customizer c set object property map customizers put element c add component c border layout center initialized true testelement cleargui propertyiterator propertyiterator hasnext jmeterproperty propertymap getname getobjectvalue setobject propertymap customizerindexinpanel createcustomizer setobject propertymap borderlayout public collection get menu categories list menu categories new linked list bean descriptor bd bean info get bean descriptor we don t want to show expert beans in the menus unless we re in expert mode if bd is expert j meter utils is expert mode return null int matches 0 how many classes can we assign from todo there must be a nicer way if assertion class is assignable from test bean class menu categories add menu factory assertions bd set value test element gui class abstract assertion gui class get name matches if config element class is assignable from test bean class menu categories add menu factory config elements bd set value test element gui class abstract config gui class get name matches if controller class is assignable from test bean class menu categories add menu factory controllers bd set value test element gui class abstract controller gui class get name matches if visualizer class is assignable from test bean class menu categories add menu factory listeners bd set value test element gui class abstract visualizer class get name matches if post processor class is assignable from test bean class menu categories add menu factory post processors bd set value test element gui class abstract post processor gui class get name matches if pre processor class is assignable from test bean class matches menu categories add menu factory pre processors bd set value test element gui class abstract pre processor gui class get name if sampler class is assignable from test bean class matches menu categories add menu factory samplers bd set value test element gui class abstract sampler gui class get name if timer class is assignable from test bean class matches menu categories add menu factory timers bd set value test element gui class abstract timer gui class get name if matches 0 log error could not assign gui class to test bean class get name else if matches 1 may be impossible but no harm in checking log error more than 1 gui class found for test bean class get name return menu categories getmenucategories menucategories linkedlist beandescriptor beaninfo getbeandescriptor isexpert jmeterutils isexpertmode isassignablefrom testbeanclass menucategories menufactory setvalue testelement gui_class abstractassertiongui getname configelement isassignablefrom testbeanclass menucategories menufactory config_elements setvalue testelement gui_class abstractconfiggui getname isassignablefrom testbeanclass menucategories menufactory setvalue testelement gui_class abstractcontrollergui getname isassignablefrom testbeanclass menucategories menufactory setvalue testelement gui_class abstractvisualizer getname postprocessor isassignablefrom testbeanclass menucategories menufactory post_processors setvalue testelement gui_class abstractpostprocessorgui getname preprocessor isassignablefrom testbeanclass menucategories menufactory pre_processors setvalue testelement gui_class abstractpreprocessorgui getname isassignablefrom testbeanclass menucategories menufactory setvalue testelement gui_class abstractsamplergui getname isassignablefrom testbeanclass menucategories menufactory setvalue testelement gui_class abstracttimergui getname testbeanclass getname testbeanclass getname menucategories private void init set layout new border layout 0 5 set border make border add make title panel border layout north customizer index in panel get component count if customizer class null customizer new generic test bean customizer bean info else if shared customizer class is assignable from customizer class customizer create customizer if customizer null add component customizer border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout customizerindexinpanel getcomponentcount customizerclass generictestbeancustomizer beaninfo sharedcustomizer isassignablefrom customizerclass createcustomizer borderlayout see org apache jmeter gui j metergui component get label resource public string get label resource see get static label return null jmeterguicomponent getlabelresource getlabelresource getstaticlabel public void clear gui super clear gui if customizer instanceof generic test bean customizer generic test bean customizer gtbc generic test bean customizer customizer gtbc clear gui fields cleargui cleargui generictestbeancustomizer generictestbeancustomizer generictestbeancustomizer clearguifields public report load super reportload public set get action names return commands getactionnames public void do action action event e boolean merging e get action command equals merge if merging report action router get instance do action now new action event e get source e getid close j file chooser chooser report file dialoger prompt to open file new string jmr if chooser null return boolean is test plan false input stream reader null file f null try f chooser get selected file if f null if merging log info merging file f else log info loading file f file server get file server set basedir f get absolute path reader new file input stream f hash tree tree save service load tree reader is test plan insert loaded tree e getid tree catch no class def found error ex allow for missing optional jars string msg ex get message if msg null msg missing jar file see log for details log warn missing jar file ex j meter utils report error to user msg catch exception ex string msg ex get message if msg null msg unexpected error see log for details log warn unexpected error ex j meter utils report error to user msg finally j orphan utils close quietly reader report gui package get instance update current gui report gui package get instance get main frame repaint don t change name if merging if merging is test plan f null report gui package get instance set report plan file f get absolute path doaction actionevent getactioncommand reportactionrouter getinstance doactionnow actionevent getsource jfilechooser reportfiledialoger prompttoopenfile istestplan inputstream getselectedfile fileserver getfileserver setbasedir getabsolutepath fileinputstream hashtree saveservice loadtree istestplan insertloadedtree noclassdeffounderror getmessage jmeterutils reporterrortouser getmessage jmeterutils reporterrortouser jorphanutils closequietly reportguipackage getinstance updatecurrentgui reportguipackage getinstance getmainframe istestplan reportguipackage getinstance setreportplanfile getabsolutepath returns a boolean indicating whether the loaded tree was a full test plan public boolean insert loaded tree int id hash tree tree throws exception illegal user action exception convert tree tree if tree null throw new exception error in test plan see log file boolean is test plan tree get array 0 instanceof report plan hash tree new tree report gui package get instance add sub tree tree report gui package get instance update current gui report gui package get instance get main frame get tree set selection path new tree path report tree node new tree get array 0 get path tree report gui package get instance get current sub tree report action router get instance action performed new action event tree get tree get array tree size 1 id report check dirty sub tree loaded return is test plan insertloadedtree hashtree illegaluseractionexception converttree testplan istestplan getarray reportplan hashtree newtree reportguipackage getinstance addsubtree reportguipackage getinstance updatecurrentgui reportguipackage getinstance getmainframe gettree setselectionpath treepath reporttreenode newtree getarray getpath reportguipackage getinstance getcurrentsubtree reportactionrouter getinstance actionperformed actionevent getarray reportcheckdirty sub_tree_loaded istestplan private transient input stream body null public ajp sampler inputstream ajpsampler protected http sample result sample url url string method boolean frd int fd http sample result res new http sample result res set monitor false res set sample label url to external form res sample start try setup connection url method res execute method res res sample end res set response data response data to byte array return res catch io exception iex res sample end http sample result err error result iex res last port 1 force reopen on next sample channel null return err httpsampleresult httpsampleresult httpsampleresult setmonitor setsamplelabel toexternalform samplestart setupconnection sampleend setresponsedata responsedata tobytearray ioexception sampleend httpsampleresult errorresult lastport public void thread finished if channel null try channel close catch io exception iex log debug error closing channel iex channel null body null threadfinished ioexception private void setup connection url url string method http sample result res throws io exception string host url get host int port url get port if port 0 port url get default port port 8009 string scheme url get protocol if channel null host equals last host port last port if channel null channel close channel new socket host port int timeout j meter utils get prop default httpclient timeout 0 non nls 1 if timeout 0 channel set so timeout timeout local address channel get local address get host address local name channel get local address get host name last host host last port port res seturl url res sethttp method method outpos 4 set byte byte 2 if method equals post set byte byte 4 else set byte byte 2 if j meter utils get prop default httpclient version 1 1 equals 1 0 non nls 1 non nls 2 non nls 3 set string http 1 0 non nls 1 else set string http 1 1 set string url get file set string local address set string local name set string host set int url get default port set byte protocol https equals ignore case scheme byte 1 byte 0 set int get header size method url string hdr set connection headers url host method res set request headers hdr set connection cookies url get cookie manager set byte byte 0xff attributes not supported setupconnection httpsampleresult ioexception gethost getport getdefaultport getprotocol lasthost lastport jmeterutils getpropdefault setsotimeout localaddress getlocaladdress gethostaddress localname getlocaladdress gethostname lasthost lastport sethttpmethod setbyte setbyte setbyte jmeterutils getpropdefault setstring setstring http_1_1 setstring getfile setstring localaddress setstring localname setstring setint getdefaultport setbyte protocol_https equalsignorecase setint getheadersize setconnectionheaders setrequestheaders setconnectioncookies getcookiemanager setbyte private int get header size string method url url header manager headers get header manager cookie manager cookies get cookie manager auth manager auth get auth manager int hsz 1 host always if method equals post string fn get filename if fn null fn trim length 0 hsz 3 else hsz 2 if headers null hsz headers size if cookies null hsz cookies get cookie count if auth null string auth header auth get auth header forurl url if auth header null hsz return hsz getheadersize headermanager getheadermanager cookiemanager getcookiemanager authmanager getauthmanager getfilename getcookiecount authheader getauthheaderforurl authheader private string set connection headers url url string host string method throws io exception header manager headers get header manager auth manager auth get auth manager string buffer hbuf new string buffer allow headers to override host setting hbuf append host append colon space append host append newline non nls 1 set int 0xa00b host set string host if headers null collection property coll headers get headers property iterator i coll iterator while i has next header header header i next get object value string n header get name string v header get value hbuf append n append colon space append v append newline int hc translate header n if hc 0 set int hc ajp header base else set string n set string v if method equals post int cl 1 string fn get filename if fn null fn trim length 0 file input new file fn cl int input length body new file input stream input set string header content disposition set string form data name encode get file field filename encode fn non nls 1 non nls 2 string mt get mimetype hbuf append header content type append colon space append mt append newline set int 0xa007 content type set string mt else hbuf append header content type append colon space append application x www form urlencoded append newline set int 0xa007 content type set string application x www form urlencoded string buffer sb new string buffer boolean first true property iterator args get arguments iterator while args has next j meter property arg args next if first first false else sb append sb append arg get name append append arg get string value byte sbody sb to string get bytes fixme encoding cl sbody length body new byte array input stream sbody hbuf append header content length append colon space append string value of cl append newline set int 0xa008 content length set string string value of cl if auth null string auth header auth get auth header forurl url if auth header null set int 0xa005 authorization set string auth header hbuf append header authorization append colon space append auth header append newline return hbuf to string setconnectionheaders ioexception headermanager getheadermanager authmanager getauthmanager stringbuffer stringbuffer colon_space setint setstring collectionproperty getheaders propertyiterator hasnext getobjectvalue getname getvalue colon_space translateheader setint ajp_header_base setstring setstring getfilename fileinputstream setstring header_content_disposition setstring getfilefield getmimetype header_content_type colon_space setint setstring header_content_type colon_space application_x_www_form_urlencoded setint setstring application_x_www_form_urlencoded stringbuffer stringbuffer propertyiterator getarguments hasnext jmeterproperty getname getstringvalue tostring getbytes bytearrayinputstream header_content_length colon_space valueof setint setstring valueof authheader getauthheaderforurl authheader setint setstring authheader header_authorization colon_space authheader tostring private string encode string value string buffer new value new string buffer char chars value to char array for int i 0 i chars length i if chars i non nls 1 new value append non nls 1 else new value append chars i return new value to string stringbuffer newvalue stringbuffer tochararray newvalue newvalue newvalue tostring private void set connection cookies url url cookie manager cookies if cookies null collection property coll cookies get cookies property iterator i coll iterator while i has next j meter property header i next set int 0xa009 cookie set string header get name header get string value non nls 1 setconnectioncookies cookiemanager collectionproperty getcookies propertyiterator hasnext jmeterproperty setint setstring getname getstringvalue private int translate header string n for int i 0 i header trans array length i if header trans array i equals ignore case n return i 1 return 1 translateheader headertransarray headertransarray equalsignorecase private void set byte byte b outbuf outpos b setbyte private void set int int n outbuf outpos byte n 8 0xff outbuf outpos byte n 0xff setint private void set string string s if s null set int 0xffff else int len s length set int len for int i 0 i len i set byte byte s char at i set byte byte 0 setstring setint setint setbyte charat setbyte private void send throws io exception output stream os channel get output stream int len outpos outpos 0 set int 0x1234 set int len 4 os write outbuf 0 len ioexception outputstream getoutputstream setint setint private void execute string method http sample result res throws io exception send if method equals post send post body handshake res httpsampleresult ioexception sendpostbody private void handshake http sample result res throws io exception response data reset int msg get message while msg 5 if msg 3 int len get int response data write inbuf inpos len else if msg 4 parse headers res else if msg 6 set next body chunk send msg get message httpsampleresult ioexception responsedata getmessage getint responsedata parseheaders setnextbodychunk getmessage private void send post body throws io exception set next body chunk send sendpostbody ioexception setnextbodychunk private void set next body chunk throws io exception int len body available if len 0 len 0 else if len max send size len max send size outpos 4 int nr 0 if len 0 nr body read outbuf outpos 2 len set int nr outpos nr setnextbodychunk ioexception max_send_size max_send_size setint private void parse headers http sample result res throws io exception int status get int res set response code integer to string status res set successful 200 status status 399 string msg get string res set response message msg int nh get int string buffer sb new string buffer sb append http 1 1 append status append append msg append newline non nls 1 non nls 2 for int i 0 i nh i currently no tomcat version sends translated headers string name int thn peek int if thn 0xff00 ajp header base name header trans array thn 0xff 1 else name get string string value get string if header content type equals ignore case name res set content type value res set encoding and type value else if header set cookie equals ignore case name cookie manager cookies get cookie manager if cookies null cookies add cookie from header value res geturl sb append name append colon space append value append newline res set response headers sb to string parseheaders httpsampleresult ioexception getint setresponsecode tostring setsuccessful getstring setresponsemessage getint stringbuffer stringbuffer http_1_1 peekint ajp_header_base headertransarray getstring getstring header_content_type equalsignorecase setcontenttype setencodingandtype header_set_cookie equalsignorecase cookiemanager getcookiemanager addcookiefromheader colon_space setresponseheaders tostring private int get message throws io exception input stream is channel get input stream inpos 0 int nr is read inbuf inpos 4 if nr 4 channel close channel null throw new io exception connection closed nr int mark get int int len get int int to read len int cpos inpos while to read 0 nr is read inbuf cpos to read cpos nr to read nr return get byte getmessage ioexception inputstream getinputstream ioexception getint getint toread toread toread toread getbyte private byte get byte return inbuf inpos getbyte private int get int int res inbuf inpos 8 0xff00 res inbuf inpos 0xff return res getint private int peek int int res inbuf inpos 8 0xff00 res inbuf inpos 1 0xff return res peekint private string get string throws io exception int len get int string s new string inbuf inpos len iso 8859 1 non nls 1 inpos len 1 return s getstring ioexception getint private int vgap public vertical panel this 5 left alignment verticalpanel left_alignment public vertical panel color bkg this sub panel set background bkg this set background bkg verticalpanel subpanel setbackground setbackground public vertical panel int vgap float horizontal align super new border layout add sub panel border layout north this vgap vgap this horizontal align horizontal align verticalpanel horizontalalign borderlayout subpanel borderlayout horizontalalign horizontalalign public component add component c this won t work right if we remove components but we don t so i m not going to worry about it right now if vgap 0 sub panel get component count 0 sub panel add box create vertical strut vgap if c instanceof j component j component c set alignmentx horizontal align return sub panel add c subpanel getcomponentcount subpanel createverticalstrut jcomponent jcomponent setalignmentx horizontalalign subpanel constructor param session the session to use to send the message param destination the queue to send the message on throws jms exception public temporary queue executor queue session session queue destination throws jms exception requestor new queue requestor session destination jmsexception temporaryqueueexecutor queuesession jmsexception queuerequestor see org apache jmeter protocol jms sampler queue executor send and receive javax jms message public message send and receive message request throws jms exception return requestor request request queueexecutor sendandreceive sendandreceive jmsexception private static final long serial versionuid 1l protected boolean remove eldest entry java util map entry arg0 if size max entries final object value arg0 get value if value instanceof map close all statements map value values return true return false serialversionuid removeeldestentry max_entries getvalue closeallstatements creates a jdbc sampler public jdbc sampler jdbcsampler jdbcsampler public sample result sample entry e log debug sampling jdbc sample result res new sample result res set sample label get name res set sampler data to string res set data type sample result text res set content type text plain non nls 1 res set data encoding encoding assume we will be successful res set successful true res set response messageok res set response codeok res sample start connection conn null statement stmt null try try conn data source element get connection get data source finally res latency end use latency to measure connection time res set response headers conn to string based on query return value get results string querytype get query type if select equals querytype stmt conn create statement result set rs null try rs stmt execute query get query res set response data get string from result set rs get bytes encoding finally close rs else if callable equals querytype callable statement cstmt get callable statement conn int out set arguments cstmt a callable statement can return more than 1 result sets plus a number of update counts boolean has result set cstmt execute string sb result sets to string cstmt has result set out res set response data sb get bytes encoding else if update equals querytype stmt conn create statement stmt execute update get query int update count stmt get update count string results update count updates res set response data results get bytes encoding else if prepared select equals querytype prepared statement pstmt get prepared statement conn set arguments pstmt pstmt execute query string sb result sets to string pstmt true null res set response data sb get bytes encoding else if prepared update equals querytype prepared statement pstmt get prepared statement conn set arguments pstmt pstmt execute update string sb result sets to string pstmt false null res set response data sb get bytes encoding else if rollback equals querytype conn rollback res set response data rollback get bytes encoding else if commit equals querytype conn commit res set response data commit get bytes encoding else if autocommit false equals querytype conn set auto commit false res set response data autocommit false get bytes encoding else if autocommit true equals querytype conn set auto commit true res set response data autocommit true get bytes encoding else user provided incorrect query type string results unexpected query type querytype res set response message results res set successful false catch sql exception ex final string err code integer to string ex get error code res set response message ex to string res set response code ex getsql state err code res set successful false catch unsupported encoding exception ex res set response message ex to string res set response code 000 todo is this correct res set successful false catch io exception ex res set response message ex to string res set response code 000 todo is this correct res set successful false finally close stmt close conn todo process warnings set code and message to success res sample end return res sampleresult sampleresult sampleresult setsamplelabel getname setsamplerdata tostring setdatatype sampleresult setcontenttype setdataencoding setsuccessful setresponsemessageok setresponsecodeok samplestart datasourceelement getconnection getdatasource latencyend setresponseheaders tostring _querytype getquerytype _querytype createstatement resultset executequery getquery setresponsedata getstringfromresultset getbytes _querytype callablestatement getcallablestatement setarguments callablestatement resultsets hasresultset resultsetstostring hasresultset setresponsedata getbytes _querytype createstatement executeupdate getquery updatecount getupdatecount updatecount setresponsedata getbytes prepared_select _querytype preparedstatement getpreparedstatement setarguments executequery resultsetstostring setresponsedata getbytes prepared_update _querytype preparedstatement getpreparedstatement setarguments executeupdate resultsetstostring setresponsedata getbytes _querytype setresponsedata getbytes _querytype setresponsedata getbytes autocommit_false _querytype setautocommit setresponsedata autocommit_false getbytes autocommit_true _querytype setautocommit setresponsedata autocommit_true getbytes _querytype setresponsemessage setsuccessful sqlexception errcode tostring geterrorcode setresponsemessage tostring setresponsecode getsqlstate errcode setsuccessful unsupportedencodingexception setresponsemessage tostring setresponsecode setsuccessful ioexception setresponsemessage tostring setresponsecode setsuccessful sampleend private string result sets to string prepared statement pstmt boolean result int out throws sql exception unsupported encoding exception str builder sb new str builder int update count 0 if result update count pstmt get update count do if result result set rs null try rs pstmt get result set sb append get string from result set rs append n non nls 1 finally close rs else sb append update count append updates n result pstmt get more results if result update count pstmt get update count while result update count 1 if out null pstmt instanceof callable statement callable statement cs callable statement pstmt sb append output variables by position n for int i 0 i out length i if out i java sql types null sb append sb append i 1 sb append sb append cs get object i 1 sb append n return sb to string resultsetstostring preparedstatement sqlexception unsupportedencodingexception strbuilder strbuilder updatecount updatecount getupdatecount resultset getresultset getstringfromresultset updatecount getmoreresults updatecount getupdatecount updatecount callablestatement callablestatement callablestatement getobject tostring private int set arguments prepared statement pstmt throws sql exception io exception if get query arguments trim length 0 return new int string arguments csv save service csv split string get query arguments comma char string arguments types get query arguments types split comma if arguments length arguments types length throw new sql exception number of arguments arguments length and number of types arguments types length are not equal int outputs new int arguments length for int i 0 i arguments length i string argument arguments i string argument type arguments types i string arg argument type split string input output if arg length 1 argument type arg 1 input output arg 0 int target sql type get jdbc type argument type try if out equals ignore case input output if argument equals null marker pstmt set null i 1 target sql type else pstmt set object i 1 argument target sql type if out equals ignore case input output inout equals ignore case input output callable statement cs callable statement pstmt cs register out parameter i 1 target sql type outputs i target sql type else outputs i java sql types null can t have an output parameter type null catch null pointer exception e thrown by derby jdbc at least if there are no markers in statement throw new sql exception could not set argument no i 1 missing parameter marker return outputs setarguments preparedstatement sqlexception ioexception getqueryarguments csvsaveservice csvsplitstring getqueryarguments comma_char argumentstypes getqueryargumentstypes argumentstypes sqlexception argumentstypes argumenttype argumentstypes argumenttype inputoutput argumenttype inputoutput targetsqltype getjdbctype argumenttype equalsignorecase inputoutput null_marker setnull targetsqltype setobject targetsqltype equalsignorecase inputoutput equalsignorecase inputoutput callablestatement callablestatement registeroutparameter targetsqltype targetsqltype nullpointerexception sqlexception private static int get jdbc type string jdbc type throws sql exception integer entry integer map jdbc name to int get jdbc type to lower case java util locale english if entry null try entry integer decode jdbc type catch number format exception e throw new sql exception invalid data type jdbc type return entry int value getjdbctype jdbctype sqlexception mapjdbcnametoint jdbctype tolowercase jdbctype numberformatexception sqlexception jdbctype intvalue private callable statement get callable statement connection conn throws sql exception return callable statement get prepared statement conn true callablestatement getcallablestatement sqlexception callablestatement getpreparedstatement private prepared statement get prepared statement connection conn throws sql exception return get prepared statement conn false preparedstatement getpreparedstatement sqlexception getpreparedstatement private prepared statement get prepared statement connection conn boolean callable throws sql exception map prepared statement map map per conn cache get conn if null prepared statement map mru prepared statements cache prepared statement map new linked hash map max entries protected boolean remove eldest entry java util map entry arg0 final int the size size if the size max entries object value arg0 get value if value instanceof prepared statement prepared statement pstmt prepared statement value close pstmt return true return false per conn cache put conn prepared statement map prepared statement pstmt prepared statement prepared statement map get get query if null pstmt if callable pstmt conn prepare call get query else pstmt conn prepare statement get query prepared statement map put get query pstmt pstmt clear parameters return pstmt preparedstatement getpreparedstatement sqlexception preparedstatementmap perconncache preparedstatementmap preparedstatements preparedstatementmap linkedhashmap max_entries removeeldestentry thesize thesize max_entries getvalue preparedstatement preparedstatement preparedstatement perconncache preparedstatementmap preparedstatement preparedstatement preparedstatementmap getquery preparecall getquery preparestatement getquery preparedstatementmap getquery clearparameters prepared statement map new linked hash map max entries protected boolean remove eldest entry java util map entry arg0 final int the size size if the size max entries object value arg0 get value if value instanceof prepared statement prepared statement pstmt prepared statement value close pstmt return true return false preparedstatementmap linkedhashmap max_entries removeeldestentry thesize thesize max_entries getvalue preparedstatement preparedstatement preparedstatement private static void close all statements collection collection iterator iterator collection iterator while iterator has next prepared statement pstmt prepared statement iterator next close pstmt closeallstatements hasnext preparedstatement preparedstatement gets a data object from a result set param rs result set passed in from a database query return a data object throws java sql sql exception throws unsupported encoding exception private string get string from result set result set rs throws sql exception unsupported encoding exception result set meta data meta rs get meta data str builder sb new str builder int num columns meta get column count for int i 1 i num columns i sb append meta get column name i if i num columns sb append n else sb append t j meter variables jmvars null string varnames get variable names split comma if varnames length 0 jmvars get thread context get variables int j 0 while rs next j for int i 1 i num columns i object o rs get object i if o instanceof byte o new string byte o encoding sb append o if i num columns sb append n else sb append t if jmvars null i varnames length string name varnames i 1 trim if name length 0 save the value in the variable if present jmvars put name underscore j o null null o to string remove any additional values from previous sample for int i 0 i varnames length i string name varnames i trim if name length 0 jmvars null final string var count name non nls 1 get the previous count string prev count jmvars get var count if prev count null int prev integer parse int prev count for int n j 1 n prev n jmvars remove name underscore n jmvars put var count integer to string j save the current count return sb to string resultset resultset sqlexception unsupportedencodingexception getstringfromresultset resultset sqlexception unsupportedencodingexception resultsetmetadata getmetadata strbuilder strbuilder numcolumns getcolumncount numcolumns getcolumnname numcolumns jmetervariables getvariablenames getthreadcontext getvariables numcolumns getobject numcolumns tostring varcount _ prevcount varcount prevcount parseint prevcount varcount tostring tostring public static void close connection c try if c null c close catch sql exception e log warn error closing connection e sqlexception public static void close statement s try if s null s close catch sql exception e log warn error closing statement s to string e sqlexception tostring public static void close result set rs try if rs null rs close catch sql exception e log warn error closing result set e resultset sqlexception resultset public string get query return query getquery public string to string str builder sb new str builder 80 sb append non nls 1 sb append get query type sb append non nls 1 sb append get query sb append n sb append get query arguments sb append n sb append get query arguments types return sb to string tostring strbuilder strbuilder getquerytype getquery getqueryarguments getqueryargumentstypes tostring param query the query to set public void set query string query this query query setquery return returns the data source public string get data source return data source datasource getdatasource datasource param data source the data source to set public void set data source string data source this data source data source datasource datasource setdatasource datasource datasource datasource return returns the query type public string get query type return query type querytype getquerytype querytype param query type the query type to set public void set query type string query type this query type query type querytype querytype setquerytype querytype querytype querytype public string get query arguments return query arguments getqueryarguments queryarguments public void set query arguments string query arguments this query arguments query arguments setqueryarguments queryarguments queryarguments queryarguments public string get query arguments types return query arguments types getqueryargumentstypes queryargumentstypes public void set query arguments types string query arguments type this query arguments types query arguments type setqueryargumentstypes queryargumentstype queryargumentstypes queryargumentstype return the variable names public string get variable names return variable names variablenames getvariablenames variablenames param variable names the variable names to set public void set variable names string variable names this variable names variable names variablenames variablenames setvariablenames variablenames variablenames variablenames implements java sampler client setup test java sampler context public void setup test java sampler context context log debug get class get name setup test javasamplerclient setuptest javasamplercontext setuptest javasamplercontext getclass getname setuptest implements java sampler client teardown test java sampler context public void teardown test java sampler context context log debug get class get name teardown test javasamplerclient teardowntest javasamplercontext teardowntest javasamplercontext getclass getname teardowntest implements java sampler client get default parameters public arguments get default parameters return null javasamplerclient getdefaultparameters getdefaultparameters get a logger instance which can be used by subclasses to log information this is the same logger which is used by the base java sampler classes jmeter protocol java return a logger instance which can be used for logging protected logger get logger return log javasampler getlogger return a document param key return document public static synchronized document get document object key return document memcache get key getdocument add an object to the cache param key param data public static synchronized void put document object key object data memcache put key data putdocument private constructor to prevent instantiation private dom pool dompool public class replace string with functions extends abstract transformer public replace string with functions compound variable master function map variables super set master function master function set variables variables replacestringwithfunctions abstracttransformer replacestringwithfunctions compoundvariable masterfunction setmasterfunction masterfunction setvariables public j meter property transform value j meter property prop throws invalid variable exception j meter property new value prop get master function clear get master function set parameters prop get string value if get master function has function new value new function property prop get name get master function get function return new value jmeterproperty transformvalue jmeterproperty invalidvariableexception jmeterproperty newvalue getmasterfunction getmasterfunction setparameters getstringvalue getmasterfunction hasfunction newvalue functionproperty getname getmasterfunction getfunction newvalue sampler sampler public sample package samplepackage public sample package list configs list modifiers list response modifiers list listeners list timers list assertions list extractors list pres list controllers log debug configs is null configs null this configs configs this modifiers modifiers this response modifiers response modifiers this sample listeners listeners this timers timers this assertions assertions this post processors extractors this pre processors pres this controllers controllers samplepackage responsemodifiers responsemodifiers responsemodifiers samplelisteners postprocessors preprocessors public void set running version boolean running set running version configs running set running version modifiers running set running version sample listeners running set running version assertions running set running version timers running set running version response modifiers running set running version post processors running set running version pre processors running set running version controllers running sampler set running version running setrunningversion setrunningversion setrunningversion setrunningversion samplelisteners setrunningversion setrunningversion setrunningversion responsemodifiers setrunningversion postprocessors setrunningversion preprocessors setrunningversion setrunningversion private void set running version list list boolean running iterator iter list iterator while iter has next test element iter next set running version running setrunningversion hasnext testelement setrunningversion private void recover running version list list iterator iter list iterator while iter has next test element iter next recover running version recoverrunningversion hasnext testelement recoverrunningversion public void recover running version recover running version configs recover running version modifiers recover running version sample listeners recover running version assertions recover running version timers recover running version response modifiers recover running version post processors recover running version pre processors recover running version controllers sampler recover running version recoverrunningversion recoverrunningversion recoverrunningversion recoverrunningversion samplelisteners recoverrunningversion recoverrunningversion recoverrunningversion responsemodifiers recoverrunningversion postprocessors recoverrunningversion preprocessors recoverrunningversion recoverrunningversion public list get sample listeners return sample listeners getsamplelisteners samplelisteners public void add sample listener sample listener listener sample listeners add listener addsamplelistener samplelistener samplelisteners public list get timers return timers gettimers public void add post processor post processor ex post processors add ex addpostprocessor postprocessor postprocessors public void add pre processor pre processor pre pre processors add pre addpreprocessor preprocessor preprocessors public void add timer timer timer timers add timer addtimer public void add assertion assertion asser assertions add asser addassertion public list get assertions return assertions getassertions public list get post processors return post processors getpostprocessors postprocessors public sampler get sampler return sampler getsampler public void set sampler sampler s sampler s setsampler returns the pre processors public list get pre processors return pre processors preprocessors getpreprocessors preprocessors sets the pre processors param pre processors the pre processors to set public void set pre processors list pre processors this pre processors pre processors preprocessors preprocessors preprocessors setpreprocessors preprocessors preprocessors preprocessors returns the configs return list public list get configs return configs getconfigs returns the modifiers public list get modifiers return modifiers getmodifiers returns the response modifiers public list get response modifiers return response modifiers responsemodifiers getresponsemodifiers responsemodifiers sets the assertions param assertions the assertions to set public void set assertions list assertions this assertions assertions setassertions sets the configs param configs the configs to set public void set configs list configs this configs configs setconfigs sets the modifiers param modifiers the modifiers to set public void set modifiers list modifiers this modifiers modifiers setmodifiers sets the post processors param post processors the post processors to set public void set post processors list post processors this post processors post processors postprocessors postprocessors postprocessors setpostprocessors postprocessors postprocessors postprocessors sets the response modifiers param response modifiers the response modifiers to set public void set response modifiers list response modifiers this response modifiers response modifiers responsemodifiers responsemodifiers responsemodifiers setresponsemodifiers responsemodifiers responsemodifiers responsemodifiers sets the sample listeners param sample listeners the sample listeners to set public void set sample listeners list sample listeners this sample listeners sample listeners samplelisteners samplelisteners samplelisteners setsamplelisteners samplelisteners samplelisteners samplelisteners sets the timers param timers the timers to set public void set timers list timers this timers timers settimers public assertion result get result sample result response assertion result result new assertion result get name result set failure false byte result data response get response data if result data length 0 result set error false result set failure true result set failure message response was null return result no point in checking if we don t have anything to compare against if get allowedmd5 hex equals result set error false result set failure true result set failure message md5 hex to test against is empty return result string md5 result bamd5 hex result data string md5 result digest utils md5 hex result data if md5 result equals ignore case get allowedmd5 hex result set failure true object arguments md5 result get allowedmd5 hex string message message format format j meter utils get res string md5hex assertion failure arguments non nls 1 result set failure message message return result assertionresult getresult sampleresult assertionresult assertionresult getname setfailure resultdata getresponsedata resultdata seterror setfailure setfailuremessage getallowedmd5hex seterror setfailure setfailuremessage md5hex md5result bamd5hex resultdata md5result digestutils md5hex resultdata md5result equalsignorecase getallowedmd5hex setfailure md5result getallowedmd5hex messageformat jmeterutils getresstring md5hex_assertion_failure setfailuremessage public void set allowedmd5 hex string hex set property new string property md5 hex assertion md5hex key hex setallowedmd5hex setproperty stringproperty md5hexassertion md5hex_key public string get allowedmd5 hex return get property as string md5 hex assertion md5hex key getallowedmd5hex getpropertyasstring md5hexassertion md5hex_key package protected so can be accessed by test class static string bamd5 hex byte ba byte md5 result try message digest md md message digest get instance md5 md5 result md digest ba catch no such algorithm exception e log error e return j orphan utils ba to hex string md5 result bamd5hex md5result messagedigest messagedigest getinstance md5result nosuchalgorithmexception jorphanutils batohexstring md5result public report tree node allow serializable test to work todo is the serializable test necessary now that j meter tree node is no longer a gui component this null null reporttreenode jmetertreenode public report tree node test element user obj report tree model tree model super user obj this tree model tree model reporttreenode testelement userobj reporttreemodel treemodel userobj treemodel treemodel public boolean is enabled return abstract test element get test element get property as boolean test element enabled isenabled abstracttestelement gettestelement getpropertyasboolean testelement public void set enabled boolean enabled get test element set property new boolean property test element enabled enabled tree model node changed this setenabled gettestelement setproperty booleanproperty testelement treemodel nodechanged public image icon get icon return get icon true imageicon geticon geticon public image icon get icon boolean enabled try if get test element instanceof test bean try image img introspector get bean info get test element get class get icon bean info icon color 16x16 if icon has not been defined then use gui class property if img null object clazz introspector get bean info get test element get class get bean descriptor get value test element gui class if clazz null log error can t obtain gui class for get test element get class get name return null return gui factory get icon class for name string clazz enabled return new image icon img catch introspection exception e1 log error can t obtain icon e1 throw new org apache jorphan util j meter error e1 else return gui factory get icon class for name get test element get property as string test element gui class enabled catch class not found exception e log warn can t get icon for class get test element e return null imageicon geticon gettestelement testbean getbeaninfo gettestelement getclass geticon beaninfo icon_color_16x16 gui_class getbeaninfo gettestelement getclass getbeandescriptor getvalue testelement gui_class gettestelement getclass getname guifactory geticon forname imageicon introspectionexception jmetererror guifactory geticon forname gettestelement getpropertyasstring testelement gui_class classnotfoundexception gettestelement public collection get menu categories try return report gui package get instance get gui get test element get menu categories catch exception e log error can t get popup menu for gui e return null getmenucategories reportguipackage getinstance getgui gettestelement getmenucategories public j popup menu create popup menu try return report gui package get instance get gui get test element create popup menu catch exception e log error can t get popup menu for gui e return null jpopupmenu createpopupmenu reportguipackage getinstance getgui gettestelement createpopupmenu public test element get test element return test element get user object testelement gettestelement testelement getuserobject public string get static label return report gui package get instance get gui test element get user object get static label getstaticlabel reportguipackage getinstance getgui testelement getuserobject getstaticlabel public string get doc anchor return report gui package get instance get gui test element get user object get doc anchor getdocanchor reportguipackage getinstance getgui testelement getuserobject getdocanchor public void set name string name test element get user object set name name setname testelement getuserobject setname public string get name return test element get user object get name getname testelement getuserobject getname public void name changed tree model node changed this namechanged treemodel nodechanged private object values public property2 public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception string property name compound variable values 0 execute string property default 1 non nls 1 if values length 1 we have a default property default compound variable values 1 execute string property value j meter utils get prop default property name property default return property value sampleresult previousresult currentsampler invalidvariableexception propertyname compoundvariable propertydefault propertydefault compoundvariable propertyvalue jmeterutils getpropdefault propertyname propertydefault propertyvalue public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters min parameter count max parameter count values parameters to array setparameters invalidvariableexception checkparametercount min_parameter_count max_parameter_count toarray public string get reference key return key getreferencekey public list get argument desc return desc getargumentdesc create a new assertion result the result will indicate no failure or error deprecated use the named constructor public assertion result needs to be public for tests assertionresult create a new assertion result the result will indicate no failure or error param name the name of the assertion public assertion result string name set name name assertionresult setname get the name of the assertion return the name of the assertion public string get name return name getname set the name of the assertion param name the name of the assertion public void set name string name this name name setname check if the assertion failed if it failed the failure message may give more details about the failure return true if the assertion failed false if the sample met the assertion criteria public boolean is failure return failure isfailure check if an error occurred while checking the assertion if an error occurred the failure message may give more details about the error return true if an error occurred while checking the assertion false otherwise public boolean is error return error iserror get the message associated with any failure or error this method may return null if no message was set return a failure or error message or null if no message has been set public string get failure message return failure message getfailuremessage failuremessage set the flag indicating whether or not an error occurred param e true if an error occurred false otherwise public void set error boolean e error e seterror set the flag indicating whether or not a failure occurred param f true if a failure occurred false otherwise public void set failure boolean f failure f setfailure set the failure message giving more details about a failure or error param message the message to set public void set failure message string message failure message message setfailuremessage failuremessage convenience method for setting up failed results param message the message to set return this public assertion result set result for failure string message error false failure true failure message message return this assertionresult setresultforfailure failuremessage convenience method for setting up results where the response was null return assertion result with appropriate fields set up public assertion result set result for null error false failure true failure message response was null return this assertionresult setresultfornull failuremessage response_was_null public string to string return get name null get name super to string tostring getname getname tostring create a new daemon with the specified port and target param port the port to listen on param target the target which will receive the generated j meter test components throws io exception public daemon int port proxy control target throws io exception this port target proxy class jmeter ioexception proxycontrol ioexception create a new daemon with the specified port and target using the specified class to handle individual requests param port the port to listen on param target the target which will receive the generated j meter test components param proxy class the proxy class to use to handle individual requests this class must be the link proxy class or a subclass throws io exception public daemon int port proxy control target class proxy class throws io exception super http proxy daemon this target target this daemon port port this proxy class proxy class log info creating daemon socket on port daemon port main socket new server socket daemon port main socket set so timeout accept timeout jmeter proxyclass ioexception proxycontrol proxyclass ioexception daemonport proxyclass proxyclass daemonport mainsocket serversocket daemonport mainsocket setsotimeout accept_timeout listen on the daemon port and handle incoming requests this method will not exit until link stop server is called or an error occurs public void run running true log info proxy up and running maps to contain page and form encodings map page encodings collections synchronized map new hash map map form encodings collections synchronized map new hash map try while running try listen on main socket socket client socket main socket accept if running pass request to new proxy thread proxy thd proxy proxy class new instance thd configure client socket target page encodings form encodings thd start catch interruptedio exception e continue timeout occurred ignore and keep looping until we re told to stop running log info proxy server stopped catch exception e log warn proxy server stopped e finally j orphan utils close quietly main socket clear maps page encodings null form encodings null stopserver pageencodings synchronizedmap hashmap formencodings synchronizedmap hashmap clientsocket mainsocket proxyclass newinstance clientsocket pageencodings formencodings interruptedioexception jorphanutils closequietly mainsocket pageencodings formencodings stop the proxy daemon the daemon may not stop immediately see accept timeout public void stop server running false accept_timeout stopserver private string label public sampling stat calculator don t can t use this log warn constructor only intended for use in testing non nls 1 samplingstatcalculator use this constructor public sampling stat calculator string label this label label init samplingstatcalculator essentially a copy function param stat public sampling stat calculator sampling stat calculator stat this stat label add samples stat samplingstatcalculator samplingstatcalculator addsamples private void init first time long max value calculator clear stored values clear max throughput double min value firsttime max_value storedvalues maxthroughput min_value public void add samples sampling stat calculator ssc calculator add all ssc calculator synchronized stored values stored values add all ssc stored values collections sort stored values if first time ssc first time first time ssc first time addsamples samplingstatcalculator addall storedvalues storedvalues addall storedvalues storedvalues firsttime firsttime firsttime firsttime clear the counters useful for differential stats public synchronized void clear init public sample get current sample synchronized stored values if stored values size 0 return new sample return sample stored values get stored values size 1 getcurrentsample storedvalues storedvalues storedvalues storedvalues get the elapsed time for the samples return how long the samples took public long get elapsed if get current sample get end time 0 return 0 no samples collected return get current sample get end time first time getelapsed getcurrentsample getendtime getcurrentsample getendtime firsttime returns the throughput associated to this sampler in requests per second may be slightly skewed because it takes the timestamps of the first and last samples as the total time passed and the test may actually have started before that start time and ended after that end time public double get rate if calculator get count 0 return 0 0 better behaviour when how long 0 or last time 0 return get current sample get throughput getrate getcount howlong lasttime getcurrentsample getthroughput should calculate the average page size which means divide the bytes by number of samples actually calculates the throughput in bytes second deprecated use get bytes per second instead see get avg page bytes for the average page size public double get page size double rate 0 if this get elapsed 0 calculator get total bytes 0 rate calculator get total bytes double this get elapsed 1000 if rate 0 rate 0 return rate getbytespersecond getavgpagebytes getpagesize getelapsed gettotalbytes gettotalbytes getelapsed throughput in bytes second return throughput in bytes second public double get bytes per second code duplicated from get page size double rate 0 if this get elapsed 0 calculator get total bytes 0 rate calculator get total bytes double this get elapsed 1000 if rate 0 rate 0 return rate getbytespersecond getpagesize getelapsed gettotalbytes gettotalbytes getelapsed throughput in kilobytes second return throughput in kilobytes second public double getkb per second return get bytes per second 1024 1024 bytes per kb getkbpersecond getbytespersecond calculates the average page size which means divide the bytes by number of samples return average page size in bytes public double get avg page bytes double rate 0 if this get elapsed 0 calculator get total bytes 0 rate calculator get total bytes double this get elapsed 1000 if rate 0 rate 0 return rate getavgpagebytes getelapsed gettotalbytes gettotalbytes getelapsed public string get label return label getlabel records a sample public sample add sample sample result res long rtime cmean cstdv cmedian cpercent e count end time double throughput boolean rbool synchronized calculator long byteslength res get bytes if there was more than 1 loop in the sample we handle it appropriately if res get sample count 1 long time res get time res get sample count long resbytes byteslength res get sample count for int idx 0 idx res get sample count idx calculator add value time calculator add bytes resbytes else calculator add value res get time calculator add bytes byteslength set start time res e count get current sample get error count if res is successful e count end time get end time res long how long running end time first time throughput double calculator get count double how long running 1000 0 if throughput max throughput max throughput throughput rtime res get time cmean long calculator get mean cstdv long calculator get standard deviation cmedian calculator get median long value cpercent calculator get percent point 0 500 long value todo cpercent is the same as cmedian here why and why pass it to distribution line rbool res is successful synchronized stored values int count stored values size 1 sample s new sample null rtime cmean cstdv cmedian cpercent throughput e count rbool count end time stored values add s return s addsample sampleresult ecount endtime getbytes getsamplecount gettime getsamplecount getsamplecount getsamplecount addvalue addbytes addvalue gettime addbytes setstarttime ecount getcurrentsample geterrorcount issuccessful ecount endtime getendtime howlongrunning endtime firsttime getcount howlongrunning maxthroughput maxthroughput gettime getmean getstandarddeviation getmedian longvalue getpercentpoint longvalue distributionline issuccessful storedvalues storedvalues ecount endtime storedvalues public list get samples return stored values getsamples storedvalues public sample get sample int index synchronized stored values if index stored values size return sample stored values get index return null getsample storedvalues storedvalues storedvalues private long get end time sample result res long end time res get end time long last time get current sample get end time if last time end time last time end time return last time getendtime sampleresult endtime getendtime lasttime getcurrentsample getendtime lasttime endtime lasttime endtime lasttime param res private void set start time sample result res long start time res get start time if first time start time this is our first sample set the start time to current timestamp first time start time setstarttime sampleresult starttime getstarttime firsttime starttime firsttime starttime returns the raw double value of the percentage of samples with errors that were recorded between 0 0 and 1 0 return the raw double value of the percentage of samples with errors that were recorded public double get error percentage double rval 0 0 if calculator get count 0 return rval rval double get current sample get error count double calculator get count return rval geterrorpercentage getcount getcurrentsample geterrorcount getcount for debugging purposes only public string to string string buffer mysb new string buffer mysb append samples this get count mysb append avg this get mean mysb append min this get min mysb append max this get max mysb append error rate this get error percentage mysb append sample rate this get rate return mysb to string tostring stringbuffer stringbuffer getcount getmean getmin getmax geterrorpercentage getrate tostring return error count public long get error count return get current sample get error count errorcount geterrorcount getcurrentsample geterrorcount return returns the max throughput public double get max throughput return max throughput maxthroughput getmaxthroughput maxthroughput public hash map get distribution return calculator get distribution hashmap getdistribution getdistribution public number get percent point double percent return calculator get percent point percent getpercentpoint getpercentpoint public int get count return calculator get count getcount getcount public number get max return calculator get max getmax getmax public double get mean return calculator get mean getmean getmean public number get mean as number return new long long calculator get mean getmeanasnumber getmean public number get median return calculator get median getmedian getmedian public number get min if calculator get min long value 0 return new long 0 return calculator get min getmin getmin longvalue getmin public number get percent point float percent return calculator get percent point percent getpercentpoint getpercentpoint public double get standard deviation return calculator get standard deviation getstandarddeviation getstandarddeviation constructor for the graph visualizer object public monitor health visualizer this is stats true init model init graphvisualizer monitorhealthvisualizer isstats initmodel public void configure test element el super configure el prefix field set text el get property as string connector prefix connector prefix default model set prefix prefix field get text testelement prefixfield settext getpropertyasstring connector_prefix connector_prefix_default setprefix prefixfield gettext public void modify test element test element c super modify test element c c set property connector prefix prefix field get text connector prefix default model set prefix prefix field get text modifytestelement testelement modifytestelement setproperty connector_prefix prefixfield gettext connector_prefix_default setprefix prefixfield gettext private void init model model new monitor accum model graph new monitor graph model model set buffer size j meter utils get prop default buffer 800 initmodel monitoraccummodel monitorgraph setbuffersize jmeterutils getpropdefault public string get label resource return monitor health title non nls 1 getlabelresource monitor_health_title because of the unique requirements of a monitor we have to handle the results differently than normal gui components a monitor should be able to run for a very long time without eating up all the memory public void add sample result res model add sample res try collector record stats this model get last sample clone monitor stats catch exception e for now just swallow the exception log debug stats model was null e sampleresult addsample recordstats getlastsample clonemonitorstats statsmodel public image get image image result graph create image this get width this get height graphics image result get graphics graph paint component image return result getimage createimage getwidth getheight getgraphics paintcomponent public void item state changed item event e itemstatechanged itemevent public synchronized void update gui this repaint updategui public synchronized void update gui sample s this repaint updategui initialize the gui private void init this set layout new border layout main panel border margin new empty border 10 10 5 10 this set border margin add the main panel and the graph this add this make title panel border layout north this create tabs prefix field new j labeled text field j meter utils get res string monitor label prefix non nls 1 add prefix field border layout south setlayout borderlayout emptyborder setborder maketitlepanel borderlayout createtabs prefixfield jlabeledtextfield jmeterutils getresstring monitor_label_prefix prefixfield borderlayout private void create tabs tab pane new monitor tab pane create health pane tab pane create performance pane tab pane this add tab pane border layout center createtabs tabpane monitortabpane createhealthpane tabpane createperformancepane tabpane tabpane borderlayout create the j panel param pane private void create health pane monitor tab pane pane health pane new monitor health panel model pane add tab j meter utils get res string monitor health tab title health pane non nls 1 jpanel createhealthpane monitortabpane healthpane monitorhealthpanel addtab jmeterutils getresstring monitor_health_tab_title healthpane create the j split pane for the performance history param pane private void create performance pane monitor tab pane pane perf pane new monitor performance panel model graph pane add tab j meter utils get res string monitor performance tab title perf pane non nls 1 jsplitpane createperformancepane monitortabpane perfpane monitorperformancepanel addtab jmeterutils getresstring monitor_performance_tab_title perfpane clears the monitor accum model public void clear data this model clear data this health pane clear data this perf pane clear data monitoraccummodel cleardata cleardata healthpane cleardata perfpane cleardata public monitor tab pane super top monitortabpane public add to tree addtotree gets the set of actions this command class responds to return the action names value public set get action names return command set actionnames getactionnames commandset adds the specified class to the current node of the tree public void do action action event e gui package gui package gui package get instance try gui package update current node test element test element gui package create test element j component e get source get name j meter tree node parent node gui package get current node j meter tree node node gui package get tree model add component test element parent node gui package get main frame get tree set selection path new tree path node get path catch illegal user action exception err log error err non nls 1 string msg err get message if msg null msg err to string j meter utils report error to user msg catch exception err log error err non nls 1 string msg err get message if msg null msg err to string j meter utils report error to user msg doaction actionevent guipackage guipackage guipackage getinstance guipackage updatecurrentnode testelement testelement guipackage createtestelement jcomponent getsource getname jmetertreenode parentnode guipackage getcurrentnode jmetertreenode guipackage gettreemodel addcomponent testelement parentnode guipackage getmainframe gettree setselectionpath treepath getpath illegaluseractionexception getmessage tostring jmeterutils reporterrortouser getmessage tostring jmeterutils reporterrortouser don t allow instantiation of this utility class private http reply hdr httpreplyhdr forms a http ok reply header param content type the mime type of the content param content length the length of the content return a string with the header in it public static string form ok string content type long content length string buffer out new string buffer out append http protocol append 200 ok append cr out append server append http server append cr out append mime version 1 0 append cr if 0 content type length out append content type append content type append cr else out append content type text html append cr if 0 content length out append content length append content length append cr out append cr return out to string contenttype contentlength formok contenttype contentlength stringbuffer stringbuffer http_protocol http_server contenttype contenttype contentlength contentlength tostring private builds an http document describing a headers reason param error error name param description errors description return a string with the html description body private static string form error body string error string description string buffer out new string buffer generate error body out append html head title out append error out append title head out append body h2 append error append h2 n out append p h3 out append description out append body html return out to string formerrorbody stringbuffer stringbuffer tostring builds an http document describing an error param error error name param description errors description return a string with the html description body private static string form error string error string description a http response header looks alot like http 1 0 200 ok date wednesday 02 feb 94 23 04 12 gmt server ncsa 1 1 mime version 1 0 last modified monday 15 nov 93 23 33 16 gmt content type text html content length 2345 r n string body form error body error description string buffer header new string buffer header append http protocol append append error append cr header append server append http server append cr header append mime version 1 0 append cr header append content type text html append cr header append content length append body length append cr header append cr header append body return header to string formerror formerrorbody stringbuffer stringbuffer http_protocol http_server tostring indicates a new file was created return the header in a string public static string form created return form error 201 created object was created formcreated formerror indicates the document was accepted return the header in a string public static string form accepted return form error 202 accepted object checked in formaccepted formerror indicates only a partial responce was sent return the header in a string public static string form partial return form error 203 partial only partail document available formpartial formerror indicates a requested url has moved to a new address or name return the header in a string public static string form moved 300 codes tell client to do actions return form error 301 moved file has moved formmoved formerror never seen this used return the header in a string public static string form found return form error 302 found object was found formfound formerror the requested method is not implemented by the server return the header in a string public static string form method return form error 303 method unseported method unseported formmethod formerror indicates remote copy of the requested object is current return the header in a string public static string form not modified return form error 304 not modified use local copy formnotmodified formerror client not otherized for the request return the header in a string public static string form unautorized return form error 401 unathorized unathorized use of this service formunautorized formerror payment is required for service return the header in a string public static string form payment needed return form error 402 payment required payment is required formpaymentneeded formerror client if forbidden to get the request service return the header in a string public static string form forbidden return form error 403 forbidden you need permission for this service formforbidden formerror the requested object was not found return the header in a string public static string form not found return form error 404 not found requested object was not found formnotfound formerror not_found the server had a problem and could not fulfill the request return the header in a string public static string form internal error return form error 500 internal server error server broke forminternalerror formerror server does not do the requested feature return the header in a string public static string form not implemented return form error 501 method not implemented service not implemented formnotimplemented formerror server does not do the requested feature param reason detailed information for causing the failure return the header in a string public static string form not implemented string reason return form error 501 method not implemented service not implemented reason formnotimplemented formerror server is overloaded client should try again latter return the header in a string public static string form overloaded return form error 502 server overloaded try again latter formoverloaded formerror indicates the request took to long return the header in a string public static string form timeout return form error 503 gateway timeout the connection timed out formtimeout formerror indicates the client s proxies could not locate a server return the header in a string public static string form server not found return form error 503 gateway timeout the requested server was not found formservernotfound formerror indicates the client is not allowed to access the object return the header in a string public static string form not allowed return form error 403 access denied access is not allowed formnotallowed formerror private constructor to prevent instantiation private old save service oldsaveservice public static void save sub tree hash tree sub tree output stream writer throws io exception configuration config configuration get configs from tree sub tree get 0 default configuration serializer saver new default configuration serializer saver set indent true try saver serialize writer config catch sax exception e throw new io exception sax implementation problem catch configuration exception e throw new io exception problem using avalon configuration tools savesubtree hashtree subtree outputstream ioexception getconfigsfromtree subtree defaultconfigurationserializer defaultconfigurationserializer setindent saxexception ioexception configurationexception ioexception read sample result from avalon xml file param config avalon configuration return sample result probably no point in converting this to return a sample event public static sample result get sample result configuration config sample result result new sample result config get attribute as long time stamp 0l config get attribute as long time 0l result set thread name config get attribute thread name non nls 1 result set data type config get attribute data type result set response code config get attribute response code non nls 1 result set response message config get attribute response message non nls 1 result set successful config get attribute as boolean successful false result set sample label config get attribute label non nls 1 result set response data get binary data config get child binary configuration sub results config get children sample result tag name for int i 0 i sub results length i result store sub result get sample result sub results i configuration ass results config get children assertion result tag name for int i 0 i ass results length i result add assertion result get assertion result ass results i configuration sampler data config get children property non nls 1 for int i 0 i sampler data length i result set sampler data sampler data i get value non nls 1 return result sampleresult sampleevent sampleresult getsampleresult sampleresult sampleresult getattributeaslong time_stamp getattributeaslong setthreadname getattribute thread_name setdatatype getattribute data_type setresponsecode getattribute response_code setresponsemessage getattribute response_message setsuccessful getattributeasboolean setsamplelabel getattribute setresponsedata getbinarydata getchild subresults getchildren sample_result_tag_name subresults storesubresult getsampleresult subresults assresults getchildren assertion_result_tag_name assresults addassertionresult getassertionresult assresults samplerdata getchildren samplerdata setsamplerdata samplerdata getvalue private static list get configs from tree hash tree sub tree iterator iter sub tree list iterator list configs new linked list while iter has next test element item test element iter next default configuration config new default configuration node node non nls 1 non nls 2 config add child get config for test element null item list config list get configs from tree sub tree get tree item iterator iter2 config list iterator while iter2 has next config add child configuration iter2 next configs add config return configs getconfigsfromtree hashtree subtree subtree linkedlist hasnext testelement testelement defaultconfiguration defaultconfiguration addchild getconfigfortestelement configlist getconfigsfromtree subtree gettree configlist hasnext addchild private static configuration get configuration byte bin default configuration config new default configuration binary j meter save service non nls 1 try config set value new string bin utf 8 non nls 1 catch unsupported encoding exception e log error e non nls 1 return config getconfiguration defaultconfiguration defaultconfiguration jmeter setvalue unsupportedencodingexception private static byte get binary data configuration config if config null return new byte 0 try return config get value get bytes utf 8 non nls 1 catch unsupported encoding exception e return new byte 0 getbinarydata getvalue getbytes unsupportedencodingexception private static assertion result get assertion result configuration config assertion result result new assertion result todo provide proper name result set error config get attribute as boolean error false result set failure config get attribute as boolean failure false result set failure message config get attribute failure message return result assertionresult getassertionresult assertionresult assertionresult seterror getattributeasboolean setfailure getattributeasboolean setfailuremessage getattribute failure_message private static configuration get configuration assertion result ass result default configuration config new default configuration assertion result tag name j meter save service config set attribute failure message ass result get failure message config set attribute error ass result is error config set attribute failure ass result is failure return config getconfiguration assertionresult assresult defaultconfiguration defaultconfiguration assertion_result_tag_name jmeter setattribute failure_message assresult getfailuremessage setattribute assresult iserror setattribute assresult isfailure this method determines the content of the result data that will be stored for the avalon xml format param result the object containing all of the data that has been collected param save config the configuration giving the data items to be saved n b it is rather out of date as many fields are not saved however it is probably not worth updating as no one should be using the format public static configuration get configuration sample result result sample save configuration save config default configuration config new default configuration sample result tag name j meter save service non nls 1 if save config save time config set attribute time string value of result get time if save config save label config set attribute label result get sample label if save config save code config set attribute response code result get response code if save config save message config set attribute response message result get response message if save config save thread name config set attribute thread name result get thread name if save config save data type config set attribute data type result get data type if save config print milliseconds config set attribute time stamp string value of result get time stamp else if save config formatter null string stamp save config formatter format new date result get time stamp config set attribute time stamp stamp if save config save success config set attribute successful boolean to string result is successful sample result sub results result get sub results if sub results null for int i 0 i sub results length i config add child get configuration sub results i save config assertion result ass results result get assertion results if save config save sampler data result config add child create config for string sampler data result get sampler data non nls 1 if save config save assertions ass results null for int i 0 i ass results length i config add child get configuration ass results i if save config save response data result config add child get configuration result get response data return config saveconfig getconfiguration sampleresult samplesaveconfiguration saveconfig defaultconfiguration defaultconfiguration sample_result_tag_name jmeter saveconfig savetime setattribute valueof gettime saveconfig savelabel setattribute getsamplelabel saveconfig savecode setattribute response_code getresponsecode saveconfig savemessage setattribute response_message getresponsemessage saveconfig savethreadname setattribute thread_name getthreadname saveconfig savedatatype setattribute data_type getdatatype saveconfig printmilliseconds setattribute time_stamp valueof gettimestamp saveconfig saveconfig gettimestamp setattribute time_stamp saveconfig savesuccess setattribute tostring issuccessful sampleresult subresults getsubresults subresults subresults addchild getconfiguration subresults saveconfig assertionresult assresults getassertionresults saveconfig savesamplerdata addchild createconfigforstring samplerdata getsamplerdata saveconfig saveassertions assresults assresults addchild getconfiguration assresults saveconfig saveresponsedata addchild getconfiguration getresponsedata private static configuration get config for test element string named test element item test element saver saver new test element saver named item traverse saver configuration config saver get configuration default configuration config new default configuration testelement testelement if named null config set attribute name named if item get property test element test class null config set attribute class string item get property test element test class else config set attribute class item get class get name iterator iter item get property names iterator while iter has next string name string iter next object value item get property name if value instanceof test element config add child get config for test element name test element value else if value instanceof collection config add child create config for collection name collection value else if value null config add child create config for string name value to string return config getconfigfortestelement testelement testelementsaver testelementsaver getconfiguration defaultconfiguration defaultconfiguration setattribute getproperty testelement test_class setattribute getproperty testelement test_class setattribute getclass getname getpropertynames hasnext getproperty testelement addchild getconfigfortestelement testelement addchild createconfigforcollection addchild createconfigforstring tostring private static configuration create config for string string name string value if value null value default configuration config new default configuration property property config set attribute name name config set value value config set attribute xml space preserve return config createconfigforstring defaultconfiguration defaultconfiguration setattribute setvalue setattribute xml_space public synchronized static hash tree load sub tree input stream in throws io exception try configuration config builder build in hash tree loaded tree generate node config return loaded tree catch configuration exception e string message problem loading using avalon configuration tools log error message e throw new io exception message catch sax exception e string message problem with sax implementation log error message e throw new io exception message hashtree loadsubtree inputstream ioexception hashtree loadedtree generatenode loadedtree configurationexception ioexception saxexception ioexception private static test element create test element configuration config throws configuration exception class not found exception illegal access exception instantiation exception test element element null string test class config get attribute class non nls 1 string gui class non nls 1 configuration children config get children for int i 0 i children length i if children i get name equals property non nls 1 if children i get attribute name equals test element gui class non nls 1 gui class children i get value string new class name updater get current test name test class gui class element test element class for name new class new instance for int i 0 i children length i if children i get name equals property non nls 1 try j meter property prop create property children i new class if prop null element set property prop catch exception ex log error problem loading property ex element set property children i get attribute name non nls 1 non nls 2 else if children i get name equals testelement non nls 1 element set property new test element property children i get attribute name non nls 1 non nls 2 create test element children i else if children i get name equals collection non nls 1 element set property new collection property children i get attribute name non nls 1 non nls 2 create collection children i new class else if children i get name equals map non nls 1 element set property new map property children i get attribute name non nls 1 non nls 2 create map children i new class return element testelement createtestelement configurationexception classnotfoundexception illegalaccessexception instantiationexception testelement testclass getattribute gui_class getchildren getname getattribute testelement gui_class gui_class getvalue newclass nameupdater getcurrenttestname testclass gui_class testelement forname newclass newinstance getname jmeterproperty createproperty newclass setproperty setproperty getattribute getname setproperty testelementproperty getattribute createtestelement getname setproperty collectionproperty getattribute createcollection newclass getname setproperty mapproperty getattribute createmap newclass private static collection create collection configuration config string test class throws configuration exception class not found exception illegal access exception instantiation exception collection coll collection class for name config get attribute class new instance non nls 1 configuration items config get children for int i 0 i items length i if items i get name equals property non nls 1 j meter property prop create property items i test class if prop null coll add prop else if items i get name equals testelement non nls 1 coll add new test element property items i get attribute name create test element items i non nls 1 non nls 2 else if items i get name equals collection non nls 1 coll add new collection property items i get attribute name non nls 1 non nls 2 create collection items i test class else if items i get name equals string non nls 1 j meter property prop create property items i test class if prop null coll add prop else if items i get name equals map non nls 1 coll add new map property items i get attribute name create map items i test class non nls 1 non nls 2 return coll createcollection testclass configurationexception classnotfoundexception illegalaccessexception instantiationexception forname getattribute newinstance getchildren getname jmeterproperty createproperty testclass getname testelementproperty getattribute createtestelement getname collectionproperty getattribute createcollection testclass getname jmeterproperty createproperty testclass getname mapproperty getattribute createmap testclass private static j meter property create property configuration config string test class throws illegal access exception class not found exception instantiation exception string value config get value non nls 1 string name config get attribute name value non nls 1 string oname name string type config get attribute prop type string property class get name non nls 1 do upgrade translation name name updater get current name name test class if test element gui class equals name value name updater get current name value else if test element test class equals name value test class must always agree else value name updater get current name value name test class delete any properties whose name converts to the empty string if oname length 0 name length 0 return null create the property j meter property prop j meter property class for name type new instance prop set name name prop set object value value return prop jmeterproperty createproperty testclass illegalaccessexception classnotfoundexception instantiationexception getvalue getattribute getattribute proptype stringproperty getname nameupdater getcurrentname testclass testelement gui_class nameupdater getcurrentname testelement test_class testclass nameupdater getcurrentname testclass jmeterproperty jmeterproperty forname newinstance setname setobjectvalue private static map create map configuration config string test class throws configuration exception class not found exception illegal access exception instantiation exception map map map class for name config get attribute class new instance configuration items config get children for int i 0 i items length i if items i get name equals property non nls 1 j meter property prop create property items i test class if prop null map put prop get name prop else if items i get name equals testelement non nls 1 map put items i get attribute name new test element property items i get attribute name non nls 1 non nls 2 create test element items i else if items i get name equals collection non nls 1 map put items i get attribute name non nls 1 new collection property items i get attribute name non nls 1 non nls 2 create collection items i test class else if items i get name equals map non nls 1 map put items i get attribute name non nls 1 non nls 2 new map property items i get attribute name non nls 1 non nls 2 create map items i test class return map createmap testclass configurationexception classnotfoundexception illegalaccessexception instantiationexception forname getattribute newinstance getchildren getname jmeterproperty createproperty testclass getname getname getattribute testelementproperty getattribute createtestelement getname getattribute collectionproperty getattribute createcollection testclass getname getattribute mapproperty getattribute createmap testclass private static hash tree generate node configuration config test element element null try element create test element config get child testelement non nls 1 catch exception e log error problem loading part of file e return null hash tree sub tree new listed hash tree element configuration sub nodes config get children node non nls 1 for int i 0 i sub nodes length i hash tree t generate node sub nodes i if t null sub tree add element t return sub tree hashtree generatenode testelement createtestelement getchild hashtree subtree listedhashtree subnodes getchildren subnodes hashtree generatenode subnodes subtree subtree called by result collector load existing file public static void process samples string filename visualizer visualizer result collector rc throws sax exception io exception configuration exception default configuration builder cfgbuilder new default configuration builder configuration saved samples cfgbuilder build from file filename configuration samples saved samples get children final boolean errors only rc is error logging final boolean success only rc is success only logging for int i 0 i samples length i sample result result old save service get sample result samples i if result collector is sample wanted result is successful errors only success only visualizer add result resultcollector loadexistingfile processsamples resultcollector saxexception ioexception configurationexception defaultconfigurationbuilder defaultconfigurationbuilder savedsamples buildfromfile savedsamples getchildren errorsonly iserrorlogging successonly issuccessonlylogging sampleresult oldsaveservice getsampleresult resultcollector issamplewanted issuccessful errorsonly successonly called by result collector record result public static string get serialized sample result sample result result default configuration serializer slzr sample save configuration cfg throws sax exception io exception configuration exception byte array output stream temp out new byte array output stream slzr serialize temp out old save service get configuration result cfg string ser ver temp out to string string line sep system get property line separator non nls 1 remove the xml prefix when using the x jars xakan etc or java 1 4 the serialised output has a newline after the prefix however when using java 1 5 without the x jars the output has no newline at all int index ser ver index of line sep is there a new line if index 1 yes assume it follows the prefix return ser ver substring index if ser ver starts with xml non nls 1 index ser ver index of must exist non nls 1 return line sep ser ver substring index 2 2 for return ser ver resultcollector recordresult getserializedsampleresult sampleresult defaultconfigurationserializer samplesaveconfiguration saxexception ioexception configurationexception bytearrayoutputstream tempout bytearrayoutputstream tempout oldsaveservice getconfiguration server tempout tostring linesep getproperty server indexof linesep server server startswith server indexof linesep server server protected int shape counter 0 public line chart super shape_counter linechart public string getur ls return get property as string report chart urls geturls getpropertyasstring report_chart_urls public void setur ls string urls set property report chart urls urls seturls setproperty report_chart_urls public double convert to double list data string urls this getur ls split url delim double dataset new double urls length data size for int idx 0 idx urls length idx for int idz 0 idz data size idz data set dset data set data get idz sampling stat calculator ss dset get statistics urls idx dataset idx idz get value ss return dataset converttodouble geturls url_delim dataset dataset samplingstatcalculator getstatistics getvalue public j component render chart list dataset array list dset new array list array list xlabels new array list iterator itr dataset iterator while itr has next data set item data set itr next if item null we add the entry dset add item if getx label equals x data filename label xlabels add item get data source name else xlabels add item get month day year date double dbset convert to double dset return render graphics dbset string xlabels to array new string xlabels size jcomponent renderchart arraylist arraylist arraylist arraylist hasnext dataset dataset getxlabel x_data_filename_label getdatasourcename getmonthdayyeardate converttodouble rendergraphics toarray public j component render graphics double data string x axis labels line graph panel new line graph panel set title this get title panel set data data panel setx axis labels x axis labels panel sety axis labels this getur ls split url delim panel setx axis title this get formattedx axis panel sety axis title this gety axis we should make this configurable eventually int width get width int height get height panel set preferred size new dimension width height panel set size new dimension width height panel set width width panel set height width set buffered image new buffered image width height buffered image type int rgb panel paint component this get buffered image create graphics return panel jcomponent rendergraphics xaxislabels linegraph linegraph settitle gettitle setdata setxaxislabels xaxislabels setyaxislabels geturls url_delim setxaxistitle getformattedxaxis setyaxistitle getyaxis _width getwidth _height getheight setpreferredsize _width _height setsize _width _height setwidth _width setheight _width setbufferedimage bufferedimage _width _height bufferedimage type_int_rgb paintcomponent getbufferedimage creategraphics since we only have 4 shapes the method will start with the first shape and keep cycling through the shapes in order param count return array of shapes public shape create shapes int count shape shapes new shape count for int idx 0 idx count idx shapes idx next shape return shapes createshapes nextshape return the next shape return the shape public shape next shape if shape counter shape array length 1 shape counter 0 return shape array shape counter nextshape shape_counter shape_array shape_counter shape_array shape_counter param count return array of strokes public stroke create strokes int count stroke str new stroke count for int idx 0 idx count idx str idx next stroke return str createstrokes nextstroke public stroke next stroke return new basic stroke 1 5f nextstroke basicstroke public j meter error super jmetererror param s public j meter error string s super s jmetererror param cause public j meter error throwable cause jdk1 4 super cause saved cause cause jmetererror savedcause param message param cause public j meter error string message throwable cause jdk1 4 super message cause super message saved cause cause jmetererror savedcause local version of get cause for jdk1 3 support public throwable get cause return saved cause getcause getcause savedcause private final remote sample listener listener public remote test listener wrapper log warn only intended for use in testing listener null remotesamplelistener remotetestlistenerwrapper public remote test listener wrapper remote sample listener l listener l remotetestlistenerwrapper remotesamplelistener public void test started try listener test started catch exception ex log error ex non nls 1 teststarted teststarted public void test ended try listener test ended catch exception ex log error ex non nls 1 testended testended public void test started string host try listener test started host catch exception ex log error ex non nls 1 teststarted teststarted public void test ended string host try listener test ended host catch exception ex log error ex non nls 1 testended testended see test listener test iteration start loop iteration event public void test iteration start loop iteration event event listener test iteration start event testlistener testiterationstart loopiterationevent testiterationstart loopiterationevent testiterationstart public j meter report super jmeterreport public string get icon mappings string icon prop j meter utils get prop default jmeter icons org apache jmeter images icon properties properties p j meter utils load properties icon prop if p null log info icon prop not found using default icon set return default icons log info loaded icon properties from icon prop string iconlist new string p size 3 enumeration pe p keys int i 0 while pe has more elements string key string pe next element string icons j orphan utils split p get property key iconlist i 0 key iconlist i 1 icons 0 if icons length 1 iconlist i 2 icons 1 i return iconlist geticonmappings iconprop jmeterutils getpropdefault jmeterutils loadproperties iconprop iconprop default_icons iconprop hasmoreelements nextelement jorphanutils getproperty see org apache jmeter plugin j meter plugin get resource bundles public string get resource bundles return new string 0 jmeterplugin getresourcebundles getresourcebundles public void start non gui cl option test file cl option log file system set property j meter jmeter non gui true plugin manager install this false startnongui cloption testfile cloption logfile setproperty jmeter jmeter_non_gui pluginmanager public void start gui cl option test file plugin manager install this true report tree model tree model new report tree model report tree listener tree lis new report tree listener tree model tree lis set action handler report action router get instance report gui package get instance tree lis tree model org apache jmeter gui report main frame main new org apache jmeter gui report main frame report action router get instance tree model tree lis component util center component in window main 80 main show report action router get instance action performed new action event main 1 report check dirty add all if test file null file input stream reader null try file f new file test file get argument log info loading file f reader new file input stream f hash tree tree save service load tree reader report gui package get instance set report plan file f get absolute path new report load insert loaded tree 1 tree catch exception e log error failure loading test file e j meter utils report error to user e to string finally j orphan utils close quietly reader startgui cloption testfile pluginmanager reporttreemodel treemodel reporttreemodel reporttreelistener treelis reporttreelistener treemodel treelis setactionhandler reportactionrouter getinstance reportguipackage getinstance treelis treemodel reportmainframe reportmainframe reportactionrouter getinstance treemodel treelis componentutil centercomponentinwindow reportactionrouter getinstance actionperformed actionevent reportcheckdirty add_all testfile fileinputstream testfile getargument fileinputstream hashtree saveservice loadtree reportguipackage getinstance setreportplanfile getabsolutepath reportload insertloadedtree jmeterutils reporterrortouser tostring jorphanutils closequietly param args public void start string args cl args parser parser new cl args parser args options if null parser get error string system err println error parser get error string system out println usage system out println cl util describe options options to string return try initialize properties parser log info version j meter utils getj meter version log info java version system get property java version log info j meter utils getj meter copyright if parser get argument by id version opt null system out println j meter utils getj meter copyright system out println version j meter utils getj meter version else if parser get argument by id help opt null system out println j meter utils get resource file as text org apache jmeter help txt else if parser get argument by id nongui opt null start gui parser get argument by id testfile opt else start non gui parser get argument by id testfile opt parser get argument by id logfile opt catch exception e e print stack trace system out println an error occurred e get message system exit 1 clargsparser clargsparser geterrorstring geterrorstring clutil describeoptions tostring initializeproperties jmeterutils getjmeterversion getproperty jmeterutils getjmetercopyright getargumentbyid version_opt jmeterutils getjmetercopyright jmeterutils getjmeterversion getargumentbyid help_opt jmeterutils getresourcefileastext getargumentbyid nongui_opt startgui getargumentbyid testfile_opt startnongui getargumentbyid testfile_opt getargumentbyid logfile_opt printstacktrace getmessage private void initialize properties cl args parser parser if parser get argument by id propfile opt null j meter utils get properties parser get argument by id propfile opt get argument else j meter utils get properties new driver getj meter dir file separator bin file separator jmeter properties bug 33845 allow direct override of home dir if parser get argument by id jmeter home opt null j meter utils setj meter home new driver getj meter dir else j meter utils setj meter home parser get argument by id jmeter home opt get argument process command line property definitions can occur multiple times properties jmeter props j meter utils getj meter properties list cl options parser get arguments int size cl options size for int i 0 i size i cl option option cl option cl options get i string name option get argument 0 string value option get argument 1 switch option get descriptor get id case propfile2 opt bug 33920 allow multiple props file f new file name try jmeter props load new file input stream f catch file not found exception e log warn can t find additional property file name e catch io exception e log warn error loading additional property file name e break case system property if value length 0 set it log info setting system property name value system get properties set property name value else reset it log warn removing system property name system get properties remove name break case jmeter property if value length 0 set it log info setting j meter property name value jmeter props set property name value else reset it log warn removing j meter property name jmeter props remove name break case loglevel if value length 0 set category log info log level name value logging manager set priority value name else set root level log warn log level name logging manager set priority name break initializeproperties clargsparser getargumentbyid propfile_opt jmeterutils getproperties getargumentbyid propfile_opt getargument jmeterutils getproperties newdriver getjmeterdir getargumentbyid jmeter_home_opt jmeterutils setjmeterhome newdriver getjmeterdir jmeterutils setjmeterhome getargumentbyid jmeter_home_opt getargument jmeterprops jmeterutils getjmeterproperties cloptions getarguments cloptions cloption cloption cloptions getargument getargument getdescriptor getid propfile2_opt jmeterprops fileinputstream filenotfoundexception ioexception system_property getproperties setproperty getproperties jmeter_property jmeter jmeterprops setproperty jmeter jmeterprops loglevel loggingmanager setpriority loglevel loggingmanager setpriority public class simple data writer extends abstract visualizer create the simple data writer public simple data writer init set name get static label simpledatawriter abstractvisualizer simpledatawriter simpledatawriter setname getstaticlabel public string get label resource return simple data writer title non nls 1 getlabelresource simple_data_writer_title initialize the component in the ui private void init set layout new border layout set border make border add make title panel border layout north setlayout borderlayout setborder makeborder maketitlepanel borderlayout does nothing but required by interface public void clear data cleardata does nothing but required by interface param sample ignored public void add sample result sample sampleresult private final int hgap public horizontal panel this 5 center alignment horizontalpanel center_alignment public horizontal panel color bk this sub panel set background bk this set background bk horizontalpanel subpanel setbackground setbackground public horizontal panel int hgap float vertical align super new border layout add sub panel border layout west this hgap hgap this vertical align vertical align horizontalpanel verticalalign borderlayout subpanel borderlayout verticalalign verticalalign public component add component c this won t work right if we remove components but we don t so i m not going to worry about it right now if hgap 0 sub panel get component count 0 sub panel add box create horizontal strut hgap if c instanceof j component j component c set alignmenty vertical align return sub panel add c subpanel getcomponentcount subpanel createhorizontalstrut jcomponent jcomponent setalignmenty verticalalign subpanel private static final thread local local matcher new thread local protected object initial value return new perl5 matcher threadlocal localmatcher threadlocal initialvalue perl5matcher gets perl5 matcher for this thread public static perl5 matcher get matcher return perl5 matcher local matcher get perl5matcher perl5matcher getmatcher perl5matcher localmatcher this method is used by the init method to load the property file that may even reside in the user space or in the classpath under org apache jmeter jmeter properties the method also initialises logging and sets up the default locale todo perhaps remove still used param file the file to load return the properties from the file public static properties get properties string file loadj meter properties file init logging init locale return app properties getproperties loadjmeterproperties initlogging initlocale appproperties initialise j meter logging public static void init logging logging manager initialize logging app properties jmeter initlogging loggingmanager initializelogging appproperties initialise the j meter locale public static void init locale string loc app properties get property language non nls 1 if loc null string parts j orphan utils split loc non nls 1 if parts length 2 set locale new locale parts 0 parts 1 else set locale new locale loc non nls 1 else set locale locale get default jmeter initlocale appproperties getproperty jorphanutils _ setlocale setlocale setlocale getdefault load the j meter properties file if not found then default to org apache jmeter jmeter properties from the classpath c f load properties public static void loadj meter properties string file properties p new properties system get properties input stream is null try file f new file file is new file input stream f p load is catch io exception e try is class loader get system resource as stream org apache jmeter jmeter properties non nls 1 if is null throw new runtime exception could not read j meter properties file p load is catch io exception ex j meter fail could not read internal resource archive is broken finally j orphan utils close quietly is app properties p jmeter loadproperties loadjmeterproperties getproperties inputstream fileinputstream ioexception classloader getsystemresourceasstream runtimeexception jmeter ioexception jmeter jorphanutils closequietly appproperties this method loads a property file that may reside in the user space or in the classpath param file the file to load return the properties from the file public static properties load properties string file properties p new properties input stream is null try file f new file file is new file input stream f p load is catch io exception e try final url resource j meter utils class get class loader get resource file if resource null log warn cannot find file return null is resource open stream if is null log warn cannot open file return null p load is catch io exception ex log warn error reading file ex to string return null finally j orphan utils close quietly is return p loadproperties inputstream fileinputstream ioexception jmeterutils getclassloader getresource openstream ioexception tostring jorphanutils closequietly public static pattern cachelru get pattern cache return pattern cache patterncachelru getpatterncache patterncache get a compiled expression from the pattern cache read only param expression return compiled pattern throws org apache oro text regex malformed pattern exception runtime this should be caught for expressions that may vary e g user input public static pattern get pattern string expression return get pattern expression perl5 compiler read only mask read_only malformedpatternexception getpattern getpattern perl5compiler read_only_mask get a compiled expression from the pattern cache param expression re param options e g read only mask return compiled pattern throws org apache oro text regex malformed pattern exception runtime this should be caught for expressions that may vary e g user input public static pattern get pattern string expression int options return pattern cache get pattern expression options read_only_mask malformedpatternexception getpattern patterncache getpattern public void initialize properties string file system out println initializing properties file get properties file initializeproperties getproperties public static string get search paths string p j meter utils get prop default search paths null non nls 1 string result new string 1 if p null string paths p split non nls 1 result new string paths length 1 for int i 1 i result length i result i paths i 1 result 0 getj meter home lib ext non nls 1 return result getsearchpaths jmeterutils getpropdefault search_paths getjmeterhome provide random numbers param r the upper bound exclusive public static int get random int int r return rand next int r getrandomint nextint changes the current locale re reads resource strings and notifies listeners param loc new locale public static void set locale locale loc log info setting locale to loc to string see bug 29920 get bundle defaults to the property file for the default locale before it defaults to the base property file so we need to change the default locale to ensure the base property file is found locale def null boolean is default false are we the default language if loc get language equals english language is default true def locale get default don t change locale from en gb to en if def get language equals english language locale set default locale english else def null no need to reset locale if loc to string equals ignore resources non nls 1 log warn resource bundles will be ignored ignore resorces true keep existing settings else ignore resorces false resource bundle res bund resource bundle get bundle org apache jmeter resources messages loc non nls 1 resources res bund locale loc final locale res bund locale res bund get locale if is default res bund locale equals loc language change worked check if we at least found the correct language else if res bund locale get language equals loc get language log warn could not find resources for loc to string using res bund locale to string else log error could not find resources for loc to string notify locale change listeners reset locale if necessary so other locales are properly handled if def null locale set default def setlocale tostring getbundle isdefault getlanguage english_language isdefault getdefault en_gb getlanguage english_language setdefault tostring ignoreresources ignoreresorces ignoreresorces resourcebundle resbund resourcebundle getbundle resbund resbundlocale resbund getlocale isdefault resbundlocale resbundlocale getlanguage getlanguage tostring resbundlocale tostring tostring notifylocalechangelisteners setdefault gets the current locale return current locale public static locale get locale return locale getlocale public static void add locale change listener locale change listener listener locale change listeners add listener addlocalechangelistener localechangelistener localechangelisteners public static void remove locale change listener locale change listener listener locale change listeners remove listener removelocalechangelistener localechangelistener localechangelisteners notify all listeners interested in locale changes private static void notify locale change listeners locale change event event new locale change event j meter utils class locale iterator iterator vector locale change listeners clone iterator while iterator has next locale change listener listener locale change listener iterator next listener locale changed event notifylocalechangelisteners localechangeevent localechangeevent jmeterutils localechangelisteners hasnext localechangelistener localechangelistener localechanged gets the resource string for this key if the resource is not found a warning is logged param key the key in the resource file return the resource string if the key is found otherwise return res key key public static string get res string string key return get res string default key res key pfx key non nls 1 res_key getresstring getresstringdefault res_key_pfx gets the resource string for this key if the resource is not found a warning is logged param key the key in the resource file param default value the default value return the resource string if the key is found otherwise return the default deprecated only intended for use in development use get res string string normally public static string get res string string key string default value return get res string default key default value defaultvalue getresstring getresstring defaultvalue getresstringdefault defaultvalue private static string get res string default string key string default value if key null return null resource keys cannot contain spaces and are forced to lower case string res key key replace non nls 1 non nls 2 res key res key to lower case java util locale english string res string null try res string resources get string res key if ignore resorces special mode for debugging resource handling return key catch missing resource exception mre if ignore resorces special mode for debugging resource handling return key log warn error resource string not found res key mre res string default value return res string getresstringdefault defaultvalue reskey _ reskey reskey tolowercase resstring resstring getstring reskey ignoreresorces missingresourceexception ignoreresorces reskey resstring defaultvalue resstring get the locale name as a resource does not log an error if the resource does not exist this is needed to support additional locales as they won t be in existing messages files param locale name return the locale display name as defined in the current locale or the original string if not present public static string get locale string string locale all keys in messages properties are lowercase historical reasons string res key locale to lower case java util locale english try return resources get string res key catch missing resource exception e return locale getlocalestring reskey tolowercase getstring reskey missingresourceexception this gets the currently defined app properties it can only be called after the link get properties string method is called return the j meter properties value public static properties getj meter properties return app properties appproperties getproperties jmeterproperties getjmeterproperties appproperties this looks for the requested image in the classpath under org apache jmeter images name param name description of parameter return the image value public static image icon get image string name try return new image icon j meter utils class get class loader get resource org apache jmeter images name trim non nls 1 catch null pointer exception e log warn no icon for name return null catch no class def found error e can be returned by headless hosts log info no icon for name e get message return null catch internal error e can be returned by headless hosts log info no icon for name e get message return null imageicon getimage imageicon jmeterutils getclassloader getresource nullpointerexception noclassdeffounderror getmessage internalerror getmessage this looks for the requested image in the classpath under org apache jmeter images name and also sets the description of the image which is useful if the icon is going to be placed on the clipboard param name the name of the image param description the description of the image return the image value public static image icon get image string name string description image icon icon get image name if icon null icon set description description return icon imageicon getimage imageicon getimage setdescription public static string get resource file as text string name buffered reader file reader null try string line end system get property line separator non nls 1 file reader new buffered reader new input stream reader j meter utils class get class loader get resource as stream name string buffer text new string buffer string line notnull non nls 1 while line null line file reader read line if line null text append line text append line end done by finally block file reader close return text to string catch null pointer exception e cannot find file return non nls 1 catch io exception e return non nls 1 finally io utils close quietly file reader getresourcefileastext bufferedreader filereader lineend getproperty filereader bufferedreader inputstreamreader jmeterutils getclassloader getresourceasstream stringbuffer stringbuffer filereader readline lineend filereader tostring nullpointerexception ioexception ioutils closequietly filereader creates the vector of timers plugins param properties description of parameter return the timers value public static vector get timers properties properties return instantiate get vector properties timer non nls 1 org apache jmeter timers timer non nls 1 gettimers getvector creates the vector of visualizer plugins param properties description of parameter return the visualizers value public static vector get visualizers properties properties return instantiate get vector properties visualizer non nls 1 org apache jmeter visualizers visualizer non nls 1 getvisualizers getvector creates a vector of sample controller plugins param properties the properties with information about the samplers return the controllers value todo does not appear to be called directly public static vector get controllers properties properties string name controller non nls 1 vector v new vector enumeration names properties keys while names has more elements string prop string names next element if prop starts with name object o instantiate properties get property prop org apache jmeter control sampler controller non nls 1 v add element o return v samplecontroller getcontrollers hasmoreelements nextelement startswith getproperty samplercontroller addelement create a string of class names for a particular sampler controller param properties the properties with info about the samples param name the name of the sampler controller return the test samples value public static string get test samples properties properties string name return string get vector properties name testsample to array new string 0 non nls 1 samplercontroller testsamples gettestsamples getvector toarray create an instance of an org xml sax parser based on the default props return the xml parser value public static xml reader getxml parser xml reader reader null try reader xml reader instantiate get prop default xml parser non nls 1 org apache xerces parsers sax parser non nls 1 org xml sax xml reader non nls 1 reader xml factory newsax parser getxml reader catch exception e reader xml reader instantiate get prop default xml parser non nls 1 org apache xerces parsers sax parser non nls 1 org xml sax xml reader non nls 1 return reader xmlparser xmlreader getxmlparser xmlreader xmlreader getpropdefault saxparser xmlreader xmlfactory newsaxparser getxmlreader xmlreader getpropdefault saxparser xmlreader creates the vector of alias strings param properties description of parameter return the alias value public static hashtable get alias properties properties return get hashtable properties alias non nls 1 getalias gethashtable creates a vector of strings for all the properties that start with a common prefix param properties description of parameter param name description of parameter return the vector value public static vector get vector properties properties string name vector v new vector enumeration names properties keys while names has more elements string prop string names next element if prop starts with name v add element properties get property prop return v getvector hasmoreelements nextelement startswith addelement getproperty creates a table of strings for all the properties that start with a common prefix param properties description of parameter param name description of parameter return the hashtable value public static hashtable get hashtable properties properties string name hashtable t new hashtable enumeration names properties keys while names has more elements string prop string names next element if prop starts with name t put prop substring name length properties get property prop return t gethashtable hasmoreelements nextelement startswith getproperty get a int value with default if not present param prop name the name of the property param default val the default value return the prop default value public static int get prop default string prop name int default val int ans try ans integer value of app properties get property prop name integer to string default val trim int value catch exception e ans default val return ans propname defaultval propdefault getpropdefault propname defaultval valueof appproperties getproperty propname tostring defaultval intvalue defaultval get a boolean value with default if not present param prop name the name of the property param default val the default value return the prop default value public static boolean get prop default string prop name boolean default val boolean ans try string str val app properties get property prop name boolean to string default val trim if str val equals ignore case true str val equals ignore case t non nls 1 non nls 2 ans true else if str val equals ignore case false str val equals ignore case f non nls 1 non nls 2 ans false else ans integer value of str val int value 1 catch exception e ans default val return ans propname defaultval propdefault getpropdefault propname defaultval strval appproperties getproperty propname tostring defaultval strval equalsignorecase strval equalsignorecase strval equalsignorecase strval equalsignorecase valueof strval intvalue defaultval get a long value with default if not present param prop name the name of the property param default val the default value return the prop default value public static long get prop default string prop name long default val long ans try ans long value of app properties get property prop name long to string default val trim long value catch exception e ans default val return ans propname defaultval propdefault getpropdefault propname defaultval valueof appproperties getproperty propname tostring defaultval longvalue defaultval get a string value with default if not present param prop name the name of the property param default val the default value return the prop default value public static string get prop default string prop name string default val string ans try ans app properties get property prop name default val trim catch exception e ans default val return ans propname defaultval propdefault getpropdefault propname defaultval appproperties getproperty propname defaultval defaultval get the value of a j meter property param prop name the name of the property return the value of the j meter property or null if not defined public static string get property string prop name string ans null try ans app properties get property prop name catch exception e ans null return ans jmeter propname jmeter getproperty propname appproperties getproperty propname set a string value param prop name the name of the property param prop value the value of the property return the previous value of the property public static object set property string prop name string prop value return app properties set property prop name prop value propname propvalue setproperty propname propvalue appproperties setproperty propname propvalue sets the selection of the j combo box to the object name from the list in nam vec public static void selj combo box item properties properties j combo box combo vector nam vec string name int idx nam vec index of name combo set selected index idx redisplay combo updateui return jcombobox namvec seljcomboboxitem jcombobox namvec namvec indexof setselectedindex instatiate an object and guarantee its class param class name the name of the class to instantiate param impls the name of the class it subclases return description of the returned value public static object instantiate string class name string impls if class name null class name class name trim if impls null impls impls trim try class c class for name impls try class o class for name class name object res o new instance if c is instance res return res throw new illegal argument exception class name is not an instance of impls catch class not found exception e log error error loading class class name class is not found catch illegal access exception e log error error loading class class name does not have access catch instantiation exception e log error error loading class class name could not instantiate catch no class def found error e log error error loading class class name couldn t find class e get message catch class not found exception e log error error loading class impls was not found return null classname classname classname classname classname forname forname classname newinstance isinstance illegalargumentexception classname classnotfoundexception classname illegalaccessexception classname instantiationexception classname noclassdeffounderror classname getmessage classnotfoundexception instantiate a vector of classes param v description of parameter param class name description of parameter return description of the returned value public static vector instantiate vector v string class name vector i new vector try class c class for name class name enumeration elements v elements while elements has more elements string name string elements next element try object o class for name name new instance if c is instance o i add element o catch class not found exception e log error error loading class name class is not found catch illegal access exception e log error error loading class name does not have access catch instantiation exception e log error error loading class name could not instantiate catch no class def found error e log error error loading class name couldn t find class e get message catch class not found exception e log error error loading class class name class is not found return i classname classname forname classname hasmoreelements nextelement forname newinstance isinstance addelement classnotfoundexception illegalaccessexception instantiationexception noclassdeffounderror getmessage classnotfoundexception classname tokenize a string into a vector of tokens param string description of parameter param separator description of parameter return description of the returned value todo move to j orphan utils public static vector tokenize string string string separator vector v new vector string tokenizer s new string tokenizer string separator while s has more tokens v add element s next token return v jorphanutils stringtokenizer stringtokenizer hasmoretokens addelement nexttoken create a button with the netscape style param name description of parameter param listener description of parameter return description of the returned value public static j button create button string name action listener listener j button button new j button get image name on gif non nls 1 button set disabled icon get image name off gif non nls 1 button set rollover icon get image name over gif non nls 1 button set pressed icon get image name down gif non nls 1 button set action command name button add action listener listener button set rollover enabled true button set focus painted false button set border painted false button set opaque false button set preferred size new dimension 24 24 return button jbutton createbutton actionlistener jbutton jbutton getimage setdisabledicon getimage setrollovericon getimage setpressedicon getimage setactioncommand addactionlistener setrolloverenabled setfocuspainted setborderpainted setopaque setpreferredsize create a button with the netscape style param name description of parameter param listener description of parameter return description of the returned value public static j button create simple button string name action listener listener j button button new j button get image name gif non nls 1 button set action command name button add action listener listener button set focus painted false button set border painted false button set opaque false button set preferred size new dimension 25 25 return button jbutton createsimplebutton actionlistener jbutton jbutton getimage setactioncommand addactionlistener setfocuspainted setborderpainted setopaque setpreferredsize report an error through a dialog box title defaults to error title resource string param error msg the error message public static void report error to user string error msg report error to user error msg j meter utils get res string error title non nls 1 error_title errormsg reporterrortouser errormsg reporterrortouser errormsg jmeterutils getresstring error_title report an error through a dialog box param error msg the error message param title msg title string public static void report error to user string error msg string title msg if error msg null error msg unknown error see log file log warn unknown error new throwable error msg null gui package instance gui package get instance if instance null system out println error msg return done try j option pane show message dialog instance get main frame error msg title msg j option pane error message catch headless exception e log warn report error to user error msg caused e errormsg titlemsg reporterrortouser errormsg titlemsg errormsg errormsg errormsg guipackage guipackage getinstance errormsg joptionpane showmessagedialog getmainframe errormsg titlemsg joptionpane error_message headlessexception reporterrortouser errormsg finds a string in an array of strings and returns the param array array of strings param value string to compare to array values return index of value in array or 1 if not in array todo move to j orphan utils public static int find in array string array string value int count 1 int index 1 if array null value null while count array length if array count null array count equals value index count break return index jorphanutils findinarray takes an array of strings and a tokenizer character and returns a string of all the strings concatenated with the tokenizer string in between each one param splittee array of objects to be concatenated param split char object to unsplit the strings with return array of all the tokens todo move to j orphan utils public static string unsplit object splittee object split char string buffer ret val new string buffer int count 1 while count splittee length if splittee count null ret val append splittee count if count 1 splittee length splittee count 1 null ret val append split char return ret val to string splitchar jorphanutils splitchar stringbuffer retval stringbuffer retval retval splitchar retval tostring takes an array of strings and a tokenizer character and returns a string of all the strings concatenated with the tokenizer string in between each one param splittee array of objects to be concatenated param split char object to unsplit the strings with param def default value to replace null values in array return array of all the tokens todo move to j orphan utils public static string unsplit object splittee object split char string def string buffer ret val new string buffer int count 1 while count splittee length if splittee count null ret val append splittee count else ret val append def if count 1 splittee length ret val append split char return ret val to string splitchar jorphanutils splitchar stringbuffer retval stringbuffer retval retval retval splitchar retval tostring get the j meter home directory does not include the trailing separator return the home directory public static string getj meter home return jm dir jmeter getjmeterhome jmdir get the j meter bin directory does not include the trailing separator return the bin directory public static string getj meter bin dir return jm bin jmeter getjmeterbindir jmbin public static void setj meter home string home jm dir home jm bin jm dir file separator bin non nls 1 setjmeterhome jmdir jmbin jmdir gets the j meter version return the j meter version string public static string getj meter version return j meter version getversion jmeter jmeter getjmeterversion jmeterversion gets the j meter copyright return the j meter copyright string public static string getj meter copyright return j meter version copyright jmeter jmeter getjmetercopyright jmeterversion determine whether we are in expert mode certain features may be hidden from user s view unless in expert mode return true iif we re in expert mode public static boolean is expert mode return j meter utils get prop default expert mode property false isexpertmode jmeterutils getpropdefault expert_mode_property find a file in the current directory or in the j meter bin directory param file name return file object public static file find file string file name file f new file file name if f exists f new file getj meter bin dir file name return f jmeter filename findfile filename filename getjmeterbindir filename returns the cached result from calling inet address get local host get host address return string representation of local ip address public static synchronized string get local hostip if local hostip null get local host details return local hostip inetaddress getlocalhost gethostaddress getlocalhostip localhostip getlocalhostdetails localhostip returns the cached result from calling inet address get local host get host name return local host name public static synchronized string get local host name if local host name null get local host details return local host name inetaddress getlocalhost gethostname getlocalhostname localhostname getlocalhostdetails localhostname returns the cached result from calling inet address get local host get canonical host name return local host name in canonical form public static synchronized string get local host full name if local host full name null get local host details return local host full name inetaddress getlocalhost getcanonicalhostname getlocalhostfullname localhostfullname getlocalhostdetails localhostfullname private static void get local host details inet address local host null try local host inet address get local host catch unknown host exception e1 log error unable to get local host ip address return todo perhaps this should be a fatal error local hostip local host get host address local host name local host get host name local host full name local host get canonical host name getlocalhostdetails inetaddress localhost localhost inetaddress getlocalhost unknownhostexception localhostip localhost gethostaddress localhostname localhost gethostname localhostfullname localhost getcanonicalhostname private remote sample listener listener public remote sample listener wrapper remote sample listener l listener l remotesamplelistener remotesamplelistenerwrapper remotesamplelistener public remote sample listener wrapper remotesamplelistenerwrapper public void sample occurred sample event e try listener sample occurred e catch remote exception err log error err non nls 1 sampleoccurred sampleevent sampleoccurred remoteexception public void sample started sample event e try listener sample started e catch remote exception err log error err non nls 1 samplestarted sampleevent samplestarted remoteexception public void sample stopped sample event e try listener sample stopped e catch remote exception err log error err non nls 1 samplestopped sampleevent samplestopped remoteexception private string name public spline model samples new sampling stat calculator spline splinemodel samplingstatcalculator public synchronized void set listener graph listener vis listener vis setlistener graphlistener public synchronized void set name string new name name new name setname newname newname public boolean is editable return true iseditable public synchronized spline3 get data curve return data curve getdatacurve datacurve public class get gui class return org apache jmeter visualizers spline visualizer class getguiclass splinevisualizer public collection get add list return null getaddlist public long get minimum return samples get min long value getminimum getmin longvalue public long get maximum return samples get max long value getmaximum getmax longvalue public long get average return long samples get mean getaverage getmean public long get current return samples get current sample get data getcurrent getcurrentsample getdata public long get sample int i return samples get sample i get data getsample getsample getdata public long get number of collected samples return samples get count getnumberofcollectedsamples getcount public synchronized string get name return name getname public void uncompile clear data cleardata public synchronized void clear data this graph clear samples clear this data curve null if listener null listener update gui cleardata datacurve updategui public synchronized void add sample result sample result samples add sample sample result long n samples get count if n number of nodes refresh period 0 float float node new float number of nodes notused long long sample get samples load each node long load factor n number of nodes for int i 0 i number of nodes i for int j 0 j load factor j float node i samples get sample int i load factor j get data float node i float node i load factor compute the new spline curve data curve new spline3 float node if listener null listener update gui else do nothing wait for the next pile to complete sampleresult sampleresult addsample sampleresult getcount numberofnodes refreshperiod floatnode numberofnodes longsample getsamples loadfactor numberofnodes numberofnodes loadfactor floatnode getsample loadfactor getdata floatnode floatnode loadfactor datacurve floatnode updategui public class http test sample gui2 extends http test sample gui public http test sample gui2 super httptestsamplegui2 httptestsamplegui httptestsamplegui2 public test element create test element http sampler base sampler http sampler factory new instance http sampler factory http sampler apache modify test element sampler return sampler testelement createtestelement httpsamplerbase httpsamplerfactory newinstance httpsamplerfactory http_sampler_apache modifytestelement use this instead of get label resource otherwise get doc anchor below does not work public string get static label return j meter utils get res string web testing2 title non nls 1 getlabelresource getdocanchor getstaticlabel jmeterutils getresstring web_testing2_title documentation is shared with our parent public string get doc anchor return super get static label replace non nls 1 non nls 2 getdocanchor getstaticlabel _ private file panel soap xml file new file panel public soap sampler gui init filepanel soapxmlfile filepanel soapsamplergui public string get label resource return soap sampler title non nls 1 getlabelresource soap_sampler_title public test element create test element soap sampler sampler new soap sampler modify test element sampler return sampler testelement createtestelement soapsampler soapsampler modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element s this configure test element s if s instanceof soap sampler soap sampler sampler soap sampler s sampler seturl data url field get text sampler set xml data soap xml get text sampler set xml file soap xml file get filename sampler setsoap action soap action get text sampler set sendsoap action send soap action is selected sampler set use keep alive use keep alive is selected testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement soapsampler soapsampler soapsampler seturldata urlfield gettext setxmldata soapxml gettext setxmlfile soapxmlfile getfilename setsoapaction soapaction gettext setsendsoapaction sendsoapaction isselected setusekeepalive usekeepalive isselected implements j metergui component clear gui public void clear gui super clear gui url field set text non nls 1 soap action set text non nls 1 soap xml set text non nls 1 send soap action set selected true soap xml file set filename non nls 1 use keep alive set selected false jmeterguicomponent cleargui cleargui cleargui urlfield settext soapaction settext soapxml settext sendsoapaction setselected soapxmlfile setfilename usekeepalive setselected private void init set layout new border layout set border make border add make title panel border layout north url field new j labeled text field j meter utils get res string url 10 non nls 1 soap xml new j labeled text area j meter utils get res string soap data title non nls 1 soap action new j labeled text field 10 non nls 1 send soap action new j check box j meter utils get res string soap send action true non nls 1 use keep alive new j check box j meter utils get res string use keepalive non nls 1 j panel main panel new j panel new border layout j panel soap action panel new j panel soap action panel set layout new grid bag layout grid bag constraints c new grid bag constraints c fill grid bag constraints horizontal c gridwidth 2 c gridx 0 c gridy 0 c weightx 1 soap action panel add url field c c fill grid bag constraints none c gridwidth 1 c gridy 1 c weightx 0 soap action panel add send soap action c c gridx 1 c fill grid bag constraints horizontal c weightx 1 soap action panel add soap action c c fill grid bag constraints horizontal c gridwidth 2 c gridy 2 c gridx 0 soap action panel add use keep alive c main panel add soap action panel border layout north main panel add soap xml border layout center main panel add soap xml file border layout south send soap action add action listener new action listener public void action performed action event e soap action set enabled send soap action is selected add main panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout urlfield jlabeledtextfield jmeterutils getresstring soapxml jlabeledtextarea jmeterutils getresstring soap_data_title soapaction jlabeledtextfield sendsoapaction jcheckbox jmeterutils getresstring soap_send_action usekeepalive jcheckbox jmeterutils getresstring use_keepalive jpanel mainpanel jpanel borderlayout jpanel soapactionpanel jpanel soapactionpanel setlayout gridbaglayout gridbagconstraints gridbagconstraints gridbagconstraints soapactionpanel urlfield gridbagconstraints soapactionpanel sendsoapaction gridbagconstraints soapactionpanel soapaction gridbagconstraints soapactionpanel usekeepalive mainpanel soapactionpanel borderlayout mainpanel soapxml borderlayout mainpanel soapxmlfile borderlayout sendsoapaction addactionlistener actionlistener actionperformed actionevent soapaction setenabled sendsoapaction isselected mainpanel borderlayout send soap action add action listener new action listener public void action performed action event e soap action set enabled send soap action is selected sendsoapaction addactionlistener actionlistener actionperformed actionevent soapaction setenabled sendsoapaction isselected public void configure test element el super configure el soap sampler sampler soap sampler el url field set text sampler geturl data send soap action set selected sampler get sendsoap action soap action set text sampler getsoap action soap xml set text sampler get xml data soap xml file set filename sampler get xml file use keep alive set selected sampler get use keep alive testelement soapsampler soapsampler urlfield settext geturldata sendsoapaction setselected getsendsoapaction soapaction settext getsoapaction soapxml settext getxmldata soapxmlfile setfilename getxmlfile usekeepalive setselected getusekeepalive public dimension get preferred size return get minimum size getpreferredsize getminimumsize private int loop count 0 for get iter count public run time loopcount getitercount runtime public void set runtime long seconds set property new long property seconds seconds setruntime setproperty longproperty public void set runtime string seconds set property new string property seconds seconds setruntime setproperty stringproperty public long get runtime try return long parse long get property as string seconds catch number format exception e return 0l getruntime parselong getpropertyasstring numberformatexception public string get runtime string return get property as string seconds getruntimestring getpropertyasstring public boolean is done if get runtime 0 get sub controllers size 0 return super is done return true runtime is zero no point staying around isdone getruntime getsubcontrollers isdone private boolean end of loop return system current time millis start time 1000 get runtime endofloop currenttimemillis starttime getruntime public sampler next if start time 0 start time system current time millis if end of loop re initialize reset loop count return null return super next starttime starttime currenttimemillis endofloop reinitialize resetloopcount protected sampler next is null throws next is null exception re initialize if end of loop reset loop count return null return next nextisnull nextisnullexception reinitialize endofloop resetloopcount protected void increment loop count loop count incrementloopcount loopcount protected void reset loop count loop count 0 start time 0 resetloopcount loopcount starttime this is needed for once only to work like other loop controllers protected int get iter count return loop count 1 onceonly getitercount loopcount protected void re initialize set first true reset current increment loop count recover running version reinitialize setfirst resetcurrent incrementloopcount recoverrunningversion private j text area data public example sampler gui init jtextarea examplesamplergui see org apache jmeter gui j metergui component get static label public string get label resource return example title non nls 1 jmeterguicomponent getstaticlabel getlabelresource example_title see org apache jmeter gui j metergui component configure org apache jmeter testelement test element public void configure test element element data set text element get property as string example sampler data super configure element jmeterguicomponent testelement testelement settext getpropertyasstring examplesampler public test element create test element example sampler sampler new example sampler modify test element sampler return sampler testelement createtestelement examplesampler examplesampler modifytestelement public void modify test element test element te te clear configure test element te te set property example sampler data data get text modifytestelement testelement configuretestelement setproperty examplesampler gettext private void init standard setup set layout new border layout 0 5 set border make border add make title panel border layout north add the standard title specific setup add create data panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout createdatapanel borderlayout private component create data panel j label label new j label j meter utils get res string example data non nls 1 data new j text area data set name example sampler data label set label for data j panel data panel new j panel new border layout 5 0 data panel add label border layout west data panel add data border layout center return data panel createdatapanel jlabel jlabel jmeterutils getresstring example_data jtextarea setname examplesampler setlabelfor jpanel datapanel jpanel borderlayout datapanel borderlayout datapanel borderlayout datapanel public void clear gui super clear gui data set text non nls 1 cleargui cleargui settext public final class class context extends security manager private constructor to prevent instantiation private class context classcontext securitymanager classcontext gets the calling context as an array of classes class 0 is this class return class list of classes in the callers context public static class get my class context return instance get class context getmyclasscontext _instance getclasscontext get the name of the class at a particular stack depth i 0 gives this class param i stack depth return string name of class at depth i public static string get caller class name at int i return instance get class context i get name getcallerclassnameat _instance getclasscontext getname private string file contents null public publisher sampler file_contents publishersampler the implementation calls test started without any parameters public void test started string test test started teststarted teststarted teststarted the implementation calls test ended without any parameters public void test ended string test test ended testended testended testended end test cleans up the client see junit framework test listener end test junit framework test public void test ended log debug publisher sampler test ended called client pool clear client endtest testlistener endtest testended publishersampler testended clientpool clearclient public void test started teststarted no implementation provided for the sampler it is necessary in this case public void test iteration start loop iteration event event testiterationstart loopiterationevent initialize the publisher client private void init client this pub new publisher this get usejndi properties as boolean this getjndi initial context factory this get provider url this get connection factory this get topic this is use auth this get username this get password client pool add client this pub log debug publisher sampler init client called initclient getusejndipropertiesasboolean getjndiinitialcontextfactory getproviderurl getconnectionfactory gettopic isuseauth getusername getpassword clientpool addclient publishersampler initclient the implementation calls sample without any parameters public sample result sample entry e return this sample sampleresult the implementation will publish n messages within a for loop once n messages are published it sets the attributes of sample result return the populated sample result public sample result sample sample result result new sample result result set sample label get name if this pub null this init client int loop this get iteration count if this pub null result sample start for int idx 0 idx loop idx string tmsg this get message content this pub publish tmsg this buffer append tmsg result sample end string content this buffer to string result set bytes content get bytes length result set response code message published successfully result set response message loop messages published result set successful true result set response data content get bytes result set sample count loop this buffer set length 0 return result sampleresult sampleresult sampleresult sampleresult setsamplelabel getname initclient getiterationcount samplestart getmessagecontent sampleend tostring setbytes getbytes setresponsecode setresponsemessage setsuccessful setresponsedata getbytes setsamplecount setlength method will check the setting and get the contents for the message return the contents for the message private string get message content if this get config choice equals jms publisher gui use file rsc in the case the test uses a file we set it locally and prevent loading the file repeatedly if this file contents null this file contents this get file content this get input file return this file contents else if this get config choice equals jms publisher gui use random rsc maybe we should consider creating a global cache for the random files to make j meter more efficient string fname fserver get random file this get random path new string txt obj get absolute path return this get file content fname else return this get text message getmessagecontent getconfigchoice jmspublishergui use_file_rsc file_contents file_contents getfilecontent getinputfile file_contents getconfigchoice jmspublishergui use_random_rsc jmeter getrandomfile getrandompath getabsolutepath getfilecontent gettextmessage the implementation uses text file to load the contents of the file and returns a string param path return the contents of the file public string get file content string path text file tf new text file path return tf get text textfile getfilecontent textfile textfile gettext get set properties set the config choice param choice public void set config choice string choice set property config choice choice setconfigchoice setproperty config_choice return the config choice converts from old jmx files which used the local language string public string get config choice allow for the old jmx file which used the local language string string config get property as string config choice if config equals use file localname config equals jms publisher gui use file rsc return jms publisher gui use file rsc if config equals use random localname config equals jms publisher gui use random rsc return jms publisher gui use random rsc return config will be the 3rd option which is not checked specifically getconfigchoice getpropertyasstring config_choice use_file_localname jmspublishergui use_file_rsc jmspublishergui use_file_rsc use_random_localname jmspublishergui use_random_rsc jmspublishergui use_random_rsc set the source of the message param choice public void set message choice string choice set property message choice choice setmessagechoice setproperty message_choice return the source of the message public string get message choice return get property as string message choice getmessagechoice getpropertyasstring message_choice set the input file for the publisher param file public void set input file string file set property input file file setinputfile setproperty input_file return the path of the input file public string get input file return get property as string input file getinputfile getpropertyasstring input_file set the random path for the messages param path public void set random path string path set property random path path setrandompath setproperty random_path return the random path for messages public string get random path return get property as string random path getrandompath getpropertyasstring random_path set the text for the message param message public void set text message string message set property text msg message settextmessage setproperty text_msg return the text for the message public string get text message return get property as string text msg gettextmessage getpropertyasstring text_msg private static final string init file beanshell preprocessor init non nls 1 protected string get init file property return init file init_file getinitfileproperty init_file public void process final bean shell interpreter bsh interpreter get bean shell interpreter if bsh interpreter null log error bean shell not found return j meter context jmctx j meter context service get context j meter variables vars jmctx get variables sampler sam jmctx get current sampler sample result prev jmctx get previous result try add variables for access to context and variables bsh interpreter set ctx jmctx non nls 1 bsh interpreter set vars vars non nls 1 bsh interpreter set sampler sam non nls 1 bsh interpreter set prev prev non nls 1 process file or script bsh interpreter catch j meter exception e log warn problem in bean shell script e beanshellinterpreter bshinterpreter getbeanshellinterpreter bshinterpreter beanshell jmetercontext jmetercontextservice getcontext jmetervariables getvariables getcurrentsampler sampleresult getpreviousresult bshinterpreter bshinterpreter bshinterpreter bshinterpreter processfileorscript bshinterpreter jmeterexception beanshell set the path where xml messages are stored for random selection public void set xml path loc string path set property xml path loc path setxmlpathloc setproperty xml_path_loc get the path where xml messages are stored this is the directory where j meter will randomly select a file public string get xml path loc return get property as string xml path loc jmeter getxmlpathloc getpropertyasstring xml_path_loc it s kinda obvious but we state it anyways set the xml file with a string path param filename public void set xml file string filename set property xml data file filename setxmlfile setproperty xml_data_file get the file location of the xml file return string file path public string get xml file return get property as string xml data file getxmlfile getpropertyasstring xml_data_file method is used internally to check if a random file should be used for the message messages must be valid this is one way to load test with different messages the limitation of this approach is parsing xml takes cpu resources so it could affect j meter gui responsiveness return string filename protected string get random file name if this get xml path loc null file src new file this get xml path loc if src is directory src list null file file list src list files new j meter file filter new string xml false file one file list random next int file list length return the absolute path of the file return one get absolute path return get xml file return get xml file jmeter getrandomfilename getxmlpathloc getxmlpathloc isdirectory filelist listfiles jmeterfilefilter filelist nextint filelist absolutepath getabsolutepath getxmlfile getxmlfile set the xml data param data public void set xml data string data set property xml data data setxmldata setproperty xml_data get the xml data as a string return string data public string get xml data return get property as string xml data getxmldata getpropertyasstring xml_data set the soap action which should be in the form of an urn param data public void set soap action string data set property soap action data setsoapaction setproperty soap_action return the soap action string return string soap action public string get soap action return get property as string soap action getsoapaction getpropertyasstring soap_action set the memory cache param cache public void set memory cache boolean cache set property memory cache string value of cache setmemorycache setproperty memory_cache valueof get the memory cache return boolean cache public boolean get memory cache return get property as boolean memory cache getmemorycache getpropertyasboolean memory_cache set whether the sampler should read the response or not param read public void set read response boolean read set property read response string value of read setreadresponse setproperty read_response valueof return whether or not to read the response return boolean public boolean get read response return this get property as boolean read response getreadresponse getpropertyasboolean read_response set whether or not to use a proxy param proxy public void set use proxy boolean proxy set property use proxy string value of proxy setuseproxy setproperty use_proxy valueof return whether or not to use proxy return true if should use proxy public boolean get use proxy return this get property as boolean use proxy getuseproxy getpropertyasboolean use_proxy set the proxy hostname param host public void set proxy host string host set property proxy host host setproxyhost setproperty proxy_host return the proxy hostname return the proxy hostname public string get proxy host this check proxy return this get property as string proxy host getproxyhost checkproxy getpropertyasstring proxy_host set the proxy port param port public void set proxy port string port set property proxy port port setproxyport setproperty proxy_port return the proxy port return the proxy port public int get proxy port this check proxy return this get property as int proxy port getproxyport checkproxy getpropertyasint proxy_port param url public void set wsdlurl string url this set property wsdl url url setwsdlurl setproperty wsdl_url method returns the wsdl url return the wsdl url public string get wsdlurl return get property as string wsdl url getwsdlurl getpropertyasstring wsdl_url private void check proxy if j meter is nongui this set use proxy true we check to see if the proxy host and port are set string port this get property as string proxy port string host this get property as string proxy host if host null host length 0 it s not set lets check if the user passed proxy host and port from command line host system get property http proxy host if host null this set proxy host host if port null port length 0 it s not set lets check if the user passed proxy host and port from command line port system get property http proxy port if port null this set proxy port port checkproxy jmeter isnongui setuseproxy getpropertyasstring proxy_port getpropertyasstring proxy_host getproperty proxyhost setproxyhost getproperty proxyport setproxyport private org w3c dom element create document throws sax exception io exception document doc null string next this get random file name get filename or note that the filename is also used as a key to the pool if used documents provided in the testplan are not currently pooled as they may change between samples if next length 0 get memory cache doc dom pool get document next if doc null doc open document next if doc null we created the document dom pool put document next doc else must be local content or not using pool doc open document next if doc null return null return doc get document element createdocument saxexception ioexception getrandomfilename getmemorycache dompool getdocument opendocument dompool putdocument opendocument getdocumentelement open the file and create a document param file input filename or empty if using data from tesplan return document throws io exception throws sax exception private document open document string file throws sax exception io exception consider using apache commons pool to create a pool of document builders or make sure xml parser utils creates builders efficiently document builder xdb xml parser utils getxml doc builder xdb set error handler null suppress messages to stdout document doc null if either a file or path location is given get the file object if file length 0 we have a file if this get read response text file tfile new text file file file contents tfile get text file input stream file input stream null try file input stream new file input stream file doc xdb parse file input stream finally io utils close quietly file input stream else must be a here document file contents get xml data if file contents null file contents length 0 doc xdb parse new input source new string reader file contents else log warn no post data provided return doc ioexception saxexception opendocument saxexception ioexception xmlparserutils documentbuilder xmlparserutils getxmldocbuilder seterrorhandler getreadresponse textfile textfile filecontents gettext fileinputstream fileinputstream fileinputstream fileinputstream fileinputstream ioutils closequietly fileinputstream filecontents getxmldata filecontents filecontents inputsource stringreader filecontents protected http sample result sample url u string s boolean b int i throw new runtime exception not implemented should not be called httpsampleresult runtimeexception sample the url using apache soap driver implementation note for myself and those that are curious current logic marks the end after the response has been read if read response is set to false the buffered reader will read but do nothing with it essentially the stream from the server goes into the ether public sample result sample sample result result new sample result result set successful false assume it will fail result set response code 000 ditto non nls 1 result set sample label get name try result seturl this get url org w3c dom element rdoc create document if rdoc null throw new soap exception could not create document null set the response defaults result set data encoding encoding result set content type text xml non nls 1 result set data type sample result text result set sampler data file contents warning could be large envelope msg env envelope unmarshall rdoc create a new message message msg new message result sample start soaphttp connection spconn null if a blank header manager exists try to get the soaphttp connection after the first request there should be a connection object stored with the cookie header info if this get header manager null this get header manager getsoap header null spconn soaphttp connection this get header manager getsoap header else spconn new soaphttp connection spconn set timeout get timeout as int set the auth thanks to ki yun roe for contributing the patch i cleaned up the patch slightly 5 26 05 if get auth manager null if get auth manager get auth forurl get url null auth manager authmanager get auth manager authorization auth authmanager get auth forurl get url spconn set user name auth get user spconn set password auth get pass else log warn the url for the auth was null username and password not set check the proxy string phost int pport 0 if use proxy is set we try to pick up the proxy host and port from either the text fields or from j meter util if they were passed from command line if this get use proxy if this get proxy host length 0 this get proxy port 0 phost this get proxy host pport this get proxy port else if system get property http proxy host null system get property http proxy port null phost system get property http proxy host pport integer parse int system get property http proxy port if for some reason the host is blank and the port is zero the sampler will fail silently if phost length 0 pport 0 spconn set proxy host phost spconn set proxy port pport if proxy user length 0 proxy pass length 0 spconn set proxy user name proxy user spconn set proxy password proxy pass by default we maintain the session spconn set maintain session true msg setsoap transport spconn msg send this get url this get soap action msg env result set response headers convert soap headers spconn get headers if this get header manager null this get header manager setsoap header spconn buffered reader br null if spconn receive null br spconn receive soap context sc spconn get responsesoap context set details from the actual response needs to be done before response can be stored final string content type sc get content type result set content type content type result set encoding and type content type int length 0 if get read response string writer sw new string writer length io utils copy br sw result sample end result set response data sw to string get bytes result get data encoding with default else by not reading the response for real it improves the performance on slow clients length br read result sample end result set response data j meter utils get res string read response message get bytes non nls 1 it is not possible to access the actual http response code so we assume no data means failure if length 0 result set successful true result set response codeok result set response messageok else result set successful false result set response code 999 result set response message empty response else result sample end result set successful false final string content type spconn get responsesoap context get content type result set content type content type result set encoding and type content type result set response data spconn get responsesoap context to string get bytes result get data encoding with default if br null br close reponse code doesn t really apply since the soap driver doesn t provide a response code catch illegal argument exception exception string message exception get message log warn message result set response message message catch sax exception exception log warn exception to string result set response message exception get message catch soap exception exception log warn exception to string result set response message exception get message catch malformedurl exception exception string message exception get message log warn message result set response message message catch io exception exception string message exception get message log warn message result set response message message catch no class def found error error log error missing class error result set response message error to string catch exception exception if javax mail messaging exception equals exception get class get name log warn exception to string result set response message exception get message else log error problem processing the soap request exception result set response message exception to string finally make sure the sample start time and sample end time are recorded in order not to confuse the statistics calculation methods if an error occurs and an exception is thrown it is possible that the result sample start or result sample end won t be called if result get start time 0 result sample start if result get end time 0 result sample end return result sampleresult sampleresult sampleresult setsuccessful setresponsecode setsamplelabel getname geturl createdocument soapexception setdataencoding setcontenttype setdatatype sampleresult setsamplerdata filecontents msgenv samplestart soaphttpconnection headermanager soaphttpconnection getheadermanager getheadermanager getsoapheader soaphttpconnection getheadermanager getsoapheader soaphttpconnection settimeout gettimeoutasint kiyun getauthmanager getauthmanager getauthforurl geturl authmanager getauthmanager getauthforurl geturl setusername getuser setpassword getpass jmeterutil getuseproxy getproxyhost getproxyport getproxyhost getproxyport getproperty proxyhost getproperty proxyport getproperty proxyhost parseint getproperty proxyport setproxyhost setproxyport proxy_user proxy_pass setproxyusername proxy_user setproxypassword proxy_pass setmaintainsession setsoaptransport geturl getsoapaction msgenv setresponseheaders convertsoapheaders getheaders getheadermanager getheadermanager setsoapheader bufferedreader soapcontext getresponsesoapcontext contenttype getcontenttype setcontenttype contenttype setencodingandtype contenttype getreadresponse stringwriter stringwriter ioutils sampleend setresponsedata tostring getbytes getdataencodingwithdefault sampleend setresponsedata jmeterutils getresstring read_response_message getbytes setsuccessful setresponsecodeok setresponsemessageok setsuccessful setresponsecode setresponsemessage sampleend setsuccessful contenttype getresponsesoapcontext getcontenttype setcontenttype contenttype setencodingandtype contenttype setresponsedata getresponsesoapcontext tostring getbytes getdataencodingwithdefault illegalargumentexception getmessage setresponsemessage saxexception tostring setresponsemessage getmessage soapexception tostring setresponsemessage getmessage malformedurlexception getmessage setresponsemessage ioexception getmessage setresponsemessage noclassdeffounderror setresponsemessage tostring messagingexception getclass getname tostring setresponsemessage getmessage setresponsemessage tostring samplestart sampleend getstarttime samplestart getendtime sampleend we override this to prevent the wrong encoding and provide no implementation we want to reuse the other parts of http sampler but not the connection the connection is handled by the apache soap driver public void add encoded argument string name string value string meta data httpsampler addencodedargument metadata public string convert soap headers hashtable ht enumeration en ht keys string buffer buf new string buffer while en has more elements object key en next element buf append string key append append string ht get key append n non nls 1 non nls 2 return buf to string convertsoapheaders stringbuffer stringbuffer hasmoreelements nextelement tostring public string get timeout return get property as string timeout gettimeout getpropertyasstring public int get timeout as int return get property as int timeout gettimeoutasint getpropertyasint public void set timeout string text set property timeout text settimeout setproperty public data source element bean info super data source element class create property group var name new string data source create property group pool new string pool max timeout trim interval autocommit create property group keep alive new string keep alive connection age check query create property group database new string db url driver username password property descriptor p property data source p set value not undefined boolean true p set value default p property pool max p set value not undefined boolean true p set value default 10 p property timeout p set value not undefined boolean true p set value default 10000 p property trim interval p set value not undefined boolean true p set value default 60000 p property autocommit p set value not undefined boolean true p set value default boolean true p property keep alive p set value not undefined boolean true p set value default boolean true p property connection age p set value not undefined boolean true p set value default 5000 p property check query p set value not undefined boolean true p set value default select 1 p property db url p set value not undefined boolean true p set value default p property driver p set value not undefined boolean true p set value default p property username p set value not undefined boolean true p set value default p property password p set value not undefined boolean true p set value default datasourceelementbeaninfo datasourceelement createpropertygroup varname datasource createpropertygroup poolmax triminterval createpropertygroup keepalive connectionage checkquery createpropertygroup dburl propertydescriptor datasource setvalue not_undefined setvalue poolmax setvalue not_undefined setvalue setvalue not_undefined setvalue triminterval setvalue not_undefined setvalue setvalue not_undefined setvalue keepalive setvalue not_undefined setvalue connectionage setvalue not_undefined setvalue checkquery setvalue not_undefined setvalue dburl setvalue not_undefined setvalue setvalue not_undefined setvalue setvalue not_undefined setvalue setvalue not_undefined setvalue public class summariser gui extends abstract listener gui public summariser gui super init summarisergui abstractlistenergui summarisergui public string get label resource return summariser title non nls 1 getlabelresource summariser_title public void configure test element el super configure el testelement see org apache jmeter gui j metergui component create test element public test element create test element summariser summariser new summariser modify test element summariser return summariser jmeterguicomponent createtestelement testelement createtestelement modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element summariser super configure test element summariser testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement private void init set layout new border layout set border make border add make title panel border layout north setlayout borderlayout setborder makeborder maketitlepanel borderlayout create a new login config gui as a standalone component public login config gui this true loginconfiggui loginconfiggui create a new login config gui as either a standalone or an embedded component param display name indicates whether or not this component should display its name if true this is a standalone component if false this component is intended to be used as a subpanel for another component public login config gui boolean display name this display name display name init loginconfiggui displayname loginconfiggui displayname displayname displayname public string get label resource return login config element non nls 1 getlabelresource login_config_element a newly created component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui param element the test element to configure public void configure test element element super configure element username set text element get property as string config test element username password set text element get property as string config test element password testelement testelement settext getpropertyasstring configtestelement settext getpropertyasstring configtestelement implements j metergui component create test element public test element create test element config test element element new config test element modify test element element return element jmeterguicomponent createtestelement testelement createtestelement configtestelement configtestelement modifytestelement implements j metergui component modify test element test element public void modify test element test element element configure test element element element set property new string property config test element username username get text string password string new string password get password element set property new string property config test element password password string jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement setproperty stringproperty configtestelement gettext passwordstring getpassword setproperty stringproperty configtestelement passwordstring implements j metergui component clear gui public void clear gui super clear gui username set text non nls 1 password set text non nls 1 jmeterguicomponent cleargui cleargui cleargui settext settext initialize the components and layout of this component private void init set layout new border layout 0 5 if display name set border make border add make title panel border layout north vertical panel main panel new vertical panel main panel add create username panel main panel add create password panel add main panel border layout center setlayout borderlayout displayname setborder makeborder maketitlepanel borderlayout verticalpanel mainpanel verticalpanel mainpanel createusernamepanel mainpanel createpasswordpanel mainpanel borderlayout create a panel containing the username field and corresponding label return a gui panel containing the username field private j panel create username panel j panel panel new j panel new border layout 5 0 j label label new j label j meter utils get res string username non nls 1 label set label for username panel add label border layout west panel add username border layout center return panel jpanel createusernamepanel jpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor borderlayout borderlayout create a panel containing the password field and corresponding label return a gui panel containing the password field private j panel create password panel j panel panel new j panel new border layout 5 0 j label label new j label j meter utils get res string password non nls 1 label set label for password panel add label border layout west panel add password border layout center return panel jpanel createpasswordpanel jpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor borderlayout borderlayout see java awt event focus listener focus gained java awt event focus event public void focus gained focus event e focuslistener focusgained focusevent focusgained focusevent see java awt event focus listener focus lost java awt event focus event public void focus lost focus event e fire property change focuslistener focuslost focusevent focuslost focusevent firepropertychange private void init called from ctor so must not be overridable textui new j text area textui add focus listener this textui set wrap style word true textui set line wrap true scroller new j scroll pane textui j scroll pane vertical scrollbar as needed j scroll pane horizontal scrollbar never jtextarea addfocuslistener setwrapstyleword setlinewrap jscrollpane jscrollpane vertical_scrollbar_as_needed jscrollpane horizontal_scrollbar_never public text area editor super init textareaeditor param source public text area editor object source super source init set value source textareaeditor setvalue see java beans property editor get as text public string get as text return textui get text propertyeditor getastext getastext gettext see java beans property editor get custom editor public component get custom editor return scroller propertyeditor getcustomeditor getcustomeditor see java beans property editor set as text java lang string public void set as text string text throws illegal argument exception textui set text text propertyeditor setastext setastext illegalargumentexception settext public void set value object value if value null textui set text value to string else textui set text setvalue settext tostring settext see java beans property editor get value public object get value return textui get text propertyeditor getvalue getvalue gettext see java beans property editor supports custom editor public boolean supports custom editor return true propertyeditor supportscustomeditor supportscustomeditor private object values public log function logfunction public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception string string to log compound variable values 0 execute string priority string if values length 1 we have a default priority string compound variable values 1 execute if priority string length 0 priority string default priority else priority string default priority throwable t null if values length 2 throwable wanted string value compound variable values 2 execute if value length 0 t new throwable value string comment if values length 3 comment wanted comment compound variable values 3 execute log details log string to log priority string t comment return string to log sampleresult previousresult currentsampler invalidvariableexception stringtolog compoundvariable prioritystring prioritystring compoundvariable prioritystring prioritystring default_priority prioritystring default_priority compoundvariable compoundvariable logdetails stringtolog prioritystring stringtolog common output function private static void print details java io print stream ps string s throwable t string c string tn thread current thread get name string buffer sb new string buffer 80 sb append log sb append tn if c length 0 sb append sb append c else sb append default separator sb append s if t null sb append ps print sb to string t print stack trace ps else ps println sb to string printdetails printstream currentthread getname stringbuffer stringbuffer default_separator tostring printstacktrace tostring routine to perform the output also used by logn function static void log details logger l string s string prio throwable t string c if prio equals ignore case out non nls 1 print details system out s t c else if prio equals ignore case err non nls 1 print details system err s t c else n b if the string is not recognised debug is assumed priority p priority get priority for name prio if log is priority enabled p thread method is potentially expensive string tn thread current thread get name string buffer sb new string buffer 40 sb append tn if c length 0 sb append sb append c else sb append default separator sb append s log log p sb to string t __logn logdetails equalsignorecase printdetails equalsignorecase printdetails getpriorityforname ispriorityenabled currentthread getname stringbuffer stringbuffer default_separator tostring public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters min parameter count max parameter count values parameters to array setparameters invalidvariableexception checkparametercount min_parameter_count max_parameter_count toarray public string get reference key return key getreferencekey public list get argument desc return desc getargumentdesc public class random order controller extends generic controller implements serializable create a new random order controller public random order controller randomordercontroller genericcontroller randomordercontroller randomordercontroller see generic controller initialize public void initialize super initialize this reorder genericcontroller see generic controller re initialize protected void re initialize super re initialize this reorder genericcontroller reinitialize reinitialize reinitialize replace the sub controllers and samplers list with a reordered array list private void reorder int num elements this sub controllers and samplers size create a new list containing num elements null elements list reordered new array list this sub controllers and samplers size for int i 0 i num elements i reordered add null insert the sub controllers and samplers into random list positions for iterator i this sub controllers and samplers iterator i has next int idx int math floor math random reordered size while true if idx num elements idx 0 if reordered get idx null reordered set idx i next break idx replace sub controllers and samplers with reordered copy this sub controllers and samplers reordered subcontrollersandsamplers arraylist numelements subcontrollersandsamplers numelements arraylist subcontrollersandsamplers numelements subcontrollersandsamplers subcontrollersandsamplers hasnext numelements subcontrollersandsamplers subcontrollersandsamplers public static void main string args throws exception if args length minargs system out println please provide minargs or more arguments system out println serverhost serverport filename arg1 arg2 system out println e g system out println localhost 9000 extras remote bsh apple blake 7 system exit 1 string host args 0 string port string args 1 string file args 2 int port integer parse int port string 1 convert to telnet port system out println connecting to bsh server on host port string socket sock new socket host port input stream is sock get input stream output stream os sock get output stream input stream reader fis new file reader file new sock read is start send line bsh prompt os prompt is unnecessary send line string args os for int i minargs i args length i send line args i n os send line os int b while b fis read 1 os write b send line bsh prompt bsh os reset for other users os flush sock shutdown output tell server that we are done portstring parseint portstring portstring inputstream getinputstream outputstream getoutputstream inputstreamreader filereader sockread sendline sendline sendline sendline sendline shutdownoutput private static void send line string line output stream out pipe throws io exception out pipe write line get bytes out pipe flush sendline outputstream outpipe ioexception outpipe getbytes outpipe private final input stream is public sock read input stream is this is is this set daemon true inputstream sockread inputstream _is _is setdaemon public void run system out println reading responses from server int x 0 try while x is read 1 char c char x system out print c catch io exception e finally system out println disconnected from server try is close catch io exception e ioexception ioexception public jvm impl super jvmimpl public memory get memory return this memory getmemory see org apache jmeter monitor model jvm set memory org apache jmeter monitor model memory public void set memory memory mem this memory mem setmemory setmemory private boolean regex match should we match using regexes public replace functions with strings compound variable master function map variables this master function variables false regexmatch replacefunctionswithstrings compoundvariable masterfunction masterfunction public replace functions with strings compound variable master function map variables boolean regex match super set master function master function set variables variables this regex match regex match replacefunctionswithstrings compoundvariable masterfunction regexmatch setmasterfunction masterfunction setvariables regexmatch regexmatch public j meter property transform value j meter property prop throws invalid variable exception pattern matcher pm j meter utils get matcher pattern pattern null pattern compiler compiler new perl5 compiler iterator iter get variables key set iterator string input prop get string value while iter has next string key string iter next string value string get variables get key if regex match try pattern compiler compile value input util substitute pm pattern new string substitution function ref prefix key function ref suffix input util substitute all catch malformed pattern exception e log warn malformed pattern value else input string utilities substitute input value function ref prefix key function ref suffix string property new prop new string property prop get name input return new prop jmeterproperty transformvalue jmeterproperty invalidvariableexception patternmatcher jmeterutils getmatcher patterncompiler perl5compiler getvariables keyset getstringvalue hasnext getvariables regexmatch stringsubstitution function_ref_prefix function_ref_suffix substitute_all malformedpatternexception stringutilities function_ref_prefix function_ref_suffix stringproperty newprop stringproperty getname newprop public html pane this add hyperlink listener new hyperlink listener public void hyperlink update hyperlink event e if e get event type hyperlink event event type activated string ref e geturl get ref if ref null ref length 0 log debug reference to scroll to ref scroll to reference ref htmlpane addhyperlinklistener hyperlinklistener hyperlinkupdate hyperlinkevent geteventtype hyperlinkevent eventtype getref scrolltoreference this add hyperlink listener new hyperlink listener public void hyperlink update hyperlink event e if e get event type hyperlink event event type activated string ref e geturl get ref if ref null ref length 0 log debug reference to scroll to ref scroll to reference ref addhyperlinklistener hyperlinklistener hyperlinkupdate hyperlinkevent geteventtype hyperlinkevent eventtype getref scrolltoreference public void scroll to reference string reference super scroll to reference reference scrolltoreference scrolltoreference jmx file attributes public bsf sampler super bsfsampler public string get filename return get property as string filename getfilename getpropertyasstring public void set filename string new filename this set property filename new filename setfilename newfilename setproperty newfilename public string get script return this get property as string script getscript getpropertyasstring public void set script string new script this set property script new script setscript newscript setproperty newscript public string get parameters return this get property as string parameters getparameters getpropertyasstring public void set parameters string new script this set property parameters new script setparameters newscript setproperty newscript public string get script language return this get property as string language getscriptlanguage getpropertyasstring public void set script language string lang this set property language lang setscriptlanguage setproperty returns a formatted string label describing this sampler return a formatted string label describing this sampler public string get label return get name getlabel getname public sample result sample entry e entry tends to be ignored final string label get label final string request get script final string file name get filename log debug label file name sample result res new sample result res set sample label label file input stream is null bsf engine bsf engine null there s little point saving the manager between invocations as we need to reset most of the beans anyway bsf manager mgr new bsf manager todo find out how to retrieve these from the script at present the script has to use sample result methods to set them res set response code 200 non nls 1 res set response message ok non nls 1 res set successful true res set data type sample result text default can be overridden by the script res sample start try init manager mgr mgr declare bean sample result res res get class non nls 1 these are not useful yet as have not found how to get updated values back mgr declare bean response code 200 string class non nls 1 mgr declare bean response message ok string class non nls 1 mgr declare bean is success boolean true boolean class non nls 1 n b some engines e g javascript cannot handle certain declare bean calls after the engine has been initialised so create the engine last bsf engine mgr load scripting engine get script language object bsf out null if file name length 0 res set sampler data file file name is new file input stream file name bsf out bsf engine eval file name 0 0 io utils to string is else res set sampler data request bsf out bsf engine eval script 0 0 request if bsf out null res set response data bsf out to string get bytes catch bsf exception ex log warn bsf error ex res set successful false res set response code 500 non nls 1 res set response message ex to string catch exception ex catch evaluation errors log warn problem evaluating the script ex res set successful false res set response code 500 non nls 1 res set response message ex to string finally res sample end io utils close quietly is will be done by mgr terminate anyway if bsf engine null bsf engine terminate mgr terminate return res sampleresult getlabel getscript filename getfilename filename sampleresult sampleresult setsamplelabel fileinputstream bsfengine bsfengine bsfmanager bsfmanager sampleresult setresponsecode setresponsemessage setsuccessful setdatatype sampleresult samplestart initmanager declarebean sampleresult getclass declarebean responsecode declarebean responsemessage declarebean issuccess declarebean bsfengine loadscriptingengine getscriptlanguage bsfout filename setsamplerdata filename fileinputstream filename bsfout bsfengine filename ioutils tostring setsamplerdata bsfout bsfengine bsfout setresponsedata bsfout tostring getbytes bsfexception setsuccessful setresponsecode setresponsemessage tostring setsuccessful setresponsecode setresponsemessage tostring sampleend ioutils closequietly bsfengine bsfengine public void test construct throws exception tc log parser tcp tcp new tc log parser assert null should not have set the filename tcp filename string file testfiles access log tcp new tc log parser file assert equals filename should have been saved file tcp filename testconstruct tclogparser tclogparser assertnull tclogparser assertequals public void testcleanurl throws exception string res tclp cleanurl url1 assert equals addrbook res assert null tclp strip file res new http null sampler assertequals assertnull stripfile httpnullsampler public void testcheckurl throws exception assert false url is not have a query tclp checkurl url1 assert true url is a query tclp checkurl url2 assertfalse asserttrue create a new java config gui as a standalone component public java config gui this true javaconfiggui javaconfiggui create a new java config gui as either a standalone or an embedded component param display name field tells whether the component name should be displayed with the gui if true this is a standalone component if false this component is embedded in some other component public java config gui boolean display name field this display name display name field init javaconfiggui displaynamefield javaconfiggui displaynamefield displayname displaynamefield public string get label resource return java request defaults non nls 1 getlabelresource java_request_defaults initialize the gui components and layout private void init called from ctor so must not be overridable set layout new border layout 0 5 if display name set border make border add make title panel border layout north j panel classname request panel new j panel new border layout 0 5 classname request panel add create classname panel border layout north classname request panel add create parameter panel border layout center add classname request panel border layout center setlayout borderlayout displayname setborder makeborder maketitlepanel borderlayout jpanel classnamerequestpanel jpanel borderlayout classnamerequestpanel createclassnamepanel borderlayout classnamerequestpanel createparameterpanel borderlayout classnamerequestpanel borderlayout create a panel with gui components allowing the user to select a test class return a panel containing the relevant components private j panel create classname panel list possible classes new array list try find all the classes which implement the java sampler client interface possible classes class finder find classes that extend j meter utils get search paths new class java sampler client class remove the java config class from the list since it only implements the interface for error conditions possible classes remove java sampler class get name error sampler client catch exception e log debug exception getting interfaces e j label label new j label j meter utils get res string protocol java classname non nls 1 classname combo new j combo box possible classes to array classname combo add action listener this classname combo set name classnamecombo classname combo set editable false label set label for classname combo horizontal panel panel new horizontal panel panel add label panel add classname combo return panel jpanel createclassnamepanel possibleclasses arraylist javasamplerclient possibleclasses classfinder findclassesthatextend jmeterutils getsearchpaths javasamplerclient javaconfig possibleclasses javasampler getname errorsamplerclient jlabel jlabel jmeterutils getresstring protocol_java_classname classnamecombo jcombobox possibleclasses toarray classnamecombo addactionlistener classnamecombo setname classnamecombo seteditable setlabelfor classnamecombo horizontalpanel horizontalpanel classnamecombo handle action events for this component this method currently handles events for the classname combo box param evt the action event to be handled public void action performed action event evt if evt get source classname combo string class name string classname combo get selected item trim try java sampler client client java sampler client class for name class name true thread current thread get context class loader new instance arguments curr args new arguments args panel modify test element curr args map curr args map curr args get arguments as map arguments new args new arguments arguments test params null try test params client get default parameters catch abstract method error e log warn java sampler client doesn t implement get default parameters default parameters won t be shown please update your client class class name if test params null property iterator i test params get arguments iterator while i has next argument arg argument i next get object value string name arg get name string value arg get value if a user has set parameters in one test and then selects a different test which supports the same parameters those parameters should have the same values that they did in the original test if curr args map contains key name string new val string curr args map get name if new val null new val length 0 value new val new args add argument name value args panel configure new args catch exception e log error error getting argument list for class name e actionevent actionperformed actionevent getsource classnamecombo classname classnamecombo getselecteditem javasamplerclient javasamplerclient forname classname currentthread getcontextclassloader newinstance currargs argspanel modifytestelement currargs currargsmap currargs getargumentsasmap newargs testparams testparams getdefaultparameters abstractmethoderror javasamplerclient getdefaultparameters classname testparams propertyiterator testparams getarguments hasnext getobjectvalue getname getvalue currargsmap containskey newval currargsmap newval newval newval newargs addargument argspanel newargs classname create a panel containing components allowing the user to provide arguments to be passed to the test class instance return a panel containing the relevant components private j panel create parameter panel args panel new arguments panel j meter utils get res string paramtable non nls 1 return args panel jpanel createparameterpanel argspanel argumentspanel jmeterutils getresstring argspanel overrides abstractj meter gui component configure test element public void configure test element config super configure config args panel configure arguments config get property java sampler arguments get object value classname combo set selected item config get property as string java sampler classname abstractjmeterguicomponent testelement testelement argspanel getproperty javasampler getobjectvalue classnamecombo setselecteditem getpropertyasstring javasampler implements j metergui component create test element public test element create test element java config config new java config modify test element config return config jmeterguicomponent createtestelement testelement createtestelement javaconfig javaconfig modifytestelement implements j metergui component modify test element test element public void modify test element test element config configure test element config java config config set arguments arguments args panel create test element java config config set classname string value of classname combo get selected item jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement javaconfig setarguments argspanel createtestelement javaconfig setclassname valueof classnamecombo getselecteditem private static final string init file beanshell timer init non nls 1 protected string get init file property return init file init_file getinitfileproperty init_file public long delay string ret 0 final bean shell interpreter bsh interpreter get bean shell interpreter if bsh interpreter null log error bean shell not found return 0 j meter context jmctx j meter context service get context j meter variables vars jmctx get variables try add variables for access to context and variables bsh interpreter set ctx jmctx non nls 1 bsh interpreter set vars vars non nls 1 object o process file or script bsh interpreter if o null ret o to string catch j meter exception e log warn problem in bean shell script e try return long decode ret long value catch number format exception e log warn e get localized message return 0 beanshellinterpreter bshinterpreter getbeanshellinterpreter bshinterpreter beanshell jmetercontext jmetercontextservice getcontext jmetervariables getvariables bshinterpreter bshinterpreter processfileorscript bshinterpreter tostring jmeterexception beanshell longvalue numberformatexception getlocalizedmessage the constructor public html assertion gui init htmlassertiongui returns the label to be shown within the j tree component public string get label resource return html assertion title non nls 1 jtree getlabelresource html_assertion_title see org apache jmeter gui j metergui component create test element public test element create test element html assertion el new html assertion modify test element el return el jmeterguicomponent createtestelement testelement createtestelement htmlassertion htmlassertion modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element in element log debug html assertion gui modify test element called configure test element in element string error threshold string error threshold field get text long error threshold 0 try error threshold long parse long error threshold string catch number format exception e error threshold 0 html assertion in element set error threshold error threshold string warning threshold string warning threshold field get text long warning threshold 0 try warning threshold long parse long warning threshold string catch number format exception e warning threshold 0 html assertion in element set warning threshold warning threshold string doc type string doc type box get selected item to string html assertion in element set doctype doc type string boolean track errors only errors only is selected html assertion in element set errors only track errors only if html radio button is selected html assertion in element sethtml else if xhtml radio button is selected html assertion in element setxhtml else html assertion in element setxml html assertion in element set filename file panel get filename testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement inelement htmlassertiongui modifytestelement configuretestelement inelement errorthresholdstring errorthresholdfield gettext errorthreshold errorthreshold parselong errorthresholdstring numberformatexception errorthreshold htmlassertion inelement seterrorthreshold errorthreshold warningthresholdstring warningthresholdfield gettext warningthreshold warningthreshold parselong warningthresholdstring numberformatexception warningthreshold htmlassertion inelement setwarningthreshold warningthreshold doctypestring doctypebox getselecteditem tostring htmlassertion inelement setdoctype doctypestring trackerrorsonly errorsonly isselected htmlassertion inelement seterrorsonly trackerrorsonly htmlradiobutton isselected htmlassertion inelement xhtmlradiobutton isselected htmlassertion inelement htmlassertion inelement htmlassertion inelement setfilename filepanel getfilename implements j metergui component clear gui public void clear gui super clear gui doc type box set selected index 0 html radio button set selected true xhtml radio button set selected false xml radio button set selected false error threshold field set text 0 non nls 1 warning threshold field set text 0 non nls 1 file panel set filename non nls 1 errors only set selected false jmeterguicomponent cleargui cleargui cleargui doctypebox setselectedindex htmlradiobutton setselected xhtmlradiobutton setselected xmlradiobutton setselected errorthresholdfield settext warningthresholdfield settext filepanel setfilename errorsonly setselected configures the associated test element param in element public void configure test element in element super configure in element html assertion l assertion html assertion in element error threshold field set text string value of l assertion get error threshold warning threshold field set text string value of l assertion get warning threshold errors only set selected l assertion is errors only doc type box set selected item l assertion get doctype if l assertion ishtml html radio button set selected true else if l assertion isxhtml xhtml radio button set selected true else xml radio button set selected true if l assertion is errors only warning threshold field set enabled false warning threshold field set editable false else warning threshold field set enabled true warning threshold field set editable true file panel set filename l assertion get filename inelement testelement inelement inelement htmlassertion lassertion htmlassertion inelement errorthresholdfield settext valueof lassertion geterrorthreshold warningthresholdfield settext valueof lassertion getwarningthreshold errorsonly setselected lassertion iserrorsonly doctypebox setselecteditem lassertion getdoctype lassertion htmlradiobutton setselected lassertion xhtmlradiobutton setselected xmlradiobutton setselected lassertion iserrorsonly warningthresholdfield setenabled warningthresholdfield seteditable warningthresholdfield setenabled warningthresholdfield seteditable filepanel setfilename lassertion getfilename inits the gui private void init set layout new border layout 0 10 set border make border add make title panel border layout north j panel main panel new j panel new border layout user input vertical panel assertion panel new vertical panel assertion panel set border border factory create titled border border factory create etched border tidy settings doctype horizontal panel doc type panel new horizontal panel doc type box new j combo box new object omit auto strict loose doc type panel add new j label j meter utils get res string duration assertion label non nls 1 doc type panel add new j label doctype doc type panel add doc type box assertion panel add doc type panel format hmtl xhtml xml vertical panel format panel new vertical panel format panel set border border factory create titled border border factory create etched border format html radio button new j radio button html true non nls 1 xhtml radio button new j radio button xhtml false non nls 1 xml radio button new j radio button xml false non nls 1 button group button group new button group button group add html radio button button group add xhtml radio button button group add xml radio button format panel add html radio button format panel add xhtml radio button format panel add xml radio button assertion panel add format panel errors only errors only new j check box errors only false errors only add action listener this assertion panel add errors only thresholds horizontal panel threshold panel new horizontal panel threshold panel add new j label error threshold error threshold field new j text field 0 5 non nls 1 error threshold field set name error threshold field error threshold field add key listener this threshold panel add error threshold field threshold panel add new j label warning threshold warning threshold field new j text field 0 5 non nls 1 warning threshold field set name warning threshold field warning threshold field add key listener this threshold panel add warning threshold field assertion panel add threshold panel file panel file panel new file panel j meter utils get res string html assertion file txt non nls 1 non nls 2 assertion panel add file panel main panel add assertion panel border layout north add main panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout jpanel mainpanel jpanel borderlayout user_input verticalpanel assertionpanel verticalpanel assertionpanel setborder borderfactory createtitledborder borderfactory createetchedborder horizontalpanel doctypepanel horizontalpanel doctypebox jcombobox doctypepanel jlabel jmeterutils getresstring duration_assertion_label doctypepanel jlabel doctypepanel doctypebox assertionpanel doctypepanel verticalpanel formatpanel verticalpanel formatpanel setborder borderfactory createtitledborder borderfactory createetchedborder htmlradiobutton jradiobutton xhtmlradiobutton jradiobutton xmlradiobutton jradiobutton buttongroup buttongroup buttongroup buttongroup htmlradiobutton buttongroup xhtmlradiobutton buttongroup xmlradiobutton formatpanel htmlradiobutton formatpanel xhtmlradiobutton formatpanel xmlradiobutton assertionpanel formatpanel errorsonly jcheckbox errorsonly addactionlistener assertionpanel errorsonly horizontalpanel thresholdpanel horizontalpanel thresholdpanel jlabel errorthresholdfield jtextfield errorthresholdfield setname error_threshold_field errorthresholdfield addkeylistener thresholdpanel errorthresholdfield thresholdpanel jlabel warningthresholdfield jtextfield warningthresholdfield setname warning_threshold_field warningthresholdfield addkeylistener thresholdpanel warningthresholdfield assertionpanel thresholdpanel filepanel filepanel jmeterutils getresstring html_assertion_file assertionpanel filepanel mainpanel assertionpanel borderlayout mainpanel borderlayout this method is called if one of the threshold field looses the focus param in event public void focus lost focus event in event log debug html assertion gui focus lost called string error threshold string error threshold field get text if error threshold string null boolean is invalid false try long error threshold long parse long error threshold string if error threshold 0 is invalid true catch number format exception ex is invalid true if is invalid log warn html assertion gui error threshold not a valid number j option pane show message dialog null threshold for errors is invalid error j option pane error message string warning threshold string warning threshold field get text if warning threshold string null boolean is invalid false try long warning threshold long parse long warning threshold string if warning threshold 0 is invalid true catch number format exception ex is invalid true if is invalid log warn html assertion gui error threshold not a valid number j option pane show message dialog null threshold for warnings is invalid error j option pane error message inevent focuslost focusevent inevent htmlassertiongui focuslost errorthresholdstring errorthresholdfield gettext errorthresholdstring isinvalid errorthreshold parselong errorthresholdstring errorthreshold isinvalid numberformatexception isinvalid isinvalid htmlassertiongui joptionpane showmessagedialog joptionpane error_message warningthresholdstring warningthresholdfield gettext warningthresholdstring isinvalid warningthreshold parselong warningthresholdstring warningthreshold isinvalid numberformatexception isinvalid isinvalid htmlassertiongui joptionpane showmessagedialog joptionpane error_message see java awt event focus listener focus gained java awt event focus event public void focus gained focus event e focuslistener focusgained focusevent focusgained focusevent this method is called from erros only checkbox see java awt event action listener action performed java awt event action event public void action performed action event e if errors only is selected warning threshold field set enabled false warning threshold field set editable false else warning threshold field set enabled true warning threshold field set editable true actionlistener actionperformed actionevent actionperformed actionevent errorsonly isselected warningthresholdfield setenabled warningthresholdfield seteditable warningthresholdfield setenabled warningthresholdfield seteditable public void key pressed key event e keypressed keyevent public void key released key event e string field name e get component get name if field name equals warning threshold field validate integer warning threshold field if field name equals error threshold field validate integer error threshold field keyreleased keyevent fieldname getcomponent getname fieldname warning_threshold_field validateinteger warningthresholdfield fieldname error_threshold_field validateinteger errorthresholdfield private void validate integer j text field field try integer parse int field get text catch number format exception nfe int length field get text length if length 0 j option pane show message dialog this only digits allowed invalid data j option pane warning message drop the last character field set text field get text substring 0 length 1 validateinteger jtextfield parseint gettext numberformatexception gettext joptionpane showmessagedialog joptionpane warning_message settext gettext public void key typed key event e keytyped keyevent public class work bench gui extends abstractj meter gui component create a new workbench gui public work bench gui super init workbenchgui abstractjmeterguicomponent workbenchgui workbenchgui this is the list of menu categories this gui component will be available under this implementation returns null since the work bench appears at the top level of the tree and cannot be added elsewhere return a collection of strings where each element is one of the constants defined in menu factory public collection get menu categories return null workbench menufactory getmenucategories implements j metergui component create test element public test element create test element work bench wb new work bench modify test element wb return wb jmeterguicomponent createtestelement testelement createtestelement workbench workbench modifytestelement implements j metergui component modify test element test element public void modify test element test element wb super configure test element wb jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement when a user right clicks on the component in the test tree or selects the edit menu when the component is selected the component will be asked to return a j popup menu that provides all the options available to the user from this component p the work bench returns a popup menu allowing you to add anything return a j popup menu appropriate for the component public j popup menu create popup menu j popup menu menu new j popup menu j menu add menu menu factory make menus new string menu factory non test elements menu factory controllers menu factory config elements menu factory timers menu factory pre processors menu factory samplers menu factory post processors menu factory assertions menu factory listeners j meter utils get res string add non nls 1 action names add menu add add menu menu factory add paste reset menu menu menu factory add file menu menu return menu jpopupmenu workbench jpopupmenu jpopupmenu createpopupmenu jpopupmenu jpopupmenu jmenu addmenu menufactory makemenus menufactory non_test_elements menufactory menufactory config_elements menufactory menufactory pre_processors menufactory menufactory post_processors menufactory menufactory jmeterutils getresstring actionnames addmenu menufactory addpasteresetmenu menufactory addfilemenu public string get label resource return workbench title non nls 1 getlabelresource workbench_title initialize the components and layout of this component private void init set layout new border layout set border make border add make title panel border layout north setlayout borderlayout setborder makeborder maketitlepanel borderlayout public line graph super linegraph param layout public line graph layout manager layout super layout linegraph layoutmanager param layout param is double buffered public line graph layout manager layout boolean is double buffered super layout is double buffered isdoublebuffered linegraph layoutmanager isdoublebuffered isdoublebuffered public void set data double data this data data setdata public void set title string title this title title settitle public void setx axis title string title this x axis title title setxaxistitle xaxistitle public void sety axis title string title this y axis title title setyaxistitle yaxistitle public void setx axis labels string labels this x axis labels labels setxaxislabels xaxislabels public void sety axis labels string label this y axis label label setyaxislabels yaxislabel public void set width int w this width w setwidth public void set height int h this height h setheight public void paint component graphics g reset the paint counter this paint counter 1 if data null this title null this x axis labels null this x axis title null this y axis label null this y axis title null draw sample this title this x axis labels this x axis title this y axis title this data this width this height g paintcomponent paint_counter xaxislabels xaxistitle yaxislabel yaxistitle drawsample xaxislabels xaxistitle yaxistitle private void draw sample string title string xaxislabels string xaxistitle string yaxistitle double data int width int height graphics g try if width 0 width 450 if height 0 height 250 this set preferred size new dimension width height data series data series new data series xaxislabels xaxistitle yaxistitle title string legend labels y axis label paint paints this create paint data length shape shapes create shapes data length stroke lstrokes create strokes data length line chart properties line chart properties new line chart properties lstrokes shapes axis chart data set axis chart data set new axis chart data set data legend labels paints chart type line line chart properties data series addi axis plot data set axis chart data set chart properties chart properties new chart properties axis properties axis properties new axis properties show the grid lines to turn it off set it to zero axis properties gety axis properties set show grid lines 1 axis properties setx axis labels are vertical true set the y axis to round data axis properties daxp data axis properties axis properties gety axis properties daxp set round to nearest 1 legend properties legend properties new legend properties axis chart axis chart new axis chart data series chart properties axis properties legend properties width height axis chart set graphics2d graphics2d g axis chart render catch exception e log error e get message drawsample _title _xaxislabels _xaxistitle _yaxistitle _data _width _height _width _width _height _height setpreferredsize _width _height dataseries dataseries dataseries _xaxislabels _xaxistitle _yaxistitle _title legendlabels yaxislabel createpaint _data createshapes _data createstrokes _data linechartproperties linechartproperties linechartproperties axischartdataset axischartdataset axischartdataset _data legendlabels charttype linechartproperties dataseries addiaxisplotdataset axischartdataset chartproperties chartproperties chartproperties axisproperties axisproperties axisproperties axisproperties getyaxisproperties setshowgridlines axisproperties setxaxislabelsarevertical dataaxisproperties dataaxisproperties axisproperties getyaxisproperties setroundtonearest legendproperties legendproperties legendproperties axischart axischart axischart dataseries chartproperties axisproperties legendproperties _width _height axischart setgraphics2d axischart getmessage since we only have 4 shapes the method will start with the first shape and keep cycling through the shapes in order param count return the first n shapes public shape create shapes int count shape shapes new shape count for int idx 0 idx count idx shapes idx next shape return shapes createshapes nextshape return the next shape return the next shape public shape next shape this shape counter if shape counter shape array length 1 shape counter 0 return shape array shape counter nextshape shape_counter shape_counter shape_array shape_counter shape_array shape_counter param count return the first count strokes public stroke create strokes int count stroke str new stroke count for int idx 0 idx count idx str idx next stroke return str createstrokes nextstroke method always return a new basic stroke with 1 0f weight return a new basic stroke with 1 0f weight public stroke next stroke return new basic stroke 1 0f basicstroke basicstroke nextstroke basicstroke return an array of paint with different colors the current implementation will cycle through 12 colors if a line graph has more than 12 entries param count return an array of paint with different colors public paint create paint int count paint pts new paint count for int idx 0 idx count idx pts idx next paint return pts createpaint nextpaint the method will return the next paint color in the paint array rather than return a random color we want it to always go through the same sequence this way the same charts will always use the same color and make it easier to compare side by side return the next paint color in the paint array public paint next paint this paint counter if this paint counter paint array length 1 this paint counter 0 return paint array this paint counter paint_array paint_array nextpaint paint_counter paint_counter paint_array paint_counter paint_array paint_counter private transient object lock new object private object read resolve lock object must exist lock new object return this readresolve public collection property get names return collection property get property names collectionproperty getnames collectionproperty getproperty public collection property get thread lists return collection property get property thread values collectionproperty getthreadlists collectionproperty getproperty thread_values the list of names of the variables to hold values this list must come in the same order as the sub lists that are given to link set thread lists collection public void set names collection list set property new collection property names list setthreadlists setnames setproperty collectionproperty the list of names of the variables to hold values this list must come in the same order as the sub lists that are given to link set thread lists collection property public void set names collection property list set property list setthreadlists collectionproperty setnames collectionproperty setproperty the thread list is a list of lists each list within the parent list is a collection of values for a simulated user as many different sets of values can be supplied in this fashion to cause j meter to set different values to variables for different test threads public void set thread lists collection thread lists set property new collection property thread values thread lists jmeter setthreadlists threadlists setproperty collectionproperty thread_values threadlists the thread list is a list of lists each list within the parent list is a collection of values for a simulated user as many different sets of values can be supplied in this fashion to cause j meter to set different values to variables for different test threads public void set thread lists collection property thread lists set property thread lists jmeter setthreadlists collectionproperty threadlists setproperty threadlists private collection property get values collection property thread values collection property get property thread values if thread values size 0 return collection property thread values get get thread context get thread num thread values size return new collection property noname new linked list collectionproperty getvalues collectionproperty threadvalues collectionproperty getproperty thread_values threadvalues collectionproperty threadvalues getthreadcontext getthreadnum threadvalues collectionproperty linkedlist public boolean is per iteration return get property as boolean per iteration isperiteration getpropertyasboolean per_iteration public void set per iteration boolean per iter set property new boolean property per iteration per iter setperiteration periter setproperty booleanproperty per_iteration periter public void process if log is debug enabled log debug thread current thread get name process is per iteration non nls 1 if is per iteration set values isdebugenabled currentthread getname isperiteration isperiteration setvalues private void set values synchronized lock if log is debug enabled log debug thread current thread get name running up named get name non nls 1 property iterator names iter get names iterator property iterator value iter get values iterator j meter variables jmvars get thread context get variables while names iter has next value iter has next string name names iter next get string value string value value iter next get string value if log is debug enabled log debug thread current thread get name saving variable name value non nls 1 jmvars put name value setvalues isdebugenabled currentthread getname getname propertyiterator namesiter getnames propertyiterator valueiter getvalues jmetervariables getthreadcontext getvariables namesiter hasnext valueiter hasnext namesiter getstringvalue valueiter getstringvalue isdebugenabled currentthread getname see loop iteration listener iteration start loop iteration event public void iteration start loop iteration event event if log is debug enabled log debug thread current thread get name iteration start is per iteration non nls 1 if is per iteration set values loopiterationlistener iterationstart loopiterationevent iterationstart loopiterationevent isdebugenabled currentthread getname isperiteration isperiteration setvalues public object clone user parameters up user parameters super clone up lock lock ensure that clones share the same lock object return up userparameters userparameters see abstract test element merge in test element protected void merge in test element element super merge in element abstracttestelement mergein testelement mergein testelement mergein private static final logger log logging manager get logger for class public package test string arg0 super arg0 loggingmanager getloggerforclass packagetest public void test timer1 throws exception constant throughput timer timer new constant throughput timer assert equals 0 timer get calc mode int assume this thread only timer set throughput 60 0 1 per second long delay timer delay initialise assert equals 0 delay thread sleep 500 long diff math abs timer delay 500 assert true delay is approximately 500 diff 50 testtimer1 constantthroughputtimer constantthroughputtimer assertequals getcalcmodeint setthroughput assertequals asserttrue public void test timer2 throws exception constant throughput timer timer new constant throughput timer assert equals 0 timer get calc mode int assume this thread only timer set throughput 60 0 1 per second assert equals 1000 timer calculate current target 0 should delay for 1 second timer set throughput 60000 0 1 per milli second assert equals 1 timer calculate current target 0 should delay for 1 milli second testtimer2 constantthroughputtimer constantthroughputtimer assertequals getcalcmodeint setthroughput assertequals calculatecurrenttarget setthroughput assertequals calculatecurrenttarget public void test timer3 throws exception constant throughput timer timer new constant throughput timer constant throughput timer bean info bi new constant throughput timer bean info resource bundle rb resource bundle bi get bean descriptor get value bean info support resource bundle timer set calc mode rb get string calc mode 2 non nls 1 all threads assert equals 1 timer get calc mode int all threads for int i 1 i 10 i testj meter context service incr number of threads assert equals 10 j meter context service get number of threads timer set throughput 600 0 10 per second assert equals 1000 timer calculate current target 0 should delay for 1 second timer set throughput 600000 0 10 per milli second assert equals 1 timer calculate current target 0 should delay for 1 milli second for int i 1 i 990 i testj meter context service incr number of threads assert equals 1000 j meter context service get number of threads timer set throughput 60000000 0 1000 per milli second assert equals 1 timer calculate current target 0 should delay for 1 milli second testtimer3 constantthroughputtimer constantthroughputtimer constantthroughputtimerbeaninfo constantthroughputtimerbeaninfo resourcebundle resourcebundle getbeandescriptor getvalue beaninfosupport resource_bundle setcalcmode getstring calcmode assertequals getcalcmodeint testjmetercontextservice incrnumberofthreads assertequals jmetercontextservice getnumberofthreads setthroughput assertequals calculatecurrenttarget setthroughput assertequals calculatecurrenttarget testjmetercontextservice incrnumberofthreads assertequals jmetercontextservice getnumberofthreads setthroughput assertequals calculatecurrenttarget public void test timerbsh throws exception if bean shell interpreter is interpreter present final string msg bean shell jar not present test ignored log warn msg return bean shell timer timer new bean shell timer long delay timer set script 60 delay timer delay assert equals 60 delay timer set script 60 delay timer delay assert equals 60 delay timer set script 5 3 4 delay timer delay assert equals 60 delay testtimerbsh beanshellinterpreter isinterpreterpresent beanshell beanshelltimer beanshelltimer setscript assertequals setscript assertequals setscript assertequals private map allj meter component commands public report add to tree allj meter component commands new hash map allj meter component commands put add add alljmetercomponentcommands reportaddtotree alljmetercomponentcommands hashmap alljmetercomponentcommands gets the set of actions this command class responds to return the action names value public set get action names return allj meter component commands key set actionnames getactionnames alljmetercomponentcommands keyset adds the specified class to the current node of the tree public void do action action event e try test element node report gui package get instance create test element j component e get source get name add object to tree node catch exception err log error err doaction actionevent testelement reportguipackage getinstance createtestelement jcomponent getsource getname addobjecttotree protected void add object to tree test element el report gui package gui package report gui package get instance report tree node node new report tree node el gui package get tree model gui package get tree model insert node into node gui package get tree listener get current node gui package get tree listener get current node get child count test element cur node test element gui package get tree listener get current node get user object if cur node null cur node add test element el gui package get main frame get tree set selection path new tree path node get path addobjecttotree testelement reportguipackage guipackage reportguipackage getinstance reporttreenode reporttreenode guipackage gettreemodel guipackage gettreemodel insertnodeinto guipackage gettreelistener getcurrentnode guipackage gettreelistener getcurrentnode getchildcount testelement curnode testelement guipackage gettreelistener getcurrentnode getuserobject curnode curnode addtestelement guipackage getmainframe gettree setselectionpath treepath getpath constructor for the file panel object public report file panel title init filepanel reportfilepanel public report file panel string title this title title init reportfilepanel public report file panel string title string filetype this title this filetype filetype reportfilepanel constructor for the file panel object public report file panel change listener l string title this title title init listeners add l filepanel reportfilepanel changelistener public void add change listener change listener l listeners add l addchangelistener changelistener private void init set border border factory create titled border title add label add box create horizontal strut 5 add filename add box create horizontal strut 5 filename add action listener this add browse browse set action command browse browse add action listener this setborder borderfactory createtitledborder createhorizontalstrut createhorizontalstrut addactionlistener setactioncommand addactionlistener if the gui needs to enable disable the file panel call the method param enable public void enable file boolean enable browse set enabled enable filename set enabled enable filepanel enablefile setenabled setenabled gets the filename attribute of the file panel object return the filename value public string get filename return filename get text filepanel getfilename gettext sets the filename attribute of the file panel object param f the new filename value public void set filename string f filename set text f filepanel setfilename settext private void fire file changed iterator iter listeners iterator while iter has next change listener iter next state changed new change event this firefilechanged hasnext changelistener statechanged changeevent public void action performed action event e if e get action command equals browse j file chooser chooser report file dialoger prompt to open file new string filetype if chooser null chooser get selected file null filename set text chooser get selected file get path fire file changed else fire file changed actionperformed actionevent getactioncommand jfilechooser reportfiledialoger prompttoopenfile getselectedfile settext getselectedfile getpath firefilechanged firefilechanged public static class test extends j meter test case public test string a super a jmetertestcase public void test null throws exception try new file row col container testfiles xyzxyz fail should not find the file catch file not found exception e testnull filerowcolcontainer filenotfoundexception public void testrow num throws exception file row col container f new file row col container testfiles test csv assert not null f assert equals expected 4 lines 4 f get size assert equals 0 f next row assert equals 1 f next row assert equals 2 f next row assert equals 3 f next row assert equals 0 f next row testrownum filerowcolcontainer filerowcolcontainer assertnotnull assertequals getsize assertequals nextrow assertequals nextrow assertequals nextrow assertequals nextrow assertequals nextrow public void test columns throws exception file row col container f new file row col container testfiles test csv assert not null f assert true not empty f get size 0 int my row f next row assert equals 0 my row assert equals a1 f get column my row 0 assert equals d1 f get column my row 3 try f get column my row 4 fail expected out of bounds catch index out of bounds exception e my row f next row assert equals 1 my row assert equals b2 f get column my row 1 assert equals c2 f get column my row 2 testcolumns filerowcolcontainer filerowcolcontainer assertnotnull asserttrue getsize myrow nextrow assertequals myrow assertequals getcolumn myrow assertequals getcolumn myrow getcolumn myrow indexoutofboundsexception myrow nextrow assertequals myrow assertequals getcolumn myrow assertequals getcolumn myrow public void test columns comma throws exception file row col container f new file row col container testfiles test csv assert not null f assert true not empty f get size 0 int my row f next row assert equals 0 my row assert equals a1 f get column my row 0 assert equals d1 f get column my row 3 try f get column my row 4 fail expected out of bounds catch index out of bounds exception e my row f next row assert equals 1 my row assert equals b2 f get column my row 1 assert equals c2 f get column my row 2 testcolumnscomma filerowcolcontainer filerowcolcontainer assertnotnull asserttrue getsize myrow nextrow assertequals myrow assertequals getcolumn myrow assertequals getcolumn myrow getcolumn myrow indexoutofboundsexception myrow nextrow assertequals myrow assertequals getcolumn myrow assertequals getcolumn myrow public void test columns tab throws exception file row col container f new file row col container testfiles test tsv t assert not null f assert true not empty f get size 0 int my row f next row assert equals 0 my row assert equals a1 f get column my row 0 assert equals d1 f get column my row 3 try f get column my row 4 fail expected out of bounds catch index out of bounds exception e my row f next row assert equals 1 my row assert equals b2 f get column my row 1 assert equals c2 f get column my row 2 testcolumnstab filerowcolcontainer filerowcolcontainer assertnotnull asserttrue getsize myrow nextrow assertequals myrow assertequals getcolumn myrow assertequals getcolumn myrow getcolumn myrow indexoutofboundsexception myrow nextrow assertequals myrow assertequals getcolumn myrow assertequals getcolumn myrow public void test empty cols throws exception file row col container f new file row col container testfiles testempty csv assert not null f assert equals expected 4 lines 4 f get size int my row f next row assert equals 0 my row assert equals f get column my row 0 assert equals d1 f get column my row 3 my row f next row assert equals 1 my row assert equals f get column my row 1 assert equals c2 f get column my row 2 my row f next row assert equals 2 my row assert equals b3 f get column my row 1 assert equals f get column my row 2 my row f next row assert equals 3 my row assert equals b4 f get column my row 1 assert equals c4 f get column my row 2 assert equals f get column my row 3 testemptycols filerowcolcontainer filerowcolcontainer assertnotnull assertequals getsize myrow nextrow assertequals myrow assertequals getcolumn myrow assertequals getcolumn myrow myrow nextrow assertequals myrow assertequals getcolumn myrow assertequals getcolumn myrow myrow nextrow assertequals myrow assertequals getcolumn myrow assertequals getcolumn myrow myrow nextrow assertequals myrow assertequals getcolumn myrow assertequals getcolumn myrow assertequals getcolumn myrow public class j meter stop test now exception extends runtime exception public j meter stop test now exception super jmeterstoptestnowexception runtimeexception jmeterstoptestnowexception public j meter stop test now exception string s super s jmeterstoptestnowexception the cache of file packs for faster local access private static final thread local file packs new thread local protected object initial value return new hash map threadlocal filepacks threadlocal initialvalue hashmap private x path wrapper prevent separate instantiation super xpathwrapper private static x path file container open string file string xpath string string tname thread current thread get name log info tname opening file x path file container frcc null try frcc new x path file container file xpath string catch file not found exception e log warn e get localized message catch io exception e log warn e get localized message catch parser configuration exception e log warn e get localized message catch sax exception e log warn e get localized message catch transformer exception e log warn e get localized message return frcc xpathfilecontainer xpathstring currentthread getname xpathfilecontainer xpathfilecontainer xpathstring filenotfoundexception getlocalizedmessage ioexception getlocalizedmessage parserconfigurationexception getlocalizedmessage saxexception getlocalizedmessage transformerexception getlocalizedmessage not thread safe must be called from a synchronized method param file param xpath string return the next row from the file container public static string getx path string string file string xpath string map my map file packs get string key file xpath string x path file container xpfc x path file container my get key if xpfc null we don t have a local copy synchronized file containers xpfc x path file container file containers get key if xpfc null there s no global copy either xpfc open file xpath string if xpfc null file containers put key xpfc save the global copy todo improve the error handling if xpfc null log error x path file container is null return non nls 1 my put key xpfc save our local copy if xpfc size 0 log warn x path file container has no nodes file xpath string return non nls 1 int current row xpfc next row log debug getting match number current row return xpfc getx path string current row xpathstring getxpathstring xpathstring filepacks xpathstring xpathfilecontainer xpathfilecontainer filecontainers xpathfilecontainer filecontainers xpathstring filecontainers xpathfilecontainer xpathfilecontainer xpathstring currentrow nextrow currentrow getxpathstring currentrow public static void clear all log debug clear all map my map file packs get my clear string tname thread current thread get name log info tname clearing container synchronized file containers file containers clear clearall clearall filepacks currentthread getname filecontainers filecontainers constructor for the j meter tree listener object public j meter tree listener j meter tree model model this model model drag icon validate drag icon set visible true jmetertreelistener jmetertreelistener jmetertreemodel dragicon dragicon setvisible public j meter tree listener drag icon validate drag icon set visible true jmetertreelistener dragicon dragicon setvisible public void set model j meter tree model m model m setmodel jmetertreemodel sets the action handler attribute of the j meter tree listener object param ah the new action handler value public void set action handler action listener ah action handler ah actionhandler jmetertreelistener actionhandler setactionhandler actionlistener actionhandler sets the j tree attribute of the j meter tree listener object param tree the new j tree value public void setj tree j tree tree this tree tree jtree jmetertreelistener jtree setjtree jtree sets the end window attribute of the j meter tree listener object param window the new end window value public void set end window container window end window window endwindow jmetertreelistener endwindow setendwindow endwindow gets the j tree attribute of the j meter tree listener object return tree the current j tree value public j tree getj tree return tree jtree jmetertreelistener jtree jtree getjtree gets the current node attribute of the j meter tree listener object return the current node value public j meter tree node get current node if current path null if current path get last path component null return j meter tree node current path get last path component return j meter tree node current path get parent path get last path component return j meter tree node model get root currentnode jmetertreelistener currentnode jmetertreenode getcurrentnode currentpath currentpath getlastpathcomponent jmetertreenode currentpath getlastpathcomponent jmetertreenode currentpath getparentpath getlastpathcomponent jmetertreenode getroot public j meter tree node get selected nodes tree path paths tree get selection paths if paths null return new j meter tree node get current node j meter tree node nodes new j meter tree node paths length for int i 0 i paths length i nodes i j meter tree node paths i get last path component return nodes jmetertreenode getselectednodes treepath getselectionpaths jmetertreenode getcurrentnode jmetertreenode jmetertreenode jmetertreenode getlastpathcomponent public tree path removed selected node current path current path get parent path return current path treepath removedselectednode currentpath currentpath getparentpath currentpath public void value changed tree selection event e log debug value changed updating current path current path e get new lead selection path action handler action performed new action event this 3333 edit non nls 1 valuechanged treeselectionevent currentpath currentpath getnewleadselectionpath actionhandler actionperformed actionevent public void mouse clicked mouse event ev mouseclicked mouseevent public void mouse released mouse event e if dragging is valid drag action dragged nodes get current node dragging false j popup menu drag ndrop new j popup menu j menu item item new j menu item j meter utils get res string insert before non nls 1 item add action listener action handler item set action command action names insert before drag ndrop add item item new j menu item j meter utils get res string insert after non nls 1 item add action listener action handler item set action command action names insert after drag ndrop add item if menu factory can add to get current node dragged nodes item new j menu item j meter utils get res string add as child non nls 1 item add action listener action handler item set action command action names drag add drag ndrop add item drag ndrop add separator item new j menu item j meter utils get res string cancel non nls 1 drag ndrop add item display pop up e drag ndrop else gui package get instance get main frame repaint dragging false mousereleased mouseevent isvaliddragaction draggednodes getcurrentnode jpopupmenu dragndrop jpopupmenu jmenuitem jmenuitem jmeterutils getresstring insert_before addactionlistener actionhandler setactioncommand actionnames insert_before dragndrop jmenuitem jmeterutils getresstring insert_after addactionlistener actionhandler setactioncommand actionnames insert_after dragndrop menufactory canaddto getcurrentnode draggednodes jmenuitem jmeterutils getresstring add_as_child addactionlistener actionhandler setactioncommand actionnames drag_add dragndrop dragndrop addseparator jmenuitem jmeterutils getresstring dragndrop displaypopup dragndrop guipackage getinstance getmainframe public j meter tree node get dragged nodes return dragged nodes jmetertreenode getdraggednodes draggednodes tests if the node is being dragged into one of it s own sub nodes or into itself private boolean is valid drag action j meter tree node source j meter tree node dest boolean is valid true tree node path dest get path for int i 0 i path length i if contains source path i is valid false return is valid isvaliddragaction jmetertreenode jmetertreenode isvalid treenode getpath isvalid isvalid public void mouse entered mouse event e mouseentered mouseevent private void change selection if dragging mouse event e if dragging gui package get instance get main frame draw dragged component drag icon e getx e gety if tree get path for location e getx e gety null current path tree get path for location e getx e gety if contains dragged nodes get current node tree set selection path current path changeselectionifdragging mouseevent guipackage getinstance getmainframe drawdraggedcomponent dragicon getpathforlocation currentpath getpathforlocation draggednodes getcurrentnode setselectionpath currentpath private boolean contains object container object item for int i 0 i container length i if container i item return true return false public void mouse pressed mouse event e get the main frame main frame main frame gui package get instance get main frame close any main menu that is open main frame close menu int sel row tree get row for location e getx e gety if tree get path for location e getx e gety null log debug mouse pressed updating current path current path tree get path for location e getx e gety if sel row 1 update main menu j metergui component get current node get user object create popup menu if is right click e if tree get selection count 2 tree set selection path current path log debug about to display pop up display pop up e mousepressed mouseevent mainframe mainframe guipackage getinstance getmainframe mainframe closemenu selrow getrowforlocation getpathforlocation currentpath currentpath getpathforlocation selrow updatemainmenu jmeterguicomponent getcurrentnode getuserobject createpopupmenu isrightclick getselectioncount setselectionpath currentpath displaypopup public void mouse dragged mouse event e if dragging dragging true dragged nodes get selected nodes if dragged nodes 0 get user object instanceof test plan gui dragged nodes 0 get user object instanceof work bench gui dragging false change selection if dragging e mousedragged mouseevent draggednodes getselectednodes draggednodes getuserobject testplangui draggednodes getuserobject workbenchgui changeselectionifdragging public void mouse moved mouse event e mousemoved mouseevent public void mouse exited mouse event ev mouseexited mouseevent public void key pressed key event e if key strokes matches e key strokes copy action router action router action router get instance action router do action now new action event e get source e getid action names copy if key strokes matches e key strokes paste action router action router action router get instance action router do action now new action event e get source e getid action names paste if key strokes matches e key strokes cut action router action router action router get instance action router do action now new action event e get source e getid action names cut keypressed keyevent keystrokes keystrokes actionrouter actionrouter actionrouter getinstance actionrouter doactionnow actionevent getsource actionnames keystrokes keystrokes actionrouter actionrouter actionrouter getinstance actionrouter doactionnow actionevent getsource actionnames keystrokes keystrokes actionrouter actionrouter actionrouter getinstance actionrouter doactionnow actionevent getsource actionnames public void key released key event e keyreleased keyevent public void key typed key event e keytyped keyevent private boolean is right click mouse event e return e is popup trigger mouse event button2 mask e get modifiers 0 mouse event button3 mask e get modifiers isrightclick mouseevent ispopuptrigger mouseevent button2_mask getmodifiers mouseevent button3_mask getmodifiers private void display pop up mouse event e j popup menu pop get current node create popup menu gui package get instance display pop up e pop displaypopup mouseevent jpopupmenu getcurrentnode createpopupmenu guipackage getinstance displaypopup private void display pop up mouse event e j popup menu popup see bug 46108 this log message is unnecessary and misleading log warn shouldn t be here if popup null popup pack popup show tree e getx e gety popup set visible true popup request focus displaypopup mouseevent jpopupmenu setvisible requestfocus int saved value public integer property string name int value super name this value value savedvalue integerproperty see org apache jmeter testelement property j meter property set running version boolean public void set running version boolean running version saved value value super set running version running version jmeterproperty setrunningversion setrunningversion runningversion savedvalue setrunningversion runningversion see org apache jmeter testelement property j meter property recover running version org apache jmeter testelement test element public void recover running version test element owner value saved value jmeterproperty recoverrunningversion testelement recoverrunningversion testelement savedvalue public integer property string name super name integerproperty public integer property super integerproperty public void set value int value this value value setvalue protected void set number value number n value n int value setnumbervalue intvalue protected void set number value string n throws number format exception value integer parse int n setnumbervalue numberformatexception parseint see j meter property get string value public string get string value return integer to string value jmeterproperty getstringvalue getstringvalue tostring see j meter property get object value public object get object value return new integer value jmeterproperty getobjectvalue getobjectvalue public object clone integer property prop integer property super clone prop value value return prop integerproperty integerproperty see j meter property get boolean value public boolean get boolean value return get int value 0 true false jmeterproperty getbooleanvalue getbooleanvalue getintvalue see j meter property get double value public double get double value return value jmeterproperty getdoublevalue getdoublevalue see j meter property get float value public float get float value return value jmeterproperty getfloatvalue getfloatvalue see j meter property get int value public int get int value return value jmeterproperty getintvalue getintvalue see j meter property get long value public long get long value return value jmeterproperty getlongvalue getlongvalue public file editor create a button to trigger the file chooser j button button new j button browse button add action listener this get a wrapper editor to provide the field or combo we ll delegate most methods to it editor new wrapper editor this new simple file editor new combo string editor true true true null create a panel containing the combo and the button panel new j panel new border layout 5 0 panel add editor get custom editor border layout center panel add button border layout east fileeditor jbutton jbutton addactionlistener wrappereditor wrappereditor simplefileeditor combostringeditor jpanel borderlayout getcustomeditor borderlayout borderlayout public void action performed action event e j file chooser chooser file dialoger prompt to open file if chooser null return set value chooser get selected file get path actionperformed actionevent jfilechooser filedialoger prompttoopenfile setvalue getselectedfile getpath param listener public void add property change listener property change listener listener editor add property change listener listener addpropertychangelistener propertychangelistener addpropertychangelistener return the text public string get as text return editor get as text getastext getastext return custom editor panel public component get custom editor return panel getcustomeditor return the java initialisation string public string get java initialization string return editor get java initialization string getjavainitializationstring getjavainitializationstring return the editor tags public string get tags return editor get tags gettags gettags return the value public object get value return editor get value getvalue getvalue return true if the editor is paintable public boolean is paintable return editor is paintable ispaintable ispaintable param gfx param box public void paint value graphics gfx rectangle box editor paint value gfx box paintvalue paintvalue param listener public void remove property change listener property change listener listener editor remove property change listener listener removepropertychangelistener propertychangelistener removepropertychangelistener param text throws java lang illegal argument exception public void set as text string text throws illegal argument exception editor set as text text illegalargumentexception setastext illegalargumentexception setastext param value public void set value object value editor set value value setvalue setvalue return true if supports a custom editor public boolean supports custom editor return editor supports custom editor supportscustomeditor supportscustomeditor see java beans property editor get as text public string get as text return file super get value get path propertyeditor getastext getastext getvalue getpath see java beans property editor set as text java lang string public void set as text string text throws illegal argument exception super set value new file text propertyeditor setastext setastext illegalargumentexception setvalue work on this as a string public object get value return get as text should be super get value getvalue getastext getvalue tsk tsk i need to handle strings when setting too public void set value object file set as text string file setvalue setastext public class bsf listener bean info extends bsf bean info support public bsf listener bean info super bsf listener class bsflistenerbeaninfo bsfbeaninfosupport bsflistenerbeaninfo bsflistener public class test bean bean info implements bean info public bean info get additional bean info return new bean info 0 testbeanbeaninfo beaninfo beaninfo getadditionalbeaninfo beaninfo see java beans bean info get bean descriptor public bean descriptor get bean descriptor return null beaninfo getbeandescriptor beandescriptor getbeandescriptor see java beans bean info get default event index public int get default event index return 0 beaninfo getdefaulteventindex getdefaulteventindex see java beans bean info get default property index public int get default property index return 0 beaninfo getdefaultpropertyindex getdefaultpropertyindex see java beans bean info get event set descriptors public event set descriptor get event set descriptors return new event set descriptor 0 beaninfo geteventsetdescriptors eventsetdescriptor geteventsetdescriptors eventsetdescriptor see java beans bean info get icon int public image get icon int icon kind return null beaninfo geticon geticon iconkind see java beans bean info get method descriptors public method descriptor get method descriptors return new method descriptor 0 beaninfo getmethoddescriptors methoddescriptor getmethoddescriptors methoddescriptor see java beans bean info get property descriptors public property descriptor get property descriptors return new property descriptor 0 beaninfo getpropertydescriptors propertydescriptor getpropertydescriptors propertydescriptor prevent instantiation of utility class private directory dialoger directorydialoger public static j file chooser prompt to open file if lastjfc directory null string start j meter utils get prop default user dir if start equals jfc set current directory new file start jfc set file selection mode j file chooser directories only int ret val jfc show dialog report gui package get instance get main frame j meter utils get res string report select lastjfc directory jfc get current directory get absolute path if ret val j file chooser approve option return jfc else return null jfilechooser prompttoopenfile lastjfcdirectory jmeterutils getpropdefault setcurrentdirectory setfileselectionmode jfilechooser directories_only retval showdialog reportguipackage getinstance getmainframe jmeterutils getresstring report_select lastjfcdirectory getcurrentdirectory getabsolutepath retval jfilechooser approve_option public class shutdown client public static void main string args throws io exception int port 4445 if args length 1 port integer parse int args 1 else if args length 0 throw new runtime exception usage command port string command args 0 system out println sending command request to port port datagram socket socket new datagram socket byte buf command get bytes ascii inet address address inet address get by name localhost datagram packet packet new datagram packet buf buf length address port socket send packet socket close shutdownclient ioexception parseint runtimeexception datagramsocket datagramsocket getbytes inetaddress inetaddress getbyname datagrampacket datagrampacket wraps the input stream to emulate a slow device param in input stream param cps characters per second to emulate public slow input stream input stream in int cps super in pauser new cps pauser cps slowinputstream inputstream cpspauser public int read throws io exception pauser pause 1 return in read ioexception also handles read byte public int read byte b int off int len throws io exception pauser pause len return in read b off len ioexception public void process try bsf manager mgr get manager if mgr null return process file or script mgr mgr terminate catch bsf exception e log warn problem in bsf script e bsfmanager getmanager processfileorscript bsfexception public revert project super revertproject public set get action names return commands getactionnames public void do action action event e get the file name of the current project string project file gui package get instance get test plan file check if the user has loaded any file if project file null return check if the user wants to drop any changes action router get instance do action now new action event e get source e getid action names check dirty gui package gui package gui package get instance if gui package is dirty check if the user wants to revert int response j option pane show confirm dialog gui package get instance get main frame j meter utils get res string cancel revert project non nls 1 j meter utils get res string revert project non nls 1 j option pane yes no option j option pane question message if response j option pane yes option close the current project close close project e reload the project load load project file e new file project file false doaction actionevent projectfile guipackage getinstance gettestplanfile projectfile actionrouter getinstance doactionnow actionevent getsource actionnames check_dirty guipackage guipackage guipackage getinstance guipackage isdirty joptionpane showconfirmdialog guipackage getinstance getmainframe jmeterutils getresstring cancel_revert_project jmeterutils getresstring revert_project joptionpane yes_no_option joptionpane question_message joptionpane yes_option closeproject loadprojectfile projectfile create a new ldap arguments panel using the default title public ldap arguments panel this j meter utils get res string paramtable non nls 1 ldapargumentspanel ldapargumentspanel jmeterutils getresstring create a new ldap arguments panel using the specified title param label the title of the component public ldap arguments panel string label table label new j label label init ldapargumentspanel ldapargumentspanel tablelabel jlabel this is the list of menu categories this gui component will be available under the ldap arguments panel is not intended to be used as a standalone component so this inplementation returns null return a collection of strings where each element is one of the constants defined in menu factory public collection get menu categories return null ldapargumentspanel menufactory getmenucategories public string get label resource return ldapext sample title non nls 1 getlabelresource ldapext_sample_title implements j metergui component create test element public test element create test element ldap arguments args new ldap arguments modify test element args todo why do we clone the return value this is the only reference to it right so we shouldn t need a separate copy return test element args clone jmeterguicomponent createtestelement testelement createtestelement ldaparguments ldaparguments modifytestelement testelement implements j metergui component modify test element test element public void modify test element test element args stop table editing iterator model data table model iterator ldap arguments arguments null if args instanceof ldap arguments arguments ldap arguments args arguments clear while model data has next ldap argument arg ldap argument model data next arg set meta data arguments add argument arg this configure test element args jmeterguicomponent modifytestelement testelement modifytestelement testelement stoptableediting modeldata tablemodel ldaparguments ldaparguments ldaparguments modeldata hasnext ldapargument ldapargument modeldata setmetadata addargument configuretestelement a newly created component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui param el the test element to configure public void configure test element el super configure el if el instanceof ldap arguments table model clear data property iterator iter ldap arguments el iterator while iter has next ldap argument arg ldap argument iter next get object value table model add row arg check delete status testelement testelement ldaparguments tablemodel cleardata propertyiterator ldaparguments hasnext ldapargument ldapargument getobjectvalue tablemodel addrow checkdeletestatus get the table used to enter arguments return the table used to enter arguments protected j table get table return table jtable gettable get the title label for this component return the title label displayed with the table protected j label get table label return table label jlabel gettablelabel tablelabel get the button used to delete rows from the table return the button used to delete rows from the table protected j button get delete button return delete jbutton getdeletebutton get the button used to add rows to the table return the button used to add rows to the table protected j button get add button return add jbutton getaddbutton enable or disable the delete button depending on whether or not there is a row to be deleted protected void check delete status disable delete if there are no rows in the table to delete if table model get row count 0 delete set enabled false else delete set enabled true checkdeletestatus tablemodel getrowcount setenabled setenabled clear all rows from the table t elanjchezhiyan chezhiyan siptech co in public void clear table model clear data tablemodel cleardata invoked when an action occurs this implementation supports the add and delete buttons param e the event that has occurred public void action performed action event e string action e get action command if action equals delete delete argument else if action equals add add argument actionperformed actionevent getactioncommand deleteargument addargument remove the currently selected argument from the table protected void delete argument if a table cell is being edited we must cancel the editing before deleting the row if table is editing table cell editor cell editor table get cell editor table get editing row table get editing column cell editor cancel cell editing int row selected table get selected row if row selected 0 table model remove row row selected table model fire table data changed disable delete if there are no rows in the table to delete if table model get row count 0 delete set enabled false table still contains one or more rows so highlight select the appropriate one else int row to select row selected if row selected table model get row count row to select row selected 1 table set row selection interval row to select row to select deleteargument isediting tablecelleditor celleditor getcelleditor geteditingrow geteditingcolumn celleditor cancelcellediting rowselected getselectedrow rowselected tablemodel removerow rowselected tablemodel firetabledatachanged tablemodel getrowcount setenabled rowtoselect rowselected rowselected tablemodel getrowcount rowtoselect rowselected setrowselectioninterval rowtoselect rowtoselect add a new argument row to the table protected void add argument if a table cell is being edited we should accept the current value and stop the editing before adding a new row stop table editing table model add row make newldap argument enable delete which may already be enabled but it won t hurt delete set enabled true highlight select the appropriate row int row to select table model get row count 1 table set row selection interval row to select row to select addargument stoptableediting tablemodel addrow makenewldapargument setenabled rowtoselect tablemodel getrowcount setrowselectioninterval rowtoselect rowtoselect create a new ldap argument object return a new ldap argument object protected object make newldap argument return new ldap argument ldapargument ldapargument makenewldapargument ldapargument stop any editing that is currently being done on the table this will save any changes that have already been made private void stop table editing if table is editing table cell editor cell editor table get cell editor table get editing row table get editing column cell editor stop cell editing stoptableediting isediting tablecelleditor celleditor getcelleditor geteditingrow geteditingcolumn celleditor stopcellediting initialize the table model used for the arguments table protected void initialize table model table model new object table model new string column names 0 column names 1 column names 2 ldap argument class new functor new functor get name new functor get value new functor get opcode new functor new functor set name new functor set value new functor set opcode new class string class string class string class initializetablemodel tablemodel objecttablemodel column_names column_names column_names ldapargument getname getvalue getopcode setname setvalue setopcode public static boolean test functors ldap arguments panel instance new ldap arguments panel instance initialize table model return instance table model check functors null instance get class testfunctors ldapargumentspanel ldapargumentspanel initializetablemodel tablemodel checkfunctors getclass resize the table columns to appropriate widths param table the table to resize columns for protected void size columns j table table _table sizecolumns jtable _table create the main gui panel which contains the argument table return the main gui panel private component make main panel initialize table model table new j table table model table get table header set default renderer new header as property renderer table set selection mode list selection model single selection return make scroll pane table makemainpanel initializetablemodel jtable tablemodel gettableheader setdefaultrenderer headeraspropertyrenderer setselectionmode listselectionmodel single_selection makescrollpane create a panel containing the title label for the table return a panel containing the title label protected component make label panel j panel label panel new j panel new flow layout flow layout center label panel add table label return label panel makelabelpanel jpanel labelpanel jpanel flowlayout flowlayout labelpanel tablelabel labelpanel create a panel containing the add and delete buttons return a gui panel containing the buttons private j panel make button panel add new j button j meter utils get res string add non nls 1 add set action command add add set enabled true delete new j button j meter utils get res string delete non nls 1 delete set action command delete check delete status j panel button panel new j panel button panel set border border factory create empty border 0 10 0 10 add add action listener this delete add action listener this button panel add add button panel add delete return button panel jpanel makebuttonpanel jbutton jmeterutils getresstring setactioncommand setenabled jbutton jmeterutils getresstring setactioncommand checkdeletestatus jpanel buttonpanel jpanel buttonpanel setborder borderfactory createemptyborder addactionlistener addactionlistener buttonpanel buttonpanel buttonpanel initialize the components and layout of this component private void init set layout new border layout add make label panel border layout north add make main panel border layout center force a minimum table height of 70 pixels add box create vertical strut 70 border layout west add make button panel border layout south table revalidate size columns table setlayout borderlayout makelabelpanel borderlayout makemainpanel borderlayout createverticalstrut borderlayout makebuttonpanel borderlayout sizecolumns create a date field with the specified date public j date field date date super 20 this add key listener new key focus this add focus listener new focus class string my string date format format date set text my string datefield jdatefield addkeylistener keyfocus addfocuslistener focusclass mystring dateformat settext mystring dummy constructor to allo j unit tests to work public j date field this new date junit jdatefield set the date to the date mask control public void set date date date set text date format format date setdate settext dateformat get the date from the date mask control public date get date try return date format parse get text catch parse exception e return new date catch exception e date format parse has some bugs up to jdk 1 4 2 by which it throws unchecked exceptions e g see http developer java sun com developer bug parade bugs 4699765 html to avoid problems with such situations we ll catch all exceptions here and act just as for parse exception above return new date getdate dateformat gettext parseexception dateformat bugparade parseexception private static int pos to field int pos if pos field positions length if beyond the end pos field positions length 1 then set to the end return field positions pos postofield fieldpositions fieldpositions fieldpositions converts a date time to a calendar using the defined format private calendar parse date string datetime calendar c calendar get instance try date dat date format parse datetime c set time dat catch parse exception e do nothing the current time will be returned return c parsedate getinstance dateformat settime parseexception private void update int addend boolean shifted calendar c parse date get text int pos get caret position int field pos to field pos if shifted c roll field true else c add field addend string new date date format format c get time set text new date if pos new date length pos new date length set caret position pos restore position parsedate gettext getcaretposition postofield newdate dateformat gettime settext newdate newdate newdate setcaretposition class key focus extends key adapter key focus keyfocus keyadapter keyfocus public void key pressed key event e if e get key code key event vk up update 1 e is shift down else if e get key code key event vk down update 1 e is shift down keypressed keyevent getkeycode keyevent vk_up isshiftdown getkeycode keyevent vk_down isshiftdown class focus class implements focus listener focus class focusclass focuslistener focusclass public void focus gained focus event e focusgained focusevent public void focus lost focus event e try date format parse get text catch parse exception e1 request focus focuslost focusevent dateformat gettext parseexception requestfocus private map data new properties public nullurl connection throws malformedurl exception this new url http localhost nullurlconnection malformedurlexception public nullurl connection url url super url nullurlconnection public void connect public void set request property string name string value data put name value setrequestproperty public string get request property string name return string data get name getrequestproperty note windows user preferences are stored relative to hkey current user software java soft prefs public load recent project super hkey_current_user javasoft loadrecentproject public set get action names return commands getactionnames public void do action action event e we must ask the user if it is ok to close current project if close perform action e return load the file for this recent file command load project file e get recent file e false doaction actionevent performaction loadprojectfile getrecentfile get the recent file for the menu item private file get recent file action event e j menu item menu item j menu item e get source get the preference for the recent files return new file get recent file integer parse int menu item get name getrecentfile actionevent jmenuitem menuitem jmenuitem getsource getrecentfile parseint menuitem getname get the menu items to add to the menu bar to get recent file functionality return a list of j menu item and a j separator representing recent files public static list get recent file menu items linked list menu items new linked list get the preference for the recent files for int i 0 i number of menu items i create the menu item j menu item recent file new j menu item use the index as the name used when processing the action recent file set name integer to string i recent file add action listener action router get instance recent file set action command action names open recent set the key stroke to use int short key get shortcut key i if short key 0 recent file set mnemonic short key add the menu item menu items add recent file add separator as the last item j separator separator new j separator separator set visible false menu items add separator update menu items to reflect recent files update menu items menu items return menu items jmenuitem jseparator getrecentfilemenuitems linkedlist menuitems linkedlist number_of_menu_items jmenuitem recentfile jmenuitem recentfile setname tostring recentfile addactionlistener actionrouter getinstance recentfile setactioncommand actionnames open_recent keystroke shortkey getshortcutkey shortkey recentfile setmnemonic shortkey menuitems recentfile jseparator jseparator setvisible menuitems updatemenuitems menuitems menuitems update the content and visibility of the menu items for recent files param menu items the j menu item and j separator to update param loaded file name the file name of the project file that has just been loaded public static void update recent file menu items list menu items string loaded file name get the preference for the recent files linked list new recent files new linked list check if the new file is already in the recent list boolean already exists false for int i 0 i number of menu items i string recent file path get recent file i if loaded file name equals recent file path new recent files add recent file path else already exists true add the new file at the start of the list new recent files add 0 loaded file name remove the last item from the list if it was a brand new file if already exists new recent files remove last store the recent files for int i 0 i number of menu items i string file name string new recent files get i if file name null set recent file i file name update menu items to reflect recent files update menu items menu items menuitems jmenuitem jseparator loadedfilename updaterecentfilemenuitems menuitems loadedfilename linkedlist newrecentfiles linkedlist alreadyexists number_of_menu_items recentfilepath getrecentfile loadedfilename recentfilepath newrecentfiles recentfilepath alreadyexists newrecentfiles loadedfilename alreadyexists newrecentfiles removelast number_of_menu_items filename newrecentfiles filename setrecentfile filename updatemenuitems menuitems set the content and visibility of menu items and menu separator based on the recent file stored user preferences private static void update menu items list menu items assume no recent files boolean some recent files false update the menu items for int i 0 i number of menu items i get the menu item j menu item recent file j menu item menu items get i find and set the file for this recent file command string recent file path get recent file i if recent file path null file file new file recent file path string buffer sb new string buffer 60 if i 9 sb append i 1 append non nls 1 sb append get menu item display name file recent file set text sb to string recent file set tool tip text recent file path recent file set enabled true recent file set visible true at least one recent file menu item is visible some recent files true else recent file set enabled false recent file set visible false if there are some recent files we must make the separator visisble the separator is the last item in the list j separator separator j separator menu items get menu items size 1 separator set visible some recent files updatemenuitems menuitems somerecentfiles number_of_menu_items jmenuitem recentfile jmenuitem menuitems recentfilepath getrecentfile recentfilepath recentfilepath stringbuffer stringbuffer getmenuitemdisplayname recentfile settext tostring recentfile settooltiptext recentfilepath recentfile setenabled recentfile setvisible somerecentfiles recentfile setenabled recentfile setvisible jseparator jseparator menuitems menuitems setvisible somerecentfiles get the name to display in the menu item it will chop the file name if it is too long to display in the menu bar private static string get menu item display name file file limit the length of the menu text if needed final int max length 40 string menu text file get name if menu text length max length menu text menu text substring menu text length max length menu text length non nls 1 return menu text getmenuitemdisplayname maxlength menutext getname menutext maxlength menutext menutext menutext maxlength menutext menutext get the key event to use as shortcut key for menu item private static int get shortcut key int index int short key 1 switch index 1 case 1 short key key event vk 1 break case 2 short key key event vk 2 break case 3 short key key event vk 3 break case 4 short key key event vk 4 break case 5 short key key event vk 5 break case 6 short key key event vk 6 break case 7 short key key event vk 7 break case 8 short key key event vk 8 break case 9 short key key event vk 9 break default break return short key keyevent getshortcutkey shortkey shortkey keyevent vk_1 shortkey keyevent vk_2 shortkey keyevent vk_3 shortkey keyevent vk_4 shortkey keyevent vk_5 shortkey keyevent vk_6 shortkey keyevent vk_7 shortkey keyevent vk_8 shortkey keyevent vk_9 shortkey get the full path to the recent file where index 0 is the most recent public static string get recent file int index return prefs get user prefs key index null getrecentfile user_prefs_key set the full path to the recent file where index 0 is the most recent private static void set recent file int index string file name prefs put user prefs key index file name setrecentfile filename user_prefs_key filename private constructor to prevent instantiation private html parsing utils htmlparsingutils check if anchor matches by checking against protocol domain path parameter names param new link target to match param config pattern to match against return true if target url matches pattern url public static boolean is anchor matched http sampler base new link http sampler base config string query null try query url decoder decode new link get query string utf 8 non nls 1 catch unsupported encoding exception e utf 8 unsupported you must be joking log error utf 8 encoding not supported throw new error should not happen e to string final arguments arguments config get arguments if query null arguments get argument count 0 return false failed to convert query so assume no match final perl5 matcher matcher j meter utils get matcher final pattern cachelru pattern cache j meter utils get pattern cache if is equal or matches new link get protocol config get protocol matcher pattern cache return false final string domain config get domain if domain null domain length 0 if is equal or matches new link get domain domain matcher pattern cache return false final string path config get path if new link get path equals path matcher matches new link get path pattern cache get pattern path non nls 1 perl5 compiler read only mask return false property iterator iter arguments iterator while iter has next argument item argument iter next get object value final string name item get name if query index of name 1 non nls 1 if matcher contains query pattern cache get pattern name perl5 compiler read only mask return false return true newlink isanchormatched httpsamplerbase newlink httpsamplerbase urldecoder newlink getquerystring unsupportedencodingexception tostring getarguments getargumentcount perl5matcher jmeterutils getmatcher patterncachelru patterncache jmeterutils getpatterncache isequalormatches newlink getprotocol getprotocol patterncache getdomain isequalormatches newlink getdomain patterncache getpath newlink getpath newlink getpath patterncache getpattern perl5compiler read_only_mask propertyiterator hasnext getobjectvalue getname indexof patterncache getpattern perl5compiler read_only_mask arguments match if the input name matches the corresponding pattern name and the input value matches the pattern value where the matching is done first using string equals and then regular expression matching if the equals test fails param arg input argument param pattern arg pattern to match against return true if both name and value match public static boolean is argument matched argument arg argument pattern arg final perl5 matcher matcher j meter utils get matcher final pattern cachelru pattern cache j meter utils get pattern cache return is equal or matches arg get name pattern arg get name matcher pattern cache is equal or matches arg get value pattern arg get value matcher pattern cache patternarg isargumentmatched patternarg perl5matcher jmeterutils getmatcher patterncachelru patterncache jmeterutils getpatterncache isequalormatches getname patternarg getname patterncache isequalormatches getvalue patternarg getvalue patterncache match the input argument against the pattern using string equals or pattern matching if that fails param arg input string param pat pattern string param matcher perl5 matcher param cache pattern cache return true if input matches the pattern public static boolean is equal or matches string arg string pat perl5 matcher matcher pattern cachelru cache return arg equals pat matcher matches arg cache get pattern pat perl5 compiler read only mask perl5matcher patterncache isequalormatches perl5matcher patterncachelru getpattern perl5compiler read_only_mask match the input argument against the pattern using string equals or pattern matching if that fails using case insenssitive matching param arg input string param pat pattern string param matcher perl5 matcher param cache pattern cache return true if input matches the pattern public static boolean is equal or matches case blind string arg string pat perl5 matcher matcher pattern cachelru cache return arg equals ignore case pat matcher matches arg cache get pattern pat perl5 compiler read only mask perl5 compiler case insensitive mask perl5matcher patterncache isequalormatchescaseblind perl5matcher patterncachelru equalsignorecase getpattern perl5compiler read_only_mask perl5compiler case_insensitive_mask match the input argument against the pattern using string equals or pattern matching if that fails using case insensitive matching param arg input string param pat pattern string return true if input matches the pattern public static boolean is equal or matches string arg string pat return is equal or matches arg pat j meter utils get matcher j meter utils get pattern cache isequalormatches isequalormatches jmeterutils getmatcher jmeterutils getpatterncache match the input argument against the pattern using string equals or pattern matching if that fails using case insensitive matching param arg input string param pat pattern string return true if input matches the pattern public static boolean is equal or matches case blind string arg string pat return is equal or matches case blind arg pat j meter utils get matcher j meter utils get pattern cache isequalormatchescaseblind isequalormatchescaseblind jmeterutils getmatcher jmeterutils getpatterncache returns code tidy code as html parser return a code tidy code html parser public static tidy get parser log debug start get parser1 tidy tidy new tidy tidy set char encoding org w3c tidy configuration utf8 tidy set quiet true tidy set show warnings false if log is debug enabled log debug get parser1 tidy parser created tidy log debug end get parser1 return tidy getparser getparser1 setcharencoding setquiet setshowwarnings isdebugenabled getparser1 getparser1 returns a node representing a whole xml given an xml document param text an xml document return a node representing a whole xml public static node getdom string text log debug start getdom1 try node node get parser parsedom new byte array input stream text get bytes utf 8 null non nls 1 if log is debug enabled log debug node node log debug end getdom1 return node catch unsupported encoding exception e log error getdom1 unsupported encoding exception e log debug end getdom1 throw new runtime exception utf 8 encoding failed getparser bytearrayinputstream getbytes isdebugenabled unsupportedencodingexception runtimeexception public static document create empty doc return tidy create empty document createemptydoc createemptydocument create a new sampler based on an href string plus a contextual url object given that an href string might be of three possible forms some processing is required public static http sampler base create url from anchor string parsed url string url context throws malformedurl exception if log is debug enabled log debug creating url from anchor parsed url string base context url url conversion utils make relativeurl context parsed url string http sampler base sampler http sampler factory new instance sampler set domain url get host sampler set protocol url get protocol sampler set port url get port sampler set path url get path sampler parse arguments url get query return sampler httpsamplerbase createurlfromanchor parsedurlstring malformedurlexception isdebugenabled parsedurlstring conversionutils makerelativeurl parsedurlstring httpsamplerbase httpsamplerfactory newinstance setdomain gethost setprotocol getprotocol setport getport setpath getpath parsearguments getquery public static list createurl from form node doc url context string select name null linked list url configs new linked list recurse form doc url configs context select name false named node map atts form node get attributes if atts get named item action null throw new malformedurl exception string action atts get named item action get node value url config url create url from anchor action context recurse form doc url select name true form start return url configs createurlfromform selectname linkedlist urlconfigs linkedlist recurseform urlconfigs selectname namednodemap formnode getattributes getnameditem malformedurlexception getnameditem getnodevalue urlconfig createurlfromanchor recurseform selectname formstart urlconfigs n b since the tags are extracted from an html form any values must already have been encoded private static boolean recurse form node temp node linked list url configs url context string select name boolean in form named node map node atts temp node get attributes string tag temp node get node name try if in form http sampler base url http sampler base url configs get last if tag equals ignore case form non nls 1 try url configs add create form url config temp node context catch malformedurl exception e in form false else if tag equals ignore case input non nls 1 url add encoded argument get attribute value node atts name non nls 1 get attribute value node atts value non nls 1 else if tag equals ignore case textarea non nls 1 try url add encoded argument get attribute value node atts name non nls 1 temp node get first child get node value catch null pointer exception e url add argument get attribute value node atts name non nls 1 else if tag equals ignore case select non nls 1 select name get attribute value node atts name non nls 1 else if tag equals ignore case option non nls 1 string value get attribute value node atts value non nls 1 if value null try value temp node get first child get node value catch null pointer exception e value non nls 1 url add encoded argument select name value else if tag equals ignore case form non nls 1 try url configs add create form url config temp node context in form true catch malformedurl exception e in form false catch exception ex log warn some bad html print node temp node ex node list child nodes temp node get child nodes for int x 0 x child nodes get length x in form recurse form child nodes item x url configs context select name in form return in form recurseform tempnode linkedlist urlconfigs selectname inform namednodemap nodeatts tempnode getattributes tempnode getnodename inform httpsamplerbase httpsamplerbase urlconfigs getlast equalsignorecase urlconfigs createformurlconfig tempnode malformedurlexception inform equalsignorecase addencodedargument getattributevalue nodeatts getattributevalue nodeatts equalsignorecase addencodedargument getattributevalue nodeatts tempnode getfirstchild getnodevalue nullpointerexception addargument getattributevalue nodeatts equalsignorecase selectname getattributevalue nodeatts equalsignorecase getattributevalue nodeatts tempnode getfirstchild getnodevalue nullpointerexception addencodedargument selectname equalsignorecase urlconfigs createformurlconfig tempnode inform malformedurlexception inform printnode tempnode nodelist childnodes tempnode getchildnodes childnodes getlength inform recurseform childnodes urlconfigs selectname inform inform private static string get attribute value named node map att string att name try return att get named item att name get node value catch exception ex return non nls 1 getattributevalue namednodemap attname getnameditem attname getnodevalue private static string print node node node string buffer buf new string buffer buf append non nls 1 buf append node get node name named node map atts node get attributes for int x 0 x atts get length x buf append non nls 1 buf append atts item x get node name buf append non nls 1 buf append atts item x get node value buf append non nls 1 buf append non nls 1 return buf to string printnode stringbuffer stringbuffer getnodename namednodemap getattributes getlength getnodename getnodevalue tostring private static http sampler base create form url config node temp node url context throws malformedurl exception named node map atts temp node get attributes if atts get named item action null non nls 1 throw new malformedurl exception string action atts get named item action get node value non nls 1 http sampler base url create url from anchor action context return url httpsamplerbase createformurlconfig tempnode malformedurlexception namednodemap tempnode getattributes getnameditem malformedurlexception getnameditem getnodevalue httpsamplerbase createurlfromanchor public static void extract styleur ls final url base url final url collection urls string style tag str perl5 matcher matcher j meter utils get matcher pattern pattern j meter utils get pattern cache get pattern url s s non nls 1 perl5 compiler case insensitive mask perl5 compiler singleline mask perl5 compiler read only mask pattern matcher input input null input new pattern matcher input style tag str while matcher contains input pattern match result match matcher get match the value is in the second group string style url match group 2 urls addurl style url base url extractstyleurls baseurl urlcollection styletagstr perl5matcher jmeterutils getmatcher jmeterutils getpatterncache getpattern perl5compiler case_insensitive_mask perl5compiler singleline_mask perl5compiler read_only_mask patternmatcherinput patternmatcherinput styletagstr matchresult getmatch styleurl styleurl baseurl private static final random rand new random public anchor modifier anchormodifier modifies an entry object based on html response text public void process j meter context context get thread context sampler sam context get current sampler sample result res context get previous result http sampler base sampler null http sample result result null if res null sam instanceof http sampler base res instanceof http sample result log info can t apply html link parser when the previous sampler run is not an http request return else sampler http sampler base sam result http sample result res list potential links new array list string response text non nls 1 response text result get response data as string document html int index response text index of non nls 1 if index 1 index 0 if log is debug enabled log debug check for matches against sampler to string html document html parsing utils getdom response text substring index add anchor urls html result sampler potential links add form urls html result sampler potential links add frameset urls html result sampler potential links if potential links size 0 http sampler base url http sampler base potential links get rand next int potential links size if log is debug enabled log debug selected url to string sampler set domain url get domain sampler set path url get path if url get method equals http constants post property iterator iter sampler get arguments iterator while iter has next argument arg argument iter next get object value modify argument arg url get arguments else sampler set arguments url get arguments config parse arguments url get query string sampler set protocol url get protocol return else log debug no matches found return jmetercontext getthreadcontext getcurrentsampler sampleresult getpreviousresult httpsamplerbase httpsampleresult httpsamplerbase httpsampleresult httpsamplerbase httpsampleresult potentiallinks arraylist responsetext responsetext getresponsedataasstring responsetext indexof isdebugenabled tostring htmlparsingutils responsetext addanchorurls potentiallinks addformurls potentiallinks addframeseturls potentiallinks potentiallinks httpsamplerbase httpsamplerbase potentiallinks nextint potentiallinks isdebugenabled tostring setdomain getdomain setpath getpath getmethod httpconstants propertyiterator getarguments hasnext getobjectvalue modifyargument getarguments setarguments getarguments parsearguments getquerystring setprotocol getprotocol private void modify argument argument arg arguments args if log is debug enabled log debug modifying argument arg list possible replacements new array list property iterator iter args iterator argument replacement arg while iter has next replacement arg argument iter next get object value try if html parsing utils is argument matched replacement arg arg possible replacements add replacement arg catch exception ex log error problem adding argument ex if possible replacements size 0 replacement arg argument possible replacements get rand next int possible replacements size arg set name replacement arg get name arg set value replacement arg get value if log is debug enabled log debug just set argument to values arg get name arg get value args remove argument replacement arg modifyargument isdebugenabled possiblereplacements arraylist propertyiterator replacementarg hasnext replacementarg getobjectvalue htmlparsingutils isargumentmatched replacementarg possiblereplacements replacementarg possiblereplacements replacementarg possiblereplacements nextint possiblereplacements setname replacementarg getname setvalue replacementarg getvalue isdebugenabled getname getvalue removeargument replacementarg public void add config element config element config addconfigelement configelement private void add form urls document html http sample result result http sampler base config list potential links node list root list html get child nodes list urls new linked list for int x 0 x root list get length x urls add all html parsing utils createurl from form root list item x result geturl iterator iter urls iterator while iter has next http sampler base new url http sampler base iter next new url set method http constants post if log is debug enabled log debug potential form match new url to string if html parsing utils is anchor matched new url config log debug matched potential links add new url addformurls httpsampleresult httpsamplerbase potentiallinks nodelist rootlist getchildnodes linkedlist rootlist getlength addall htmlparsingutils createurlfromform rootlist hasnext httpsamplerbase newurl httpsamplerbase newurl setmethod httpconstants isdebugenabled newurl tostring htmlparsingutils isanchormatched newurl potentiallinks newurl private void add anchor urls document html http sample result result http sampler base config list potential links string base node list base list html get elements by tag name base non nls 1 if base list get length 0 base base list item 0 get attributes get named item href get node value non nls 1 node list node list html get elements by tag name a non nls 1 for int i 0 i node list get length i node temp node node list item i named node map nnm temp node get attributes node named item nnm get named item href non nls 1 if named item null continue string href str named item get node value if href str starts with javascript non nls 1 continue no point trying these try http sampler base new url html parsing utils create url from anchor href str conversion utils make relativeurl result geturl base new url set method http constants get if log is debug enabled log debug potential a href match new url if html parsing utils is anchor matched new url config log debug matched potential links add new url catch malformedurl exception e log warn bad url e addanchorurls httpsampleresult httpsamplerbase potentiallinks nodelist baselist getelementsbytagname baselist getlength baselist getattributes getnameditem getnodevalue nodelist nodelist getelementsbytagname nodelist getlength tempnode nodelist namednodemap tempnode getattributes nameditem getnameditem nameditem hrefstr nameditem getnodevalue hrefstr startswith httpsamplerbase newurl htmlparsingutils createurlfromanchor hrefstr conversionutils makerelativeurl newurl setmethod httpconstants isdebugenabled newurl htmlparsingutils isanchormatched newurl potentiallinks newurl malformedurlexception private void add frameset urls document html http sample result result http sampler base config list potential links string base node list base list html get elements by tag name base non nls 1 if base list get length 0 base base list item 0 get attributes get named item href non nls 1 get node value node list node list html get elements by tag name frame non nls 1 for int i 0 i node list get length i node temp node node list item i named node map nnm temp node get attributes node named item nnm get named item src non nls 1 if named item null continue string href str named item get node value try http sampler base new url html parsing utils create url from anchor href str conversion utils make relativeurl result geturl base new url set method http constants get if log is debug enabled log debug potential frame src match new url if html parsing utils is anchor matched new url config log debug matched potential links add new url catch malformedurl exception e log warn bad url e addframeseturls httpsampleresult httpsamplerbase potentiallinks nodelist baselist getelementsbytagname baselist getlength baselist getattributes getnameditem getnodevalue nodelist nodelist getelementsbytagname nodelist getlength tempnode nodelist namednodemap tempnode getattributes nameditem getnameditem nameditem hrefstr nameditem getnodevalue httpsamplerbase newurl htmlparsingutils createurlfromanchor hrefstr conversionutils makerelativeurl newurl setmethod httpconstants isdebugenabled newurl htmlparsingutils isanchormatched newurl potentiallinks newurl malformedurlexception public void clear values clear sum 0 sum of squares 0 mean 0 deviation 0 count 0 sumofsquares public void add value long new value number val new long new value add value val addvalue newvalue newvalue addvalue public void add value int new value number val new integer new value add value val addvalue newvalue newvalue addvalue public void add value float new value number val new float new value add value val addvalue newvalue newvalue addvalue public void add value double new value number val new double new value add value val addvalue newvalue newvalue addvalue public void add bytes long new value bytes new value addbytes newvalue newvalue public void add all stat calculator calc iterator iter calc values iterator while iter has next add value number iter next addall statcalculator hasnext addvalue public number get median if count 0 return number values get int values size 5 return new long 0 getmedian public long get total bytes return bytes gettotalbytes get the value which percent of the values are less than this works just like median where median represents the 50 point a typical desire is to see the 90 point the value that 90 of the data points are below the remaining 10 are above param percent return number of values less than the percentage public number get percent point float percent if count 0 return number values get int values size percent return new long 0 getpercentpoint get the value which percent of the values are less than this works just like median where median represents the 50 point a typical desire is to see the 90 point the value that 90 of the data points are below the remaining 10 are above param percent return number of values less than the percentage public number get percent point double percent if count 0 return number values get int values size percent return new long 0 getpercentpoint the method has a limit of 1 as the finest granularity we do this to make sure we get a whole number for iterating public synchronized hash map get distribution hash map items new hash map iterator itr this values iterator number dis while itr has next long nx long itr next if items contains key nx dis number items get nx dis 1 new integer dis 1 int value 1 items put nx dis else dis new number 2 dis 0 nx dis 1 new integer 1 items put nx dis return items hashmap getdistribution hashmap hashmap hasnext containskey intvalue public double get mean return mean getmean public double get standard deviation return deviation getstandarddeviation public number get min if count 0 return number values get 0 return new long long min value getmin min_value public number get max if count 0 return number values get count 1 return new long long max value getmax max_value public int get count return count getcount public void add value number val add sorted value val count double current val val double value sum current val sum of squares current val current val mean sum count deviation math sqrt sum of squares count mean mean addvalue addsortedvalue currentval doublevalue currentval sumofsquares currentval currentval sumofsquares param val private void add sorted value number val int index collections binary search values val if index 0 index values size values add index val else if index values size values size 0 values add val else values add index 1 1 val addsortedvalue binarysearch public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception string str non nls 1 compound variable var compound variable values 0 string exp var execute string var name non nls 1 if values length 1 var name compound variable values 1 execute trim j meter context jmctx j meter context service get context j meter variables vars jmctx get variables try script script script factory create script exp jexl context jc jexl helper create context final map jexl vars jc get vars jexl vars put log log non nls 1 jexl vars put ctx jmctx non nls 1 jexl vars put vars vars non nls 1 jexl vars put props j meter utils getj meter properties non nls 1 previously mis spelt as thead name jexl vars put thread name thread current thread get name non nls 1 jexl vars put sampler current sampler non nls 1 may be null jexl vars put sample result previous result non nls 1 may be null jexl vars put out system out non nls 1 now evaluate the script getting the result object o script execute jc if o null str o to string if vars null var name length 0 vars will be null on test plan vars put var name str catch exception e log error an error occurred while evaluating the expression exp n e return str sampleresult previousresult currentsampler invalidvariableexception compoundvariable compoundvariable varname varname compoundvariable jmetercontext jmetercontextservice getcontext jmetervariables getvariables scriptfactory createscript jexlcontext jexlhelper createcontext jexlvars getvars jexlvars jexlvars jexlvars jexlvars jmeterutils getjmeterproperties theadname jexlvars threadname currentthread getname jexlvars currentsampler jexlvars sampleresult previousresult jexlvars tostring varname testplan varname public list get argument desc return desc getargumentdesc public string get reference key return key getreferencekey public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters 1 2 values parameters to array setparameters invalidvariableexception checkparametercount toarray private transient int loop count 0 public loop controller setcontinueforever private true loopcount loopcontroller setcontinueforever_private public void set loops int loops set property new integer property loops loops setloops setproperty integerproperty public void set loops string loop value set property new string property loops loop value setloops loopvalue setproperty stringproperty loopvalue public int get loops try j meter property prop get property loops return integer parse int prop get string value catch number format exception e return 0 getloops jmeterproperty getproperty parseint getstringvalue numberformatexception public string get loop string return get property as string loops getloopstring getpropertyasstring determines whether the loop will return any samples if it is rerun param forever true if the loop must be reset after ending a run public void set continue forever boolean forever setcontinueforever private forever setcontinueforever setcontinueforever_private private void setcontinueforever private boolean forever set property new boolean property continue forever forever setcontinueforever_private setproperty booleanproperty continue_forever private boolean get continue forever return get property as boolean continue forever getcontinueforever getpropertyasboolean continue_forever public sampler next if end of loop if get continue forever set done true return null return super next endofloop getcontinueforever setdone private boolean end of loop final int loops get loops return loops 1 loop count loops endofloop getloops loopcount protected sampler next is null throws next is null exception re initialize if end of loop if get continue forever set done true else reset loop count return null return next nextisnull nextisnullexception reinitialize endofloop getcontinueforever setdone resetloopcount protected void increment loop count loop count incrementloopcount loopcount protected void reset loop count loop count 0 resetloopcount loopcount see org apache jmeter control generic controller get iter count protected int get iter count return loop count 1 genericcontroller getitercount getitercount loopcount protected void re initialize set first true reset current increment loop count recover running version reinitialize setfirst resetcurrent incrementloopcount recoverrunningversion constructor for use when a property editor is delegating to us wrapper editor object source property editor type editor property editor gui editor boolean accepts null boolean accepts expressions boolean accepts other object default value super source initialize type editor gui editor accepts null accepts expressions accepts other default value propertyeditor wrappereditor propertyeditor typeeditor propertyeditor guieditor acceptsnull acceptsexpressions acceptsother defaultvalue typeeditor guieditor acceptsnull acceptsexpressions acceptsother defaultvalue constructor for use for regular instantiation and by subclasses wrapper editor property editor type editor property editor gui editor boolean accepts null boolean accepts expressions boolean accepts other object default value super initialize type editor gui editor accepts null accepts expressions accepts other default value wrappereditor propertyeditor typeeditor propertyeditor guieditor acceptsnull acceptsexpressions acceptsother defaultvalue typeeditor guieditor acceptsnull acceptsexpressions acceptsother defaultvalue private void initialize property editor typeeditor property editor guieditor boolean acceptsnull boolean acceptsexpressions boolean acceptsother object default value this type editor typeeditor this gui editor guieditor this accepts null acceptsnull this accepts expressions acceptsexpressions this accepts other acceptsother set value default value last valid value get as text if guieditor instanceof combo string editor string tags combo string editor guieditor get tags provide an initial edit value if necessary this is an heuristic that tries to provide the most convenient initial edit value string v if acceptsother v non nls 1 else if is valid value non nls 1 v non nls 1 else if acceptsexpressions v non nls 1 else if tags null tags length 0 v tags 0 else v get as text combo string editor guieditor set initial edit value v guieditor add property change listener this propertyeditor _typeeditor propertyeditor _guieditor _acceptsnull _acceptsexpressions _acceptsother defaultvalue typeeditor _typeeditor guieditor _guieditor acceptsnull _acceptsnull acceptsexpressions _acceptsexpressions acceptsother _acceptsother setvalue defaultvalue lastvalidvalue getastext _guieditor combostringeditor combostringeditor _guieditor gettags _acceptsother isvalidvalue _acceptsexpressions getastext combostringeditor _guieditor setinitialeditvalue _guieditor addpropertychangelistener public boolean supports custom editor return true supportscustomeditor public component get custom editor return gui editor get custom editor getcustomeditor guieditor getcustomeditor public string get tags return gui editor get tags gettags guieditor gettags determine wheter a string is one of the known tags param text return true iif text equals one of the get tags private boolean isa tag string text string tags get tags if tags null return false for int i 0 i tags length i if tags i equals text return true return false gettags isatag gettags determine whether a string is a valid value for the property param text the value to be checked return true iif text is a valid value private boolean is valid value string text if text null return accepts null if accepts expressions is expression text return true not an expression isn t or can t be not null the known tags are assumed to be valid if isa tag text return true was not a tag so if we can t accept other values if accepts other return false delegate the final check to the type editor try type editor set as text text catch illegal argument exception e1 set as text failed not valid return false set as text succeeded valid return true isvalidvalue acceptsnull acceptsexpressions isexpression isatag acceptsother typeeditor typeeditor setastext illegalargumentexception setastext setastext this method is used to do some low cost defensive programming it is called when a condition that the program logic should prevent from happening occurs i hope this will help early detection of logical bugs in property value handling throws error always throws an error private final void should never happen string msg throws error throw new error msg programming error bail out shouldneverhappen same as should never happen but provide a source exception param e the exception that helped identify the problem throws error always throws one private final void should never happen exception e throws error throw new error e to string programming error bail out shouldneverhappen shouldneverhappen tostring check if a string is a valid j meter expression p the current implementation is very basic it just accepts any string containing as a valid expression todo improve but keep returning true for private final boolean is expression string text return text index of 1 non nls 1 jmeter isexpression indexof same as is expression string param text return true iif text is a string and is expression text private final boolean is expression object text return text instanceof string is expression string text isexpression isexpression isexpression isexpression see java beans property editor get value see org apache jmeter testelement property j meter property public object get value string text string gui editor get value object value if text null if accepts null should never happen text is null but null is not allowed value null else if accepts expressions is expression text value text else not an expression isn t or can t be not null a check just in case if accepts other isa tag text should never happen text is not a tag but other entries are not allowed try bug 44314 number field does not seem to accept try type editor set as text text catch number format exception e if text length 0 text 0 non nls 1 type editor set as text text else should never happen e catch illegal argument exception e should never happen e value type editor get value if log is debug enabled log debug value null value get class get name null value return value propertyeditor getvalue jmeterproperty getvalue guieditor getvalue acceptsnull shouldneverhappen acceptsexpressions isexpression acceptsother isatag shouldneverhappen typeeditor setastext numberformatexception typeeditor setastext shouldneverhappen illegalargumentexception shouldneverhappen typeeditor getvalue isdebugenabled getclass getname public void set value object value string text if log is debug enabled log debug value null value get class get name null value if value null if accepts null throw new illegal argument exception null is not allowed text null else if accepts expressions is expression value text string value else not an expression isn t or can t be not null type editor set value value may throw illegal argument exc text fix get as text bug type editor get as text if accepts other isa tag text throw new illegal argument exception value not allowed text gui editor set value text setvalue isdebugenabled getclass getname acceptsnull illegalargumentexception acceptsexpressions isexpression typeeditor setvalue illegalargumentexc fixgetastextbug typeeditor getastext acceptsother isatag illegalargumentexception guieditor setvalue private string fix get as text bug string as text if as text null return as text if as text equals true log debug true true so we can detect it return true if as text equals false log debug false false so we can detect it return false return as text fixgetastextbug astext astext astext astext astext astext public string get as text string text fix get as text bug gui editor get as text if text null if accepts null should never happen text is null but null is not allowed else if accepts expressions is expression text not an expression can t be or isn t not null try type editor set as text text catch illegal argument exception e should never happen e text fix get as text bug type editor get as text a check just in case if accepts other isa tag text should never happen text is not a tag but other values are not allowed if log is debug enabled log debug text return text getastext fixgetastextbug guieditor getastext acceptsnull shouldneverhappen acceptsexpressions isexpression typeeditor setastext illegalargumentexception shouldneverhappen fixgetastextbug typeeditor getastext acceptsother isatag shouldneverhappen isdebugenabled public void set as text string text throws illegal argument exception if log is debug enabled log debug text null null text string value if text null if accepts null throw new illegal argument exception null parameter not allowed value null else if accepts expressions is expression text value text else some editors do tiny transformations e g true to true type editor set as text text may throw illegal argument exception value type editor get as text if accepts other isa tag text throw new illegal argument exception value not allowed text gui editor set value value setastext illegalargumentexception isdebugenabled acceptsnull illegalargumentexception acceptsexpressions isexpression typeeditor setastext illegalargumentexception typeeditor getastext acceptsother isatag illegalargumentexception guieditor setvalue public void property change property change event event string text fix get as text bug gui editor get as text if is valid value text last valid value text fire property change else if gui package get instance null log warn invalid value text gui editor else j option pane show message dialog gui editor get custom editor get parent j meter utils get res string property editor value is invalid message non nls 1 j meter utils get res string property editor value is invalid title non nls 1 j option pane warning message revert to the previous value gui editor set as text last valid value propertychange propertychangeevent fixgetastextbug guieditor getastext isvalidvalue lastvalidvalue firepropertychange guipackage getinstance guieditor joptionpane showmessagedialog guieditor getcustomeditor getparent jmeterutils getresstring property_editor value_is_invalid_message jmeterutils getresstring property_editor value_is_invalid_title joptionpane warning_message guieditor setastext lastvalidvalue private final int length prefix len j meter utils get prop default tcp binarylength prefix length 2 non nls 1 public length prefixed binarytcp client impl super new binarytcp client impl tcp client set eol byte byte max value 1 lengthprefixlen jmeterutils getpropdefault lengthprefixedbinarytcpclientimpl binarytcpclientimpl tcpclient seteolbyte max_value public void write output stream os string s try os write int to byte array s length 2 length prefix len log debug wrote s length 2 bytes this tcp client write os s catch io exception e log warn write error e return outputstream inttobytearray lengthprefixlen tcpclient ioexception java io input stream public void write output stream os input stream is this tcp client write os is inputstream outputstream inputstream tcpclient public string read input stream is byte msg new byte 0 int msg len 0 try byte length buffer new byte length prefix len if is read length buffer 0 length prefix len length prefix len msg len byte array to int length buffer msg new byte msg len int bytes is read msg if bytes msg len log warn incomplete message read expected msg len got bytes catch socket timeout exception e drop out to handle buffer catch interruptedio exception e drop out to handle buffer catch io exception e log warn read error e string buffer j orphan utils ba to hex string msg log debug read msg len n buffer return buffer inputstream msglen lengthbuffer lengthprefixlen lengthbuffer lengthprefixlen lengthprefixlen msglen bytearraytoint lengthbuffer msglen msglen msglen sockettimeoutexception interruptedioexception ioexception jorphanutils batohexstring msglen not useful as the byte is never used return returns the eol byte public byte get eol byte return tcp client get eol byte eolbyte geteolbyte tcpclient geteolbyte param eol int the eol byte to set public void set eol byte int eol int throw new unsupported operation exception cannot set eom byte for prefixed messages eolint eolbyte seteolbyte eolint unsupportedoperationexception eombyte public static final string reset interpreter bean shell sampler reset interpreter non nls 1 protected string get init file property return init file reset_interpreter beanshellsampler resetinterpreter getinitfileproperty init_file returns a formatted string label describing this sampler return a formatted string label describing this sampler public string get label return get name getlabel getname public string get script return this get property as string script getscript getpropertyasstring public string get filename return get property as string filename getfilename getpropertyasstring public string get parameters return get property as string parameters getparameters getpropertyasstring public boolean is reset interpreter return get property as boolean reset interpreter isresetinterpreter getpropertyasboolean reset_interpreter public sample result sample entry e entry tends to be ignored log info get label get filename sample result res new sample result boolean is successful false res set sample label get label res sample start final bean shell interpreter bsh interpreter get bean shell interpreter if bsh interpreter null res sample end res set response code 503 non nls 1 res set response message bean shell interpreter not found res set successful false return res try string request get script string file name get filename if file name length 0 res set sampler data request else res set sampler data file name bsh interpreter set label get label non nls 1 bsh interpreter set file name get filename non nls 1 bsh interpreter set sample result res non nls 1 save parameters as single line and as string array bsh interpreter set parameters get parameters non nls 1 bsh interpreter set bsh args non nls 1 j orphan utils split get parameters non nls 1 set default values bsh interpreter set response code 200 non nls 1 bsh interpreter set response message ok non nls 1 bsh interpreter set is success true non nls 1 add variables for access to context and variables j meter context jmctx j meter context service get context j meter variables vars jmctx get variables bsh interpreter set ctx jmctx non nls 1 bsh interpreter set vars vars non nls 1 res set data type sample result text assume text output script can override if necessary object bsh out if file name length 0 bsh out bsh interpreter eval request else bsh out bsh interpreter source file name if bsh out null set response data string out bsh out to string res set response data out get bytes script can also use set response data so long as it returns null res set response code bsh interpreter get response code to string non nls 1 res set response message bsh interpreter get response message to string non nls 1 is successful boolean value of bsh interpreter get is success non nls 1 to string boolean value to avoid class loading problems when bsh jar is missing we don t try to catch this error separately catch bsh eval error ex log debug ex res set response code 500 non nls 1 res set response message ex to string but we do trap this error to make tests work better catch no class def found error ex log error bean shell jar missing ex to string res set response code 501 non nls 1 res set response message ex to string res set stop thread true no point continuing catch exception ex mainly for bsh eval error log warn ex to string res set response code 500 non nls 1 res set response message ex to string res sample end set if we were successful or not res set successful is successful return res sampleresult getlabel getfilename sampleresult sampleresult issuccessful setsamplelabel getlabel samplestart beanshellinterpreter bshinterpreter getbeanshellinterpreter bshinterpreter sampleend setresponsecode setresponsemessage beanshell setsuccessful getscript filename getfilename filename setsamplerdata setsamplerdata filename bshinterpreter getlabel bshinterpreter filename getfilename bshinterpreter sampleresult bshinterpreter getparameters bshinterpreter jorphanutils getparameters bshinterpreter responsecode bshinterpreter responsemessage bshinterpreter issuccess jmetercontext jmetercontextservice getcontext jmetervariables getvariables bshinterpreter bshinterpreter setdatatype sampleresult bshout filename bshout bshinterpreter bshout bshinterpreter filename bshout bshout tostring setresponsedata getbytes setresponsedata setresponsecode bshinterpreter responsecode tostring setresponsemessage bshinterpreter responsemessage tostring issuccessful valueof bshinterpreter issuccess tostring booleanvalue evalerror setresponsecode setresponsemessage tostring noclassdeffounderror beanshell tostring setresponsecode setresponsemessage tostring setstopthread evalerror tostring setresponsecode setresponsemessage tostring sampleend setsuccessful issuccessful private final j panel message panel new j panel public jms publisher gui init jpanel messagepanel jpanel jmspublishergui the name of the property for the jms publisher gui is jms publisher public string get label resource return jms publisher non nls 1 jmspublishergui jms_publisher getlabelresource jms_publisher see org apache jmeter gui j metergui component create test element public test element create test element publisher sampler sampler new publisher sampler this configure test element sampler sampler set usejndi properties string value of use properties is selected sampler setjndi intial context factory jndiicf get text sampler set provider url url field get text sampler set connection factory jndi conn fac get text sampler set topic jms topic get text sampler set username jms user get text sampler set password jms pwd get text sampler set text message text message get text sampler set input file message file get filename sampler set random path random file get filename sampler set config choice config choice get text sampler set message choice msg choice get text sampler set iterations iterations get text sampler set use auth use auth is selected return sampler jmeterguicomponent createtestelement testelement createtestelement publishersampler publishersampler configuretestelement setusejndiproperties valueof useproperties isselected setjndiintialcontextfactory gettext setproviderurl urlfield gettext setconnectionfactory jndiconnfac gettext settopic jmstopic gettext setusername jmsuser gettext setpassword jmspwd gettext settextmessage textmessage gettext setinputfile messagefile getfilename setrandompath randomfile getfilename setconfigchoice configchoice gettext setmessagechoice msgchoice gettext setiterations gettext setuseauth useauth isselected modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element s publisher sampler sampler publisher sampler s this configure test element sampler sampler set usejndi properties string value of use properties is selected sampler setjndi intial context factory jndiicf get text sampler set provider url url field get text sampler set connection factory jndi conn fac get text sampler set topic jms topic get text sampler set username jms user get text sampler set password jms pwd get text sampler set text message text message get text sampler set input file message file get filename sampler set random path random file get filename sampler set config choice config choice get text sampler set message choice msg choice get text sampler set iterations iterations get text sampler set use auth use auth is selected testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement publishersampler publishersampler configuretestelement setusejndiproperties valueof useproperties isselected setjndiintialcontextfactory gettext setproviderurl urlfield gettext setconnectionfactory jndiconnfac gettext settopic jmstopic gettext setusername jmsuser gettext setpassword jmspwd gettext settextmessage textmessage gettext setinputfile messagefile getfilename setrandompath randomfile getfilename setconfigchoice configchoice gettext setmessagechoice msgchoice gettext setiterations gettext setuseauth useauth isselected init adds jndiicf to the main panel the class reuses logic from soap sampler since it is common private void init this set layout new vertical layout 5 vertical layout left vertical layout top main panel j panel main panel new j panel border margin new empty border 10 10 5 10 main panel set border margin main panel set layout new vertical layout 5 vertical layout left title j label panel title label new j label get static label font cur font panel title label get font int cur font size cur font get size cur font size 4 panel title label set font new font cur font get font name cur font get style cur font size main panel add panel title label name main panel add get name panel button for browsing webservice wsdl lookup set layout new vertical layout 6 vertical layout left main panel add lookup lookup add use properties use properties add change listener this lookup add jndiicf lookup add url field lookup add jndi conn fac config choice add change listener this msg choice add change listener this j panel common params new j panel common params set layout new vertical layout 6 vertical layout left main panel add common params common params add jms topic common params add use auth common params add jms user common params add jms pwd common params add iterations message panel set layout new vertical layout 3 vertical layout left message panel add config choice message panel add msg choice message panel add message file message panel add random file message panel add text message main panel add message panel dimension pref new dimension 400 200 text message set preferred size pref we have to add the gui to the change listener this add main panel mainpanel soapsampler setlayout verticallayout verticallayout verticallayout jpanel mainpanel jpanel emptyborder mainpanel setborder mainpanel setlayout verticallayout verticallayout jlabel paneltitlelabel jlabel getstaticlabel curfont paneltitlelabel getfont curfontsize curfont getsize curfontsize paneltitlelabel setfont curfont getfontname curfont getstyle curfontsize mainpanel paneltitlelabel mainpanel getnamepanel setlayout verticallayout verticallayout mainpanel useproperties useproperties addchangelistener urlfield jndiconnfac configchoice addchangelistener msgchoice addchangelistener jpanel commonparams jpanel commonparams setlayout verticallayout verticallayout mainpanel commonparams commonparams jmstopic commonparams useauth commonparams jmsuser commonparams jmspwd commonparams messagepanel setlayout verticallayout verticallayout messagepanel configchoice messagepanel msgchoice messagepanel messagefile messagepanel randomfile messagepanel textmessage mainpanel messagepanel textmessage setpreferredsize mainpanel public void clear gui super clear gui use properties set selected false jndiicf set text non nls 1 url field set text non nls 1 jndi conn fac set text non nls 1 jms topic set text non nls 1 jms user set text non nls 1 jms pwd set text non nls 1 text message set text non nls 1 message file set filename non nls 1 random file set filename non nls 1 msg choice set text non nls 1 config choice set text use text rsc update config use text rsc iterations set text non nls 1 use auth set selected false cleargui cleargui useproperties setselected settext urlfield settext jndiconnfac settext jmstopic settext jmsuser settext jmspwd settext textmessage settext messagefile setfilename randomfile setfilename msgchoice settext configchoice settext use_text_rsc updateconfig use_text_rsc settext useauth setselected the implementation loads the url and the soap action for the request public void configure test element el super configure el publisher sampler sampler publisher sampler el use properties set selected sampler get usejndi properties as boolean jndiicf set text sampler getjndi initial context factory url field set text sampler get provider url jndi conn fac set text sampler get connection factory jms topic set text sampler get topic jms user set text sampler get username jms pwd set text sampler get password text message set text sampler get text message message file set filename sampler get input file random file set filename sampler get random path config choice set text sampler get config choice msg choice set text sampler get message choice update config sampler get config choice iterations set text sampler get iterations use auth set selected sampler is use auth testelement publishersampler publishersampler useproperties setselected getusejndipropertiesasboolean settext getjndiinitialcontextfactory urlfield settext getproviderurl jndiconnfac settext getconnectionfactory jmstopic settext gettopic jmsuser settext getusername jmspwd settext getpassword textmessage settext gettextmessage messagefile setfilename getinputfile randomfile setfilename getrandompath configchoice settext getconfigchoice msgchoice settext getmessagechoice updateconfig getconfigchoice settext getiterations useauth setselected isuseauth method from action listener param event that occurred public void action performed action event event actionlistener actionperformed actionevent when a widget state changes it will notify this class so we can enable disable the correct items public void state changed change event event if event get source this config choice update config this config choice get text else if event get source this msg choice update message type this msg choice get text else if event get source use properties if use properties is selected this jndiicf set enabled false this url field set enabled false else this jndiicf set enabled true this url field set enabled true statechanged changeevent getsource configchoice updateconfig configchoice gettext getsource msgchoice updatemessagetype msgchoice gettext getsource useproperties useproperties isselected setenabled urlfield setenabled setenabled urlfield setenabled update config contains the actual logic for enabling or disabling text message file or random path param command private void update config string command if command equals use text rsc text message set enabled true message file enable file false random file enable file false else if command equals use random rsc text message set enabled false message file enable file false random file enable file true else text message set enabled false message file enable file true random file enable file false updateconfig use_text_rsc textmessage setenabled messagefile enablefile randomfile enablefile use_random_rsc textmessage setenabled messagefile enablefile randomfile enablefile textmessage setenabled messagefile enablefile randomfile enablefile param msg type private void update message type string msg type if msg type equals object msg rsc if config choice get text equals use text rsc j option pane show confirm dialog this j meter utils get res string jms error msg non nls 1 warning j option pane ok cancel option j option pane error message msgtype updatemessagetype msgtype msgtype object_msg_rsc configchoice gettext use_text_rsc joptionpane showconfirmdialog jmeterutils getresstring jms_error_msg joptionpane ok_cancel_option joptionpane error_message private constructor to prevent instantiation private base64 encoder base64encoder public final static string encode string s return encode s get bytes getbytes public final static string encode byte bs string buffer out new string buffer int bl bs length for int i 0 i bl i 3 out append encode atom bs i bl i return out to string stringbuffer stringbuffer encodeatom tostring public final static string encode atom byte b int strt int left string buffer out new string buffer if left 1 byte b1 b strt int k 0 out append string value of pem array b1 2 63 out append string value of pem array b1 4 48 k 4 15 out append string value of eq out append string value of eq return out to string if left 2 byte b2 b strt byte b4 b strt 1 int l 0 out append string value of pem array b2 2 63 out append string value of pem array b2 4 48 b4 4 15 out append string value of pem array b4 2 60 l 6 3 out append string value of eq return out to string byte b3 b strt byte b5 b strt 1 byte b6 b strt 2 out append string value of pem array b3 2 63 out append string value of pem array b3 4 48 b5 4 15 out append string value of pem array b5 2 60 b6 6 3 out append string value of pem array b6 63 return out to string encodeatom stringbuffer stringbuffer valueof pem_array valueof pem_array valueof valueof tostring valueof pem_array valueof pem_array valueof pem_array valueof tostring valueof pem_array valueof pem_array valueof pem_array valueof pem_array tostring default constructor for ldap config gui public ldap ext config gui this true ldapconfiggui ldapextconfiggui to do constructor description param display name to do parameter description public ldap ext config gui boolean display name this display name display name init todo displayname todo ldapextconfiggui displayname displayname displayname public string get label resource return ldapext sample title non nls 1 getlabelresource ldapext_sample_title a newly created component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui param element the test element to configure public void configure test element element super configure element servername set text element get property as string ldap ext sampler servername port set text element get property as string ldap ext sampler port rootdn set text element get property as string ldap ext sampler rootdn scope set selected index element get property as int ldap ext sampler scope countlim set text element get property as string ldap ext sampler countlim timelim set text element get property as string ldap ext sampler timelim attribs set text element get property as string ldap ext sampler attribs retobj set selected element get property as boolean ldap ext sampler retobj deref set selected element get property as boolean ldap ext sampler deref connto set text element get property as string ldap ext sampler connto parseflag set selected element get property as boolean ldap ext sampler parseflag secure set selected element get property as boolean ldap ext sampler secure userpw set text element get property as string ldap ext sampler userpw userdn set text element get property as string ldap ext sampler userdn comparedn set text element get property as string ldap ext sampler comparedn comparefilt set text element get property as string ldap ext sampler comparefilt modddn set text element get property as string ldap ext sampler modddn newdn set text element get property as string ldap ext sampler newdn card layout cl card layout cards get layout final string test type element get property as string ldap ext sampler test if test type equals ldap ext sampler unbind unbind set selected true cl show cards cards default else if test type equals ldap ext sampler bind bind set selected true cl show cards cards bind else if test type equals ldap ext sampler sbind sbind set selected true cl show cards cards default else if test type equals ldap ext sampler compare compare set selected true cl show cards cards compare else if test type equals ldap ext sampler add add test set selected true add set text element get property as string ldap ext sampler base entry dn table add panel configure test element element get property ldap ext sampler arguments get object value cl show cards cards add else if test type equals ldap ext sampler modify modify test set selected true modify set text element get property as string ldap ext sampler base entry dn table modify panel configure test element element get property ldap ext sampler ldaparguments get object value cl show cards cards modify else if test type equals ldap ext sampler delete delete test set selected true delete set text element get property as string ldap ext sampler delete cl show cards cards delete else if test type equals ldap ext sampler rename rename set selected true cl show cards cards rename else if test type equals ldap ext sampler search search test set selected true searchbase set text element get property as string ldap ext sampler searchbase searchfilter set text element get property as string ldap ext sampler searchfilter cl show cards cards search testelement testelement settext getpropertyasstring ldapextsampler settext getpropertyasstring ldapextsampler settext getpropertyasstring ldapextsampler setselectedindex getpropertyasint ldapextsampler settext getpropertyasstring ldapextsampler settext getpropertyasstring ldapextsampler settext getpropertyasstring ldapextsampler setselected getpropertyasboolean ldapextsampler setselected getpropertyasboolean ldapextsampler settext getpropertyasstring ldapextsampler setselected getpropertyasboolean ldapextsampler setselected getpropertyasboolean ldapextsampler settext getpropertyasstring ldapextsampler settext getpropertyasstring ldapextsampler settext getpropertyasstring ldapextsampler settext getpropertyasstring ldapextsampler settext getpropertyasstring ldapextsampler settext getpropertyasstring ldapextsampler cardlayout cardlayout getlayout testtype getpropertyasstring ldapextsampler testtype ldapextsampler setselected cards_default testtype ldapextsampler setselected cards_bind testtype ldapextsampler setselected cards_default testtype ldapextsampler setselected cards_compare testtype ldapextsampler addtest setselected settext getpropertyasstring ldapextsampler base_entry_dn tableaddpanel testelement getproperty ldapextsampler getobjectvalue cards_add testtype ldapextsampler modifytest setselected settext getpropertyasstring ldapextsampler base_entry_dn tablemodifypanel testelement getproperty ldapextsampler getobjectvalue cards_modify testtype ldapextsampler deletetest setselected settext getpropertyasstring ldapextsampler cards_delete testtype ldapextsampler setselected cards_rename testtype ldapextsampler searchtest setselected settext getpropertyasstring ldapextsampler settext getpropertyasstring ldapextsampler cards_search implements j metergui component create test element public test element create test element config test element element new config test element modify test element element return element jmeterguicomponent createtestelement testelement createtestelement configtestelement configtestelement modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element element element clear configure test element element element set property ldap ext sampler servername servername get text element set property ldap ext sampler port port get text element set property ldap ext sampler rootdn rootdn get text element set property ldap ext sampler scope string value of scope get selected index element set property ldap ext sampler countlim countlim get text element set property ldap ext sampler timelim timelim get text element set property ldap ext sampler attribs attribs get text element set property ldap ext sampler retobj boolean to string retobj is selected element set property ldap ext sampler deref boolean to string deref is selected element set property ldap ext sampler connto connto get text element set property ldap ext sampler parseflag boolean to string parseflag is selected element set property ldap ext sampler secure boolean to string secure is selected element set property ldap ext sampler userdn userdn get text element set property ldap ext sampler userpw userpw get text element set property ldap ext sampler comparedn comparedn get text element set property ldap ext sampler comparefilt comparefilt get text element set property ldap ext sampler modddn modddn get text element set property ldap ext sampler newdn newdn get text if add test is selected element set property new string property ldap ext sampler test ldap ext sampler add element set property new string property ldap ext sampler base entry dn add get text element set property new test element property ldap ext sampler arguments table add panel create test element if modify test is selected element set property new string property ldap ext sampler test ldap ext sampler modify element set property new string property ldap ext sampler base entry dn modify get text element set property new test element property ldap ext sampler ldaparguments table modify panel create test element if delete test is selected element set property new string property ldap ext sampler test ldap ext sampler delete element set property new string property ldap ext sampler delete delete get text if search test is selected element set property new string property ldap ext sampler test ldap ext sampler search element set property new string property ldap ext sampler searchbase searchbase get text element set property new string property ldap ext sampler searchfilter searchfilter get text if bind is selected element set property new string property ldap ext sampler test ldap ext sampler bind if sbind is selected element set property new string property ldap ext sampler test ldap ext sampler sbind if compare is selected element set property new string property ldap ext sampler test ldap ext sampler compare if rename is selected element set property new string property ldap ext sampler test ldap ext sampler rename if unbind is selected element set property new string property ldap ext sampler test ldap ext sampler unbind testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement setproperty ldapextsampler gettext setproperty ldapextsampler gettext setproperty ldapextsampler gettext setproperty ldapextsampler valueof getselectedindex setproperty ldapextsampler gettext setproperty ldapextsampler gettext setproperty ldapextsampler gettext setproperty ldapextsampler tostring isselected setproperty ldapextsampler tostring isselected setproperty ldapextsampler gettext setproperty ldapextsampler tostring isselected setproperty ldapextsampler tostring isselected setproperty ldapextsampler gettext setproperty ldapextsampler gettext setproperty ldapextsampler gettext setproperty ldapextsampler gettext setproperty ldapextsampler gettext setproperty ldapextsampler gettext addtest isselected setproperty stringproperty ldapextsampler ldapextsampler setproperty stringproperty ldapextsampler base_entry_dn gettext setproperty testelementproperty ldapextsampler tableaddpanel createtestelement modifytest isselected setproperty stringproperty ldapextsampler ldapextsampler setproperty stringproperty ldapextsampler base_entry_dn gettext setproperty testelementproperty ldapextsampler tablemodifypanel createtestelement deletetest isselected setproperty stringproperty ldapextsampler ldapextsampler setproperty stringproperty ldapextsampler gettext searchtest isselected setproperty stringproperty ldapextsampler ldapextsampler setproperty stringproperty ldapextsampler gettext setproperty stringproperty ldapextsampler gettext isselected setproperty stringproperty ldapextsampler ldapextsampler isselected setproperty stringproperty ldapextsampler ldapextsampler isselected setproperty stringproperty ldapextsampler ldapextsampler isselected setproperty stringproperty ldapextsampler ldapextsampler isselected setproperty stringproperty ldapextsampler ldapextsampler implements j metergui component clear gui public void clear gui super clear gui rootdn set text non nls 1 searchbase set text non nls 1 searchfilter set text non nls 1 delete set text non nls 1 add set text non nls 1 modify set text non nls 1 servername set text non nls 1 port set text non nls 1 add set text non nls 1 scope set selected index scope strings length 1 countlim set text non nls 1 timelim set text non nls 1 attribs set text non nls 1 userdn set text non nls 1 userpw set text non nls 1 comparedn set text non nls 1 comparefilt set text non nls 1 modddn set text non nls 1 newdn set text non nls 1 connto set text non nls 1 retobj set selected false deref set selected false parseflag set selected false secure set selected false add test set selected false modify test set selected false delete test set selected false search test set selected false bind set selected false rename set selected false unbind set selected false sbind set selected false compare set selected false table add panel clear table modify panel clear jmeterguicomponent cleargui cleargui cleargui settext settext settext settext settext settext settext settext settext setselectedindex scope_strings settext settext settext settext settext settext settext settext settext settext setselected setselected setselected setselected addtest setselected modifytest setselected deletetest setselected searchtest setselected setselected setselected setselected setselected setselected tableaddpanel tablemodifypanel this item state changed listener for changing the card layout for based on the test selected in the user defined test case public void item state changed item event ie card layout cl card layout cards get layout if add test is selected cl show cards cards add else if delete test is selected cl show cards cards delete else if bind is selected cl show cards cards bind else if sbind is selected cl show cards cards bind else if rename is selected cl show cards cards rename else if compare is selected cl show cards cards compare else if search test is selected cl show cards cards search else if modify test is selected cl show cards cards modify else e g unbind cl show cards cards default itemstatechanged itemstatechanged itemevent cardlayout cardlayout getlayout addtest isselected cards_add deletetest isselected cards_delete isselected cards_bind isselected cards_bind isselected cards_rename isselected cards_compare searchtest isselected cards_search modifytest isselected cards_modify cards_default this will create the servername panel in the ldap config gui private j panel create servername panel j panel server panel new j panel new border layout 5 0 j label label new j label j meter utils get res string servername non nls 1 label set label for servername server panel add label border layout west server panel add servername border layout center return server panel ldapconfiggui jpanel createservernamepanel jpanel serverpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor serverpanel borderlayout serverpanel borderlayout serverpanel this will create the port panel in the ldap config gui private j panel create port panel j panel port panel new j panel new border layout 5 0 j label label new j label j meter utils get res string port non nls 1 label set label for port port panel add label border layout west port panel add port border layout center return port panel ldapconfiggui jpanel createportpanel jpanel portpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor portpanel borderlayout portpanel borderlayout portpanel this will create the root distinguised name panel in the ldap config gui private j panel create rootdn panel j panel rootdn panel new j panel new border layout 5 0 j label label new j label j meter utils get res string ddn non nls 1 label set label for rootdn rootdn panel add label border layout west rootdn panel add rootdn border layout center return rootdn panel ldapconfiggui jpanel createrootdnpanel jpanel rootdnpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor rootdnpanel borderlayout rootdnpanel borderlayout rootdnpanel this will create the bind sbind panel in the ldap config gui private j panel create bind panel vertical panel bind panel new vertical panel bind panel add create servername panel bind panel add create port panel bind panel add create rootdn panel j panel b panel new j panel new border layout 5 0 j label blabel0 new j label j meter utils get res string userdn non nls 1 blabel0 set label for userdn b panel add blabel0 border layout west b panel add userdn border layout center bind panel add b panel j panel b1 panel new j panel new border layout 5 0 j label blabel1 new j label j meter utils get res string userpw non nls 1 blabel1 set label for userpw b1 panel add blabel1 border layout west b1 panel add userpw border layout center bind panel add b1 panel j panel b2 panel new j panel new border layout 5 0 j label blabel2 new j label j meter utils get res string ldap connto non nls 1 blabel2 set label for connto b2 panel add blabel2 border layout west b2 panel add connto border layout center bind panel add b2 panel bind panel add secure return bind panel ldapconfiggui jpanel createbindpanel verticalpanel bindpanel verticalpanel bindpanel createservernamepanel bindpanel createportpanel bindpanel createrootdnpanel jpanel bpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor bpanel borderlayout bpanel borderlayout bindpanel bpanel jpanel b1panel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor b1panel borderlayout b1panel borderlayout bindpanel b1panel jpanel b2panel jpanel borderlayout jlabel jlabel jmeterutils getresstring ldap_connto setlabelfor b2panel borderlayout b2panel borderlayout bindpanel b2panel bindpanel bindpanel this will create the bind panel in the ldap config gui private j panel create compare panel vertical panel cbind panel new vertical panel j panel cb panel new j panel new border layout 5 0 j label c blabel0 new j label j meter utils get res string entrydn non nls 1 c blabel0 set label for comparedn cb panel add c blabel0 border layout west cb panel add comparedn border layout center cbind panel add cb panel j panel cb panel1 new j panel new border layout 5 0 j label c blabel1 new j label j meter utils get res string comparefilt non nls 1 c blabel1 set label for comparefilt cb panel1 add c blabel1 border layout west cb panel1 add comparefilt border layout center cbind panel add cb panel1 return cbind panel ldapconfiggui jpanel createcomparepanel verticalpanel cbindpanel verticalpanel jpanel cbpanel jpanel borderlayout jlabel cblabel0 jlabel jmeterutils getresstring cblabel0 setlabelfor cbpanel cblabel0 borderlayout cbpanel borderlayout cbindpanel cbpanel jpanel cbpanel1 jpanel borderlayout jlabel cblabel1 jlabel jmeterutils getresstring cblabel1 setlabelfor cbpanel1 cblabel1 borderlayout cbpanel1 borderlayout cbindpanel cbpanel1 cbindpanel this will create the search controls panel in the ldap config gui private j panel createsc panel vertical panel sc panel new vertical panel sc panel add scope j panel sc1 panel new j panel new border layout 5 0 j label label1 new j label j meter utils get res string countlim non nls 1 label1 set label for countlim sc1 panel add label1 border layout west sc1 panel add countlim border layout center sc panel add sc1 panel j panel sc2 panel new j panel new border layout 5 0 j label label2 new j label j meter utils get res string timelim non nls 1 label2 set label for timelim sc2 panel add label2 border layout west sc2 panel add timelim border layout center sc panel add sc2 panel j panel sc3 panel new j panel new border layout 5 0 j label label3 new j label j meter utils get res string attrs non nls 1 label3 set label for attribs sc3 panel add label3 border layout west sc3 panel add attribs border layout center sc panel add sc3 panel sc panel add retobj sc panel add deref sc panel add parseflag return sc panel ldapconfiggui jpanel createscpanel verticalpanel scpanel verticalpanel scpanel jpanel sc1panel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor sc1panel borderlayout sc1panel borderlayout scpanel sc1panel jpanel sc2panel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor sc2panel borderlayout sc2panel borderlayout scpanel sc2panel jpanel sc3panel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor sc3panel borderlayout sc3panel borderlayout scpanel sc3panel scpanel scpanel scpanel scpanel this will create the search panel in the ldap config gui private j panel create search panel vertical panel search panel new vertical panel j panel searchb panel new j panel new border layout 5 0 j label label new j label j meter utils get res string searchbase non nls 1 label set label for searchbase searchb panel add label border layout west searchb panel add searchbase border layout center j panel searchf panel new j panel new border layout 5 0 j label label20 new j label j meter utils get res string searchfilter non nls 1 label20 set label for searchfilter searchf panel add label20 border layout west searchf panel add searchfilter border layout center search panel add searchb panel search panel add searchf panel search panel add createsc panel return search panel ldapconfiggui jpanel createsearchpanel verticalpanel searchpanel verticalpanel jpanel searchbpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor searchbpanel borderlayout searchbpanel borderlayout jpanel searchfpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor searchfpanel borderlayout searchfpanel borderlayout searchpanel searchbpanel searchpanel searchfpanel searchpanel createscpanel searchpanel this will create the moddn panel in the ldap config gui private j panel create moddn panel vertical panel mod panel new vertical panel j panel rename panel new j panel new border layout 5 0 j label labelmod new j label j meter utils get res string modddn non nls 1 labelmod set label for modddn rename panel add labelmod border layout west rename panel add modddn border layout center j panel rename2 panel new j panel new border layout 5 0 j label labelmod2 new j label j meter utils get res string newdn non nls 1 labelmod2 set label for newdn rename2 panel add labelmod2 border layout west rename2 panel add newdn border layout center mod panel add rename panel mod panel add rename2 panel return mod panel ldapconfiggui jpanel createmoddnpanel verticalpanel modpanel verticalpanel jpanel renamepanel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor renamepanel borderlayout renamepanel borderlayout jpanel rename2panel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor rename2panel borderlayout rename2panel borderlayout modpanel renamepanel modpanel rename2panel modpanel this will create the delete panel in the ldap config gui private j panel create delete panel vertical panel panel new vertical panel j panel delete panel new j panel new border layout 5 0 j label label new j label j meter utils get res string delete non nls 1 label set label for delete delete panel add label border layout west delete panel add delete border layout center panel add delete panel return panel ldapconfiggui jpanel createdeletepanel verticalpanel verticalpanel jpanel deletepanel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor deletepanel borderlayout deletepanel borderlayout deletepanel this will create the add test panel in the ldap config gui private j panel create add panel j panel add panel new j panel new border layout 5 0 j panel add inner panel new j panel new border layout 5 0 j label label new j label j meter utils get res string entrydn non nls 1 label set label for add add inner panel add label border layout west add inner panel add add border layout center add panel add add inner panel border layout north add panel add table add panel border layout center return add panel ldapconfiggui jpanel createaddpanel jpanel addpanel jpanel borderlayout jpanel addinnerpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor addinnerpanel borderlayout addinnerpanel borderlayout addpanel addinnerpanel borderlayout addpanel tableaddpanel borderlayout addpanel this will create the modify panel in the ldap config gui private j panel create modify panel j panel modify panel new j panel new border layout 5 0 j panel modify inner panel new j panel new border layout 5 0 j label label new j label j meter utils get res string entrydn non nls 1 label set label for modify modify inner panel add label border layout west modify inner panel add modify border layout center modify panel add modify inner panel border layout north modify panel add table modify panel border layout center return modify panel ldapconfiggui jpanel createmodifypanel jpanel modifypanel jpanel borderlayout jpanel modifyinnerpanel jpanel borderlayout jlabel jlabel jmeterutils getresstring setlabelfor modifyinnerpanel borderlayout modifyinnerpanel borderlayout modifypanel modifyinnerpanel borderlayout modifypanel tablemodifypanel borderlayout modifypanel this will create the user defined test panel for create or modify or delete or search based on the panel selected in the itemevent in the ldap config gui private j panel test panel cards new j panel new card layout cards add new j panel cards default cards add create add panel cards add cards add create modify panel cards modify cards add create moddn panel cards rename cards add create delete panel cards delete cards add create search panel cards search cards add create bind panel cards bind cards add create compare panel cards compare return cards ldapconfiggui jpanel testpanel jpanel cardlayout jpanel cards_default createaddpanel cards_add createmodifypanel cards_modify createmoddnpanel cards_rename createdeletepanel cards_delete createsearchpanel cards_search createbindpanel cards_bind createcomparepanel cards_compare this will create the test panel in the ldap config gui private j panel create test panel j panel test panel new j panel new border layout test panel set border border factory create titled border j meter utils get res string test configuration non nls 1 test panel add new j label j meter utils get res string testt non nls 1 j panel row panel new j panel j panel row2 panel new j panel row panel add bind b group add bind row panel add unbind b group add unbind row panel add sbind b group add sbind row panel add rename b group add rename row2 panel add add test b group add add test row2 panel add delete test b group add delete test row2 panel add search test b group add search test row2 panel add compare b group add compare row2 panel add modify test b group add modify test test panel add row panel border layout north test panel add row2 panel border layout south return test panel ldapconfiggui jpanel createtestpanel jpanel testpanel jpanel borderlayout testpanel setborder borderfactory createtitledborder jmeterutils getresstring test_configuration testpanel jlabel jmeterutils getresstring jpanel rowpanel jpanel jpanel row2panel jpanel rowpanel bgroup rowpanel bgroup rowpanel bgroup rowpanel bgroup row2panel addtest bgroup addtest row2panel deletetest bgroup deletetest row2panel searchtest bgroup searchtest row2panel bgroup row2panel modifytest bgroup modifytest testpanel rowpanel borderlayout testpanel row2panel borderlayout testpanel this will initalise all the panel in the ldap config gui private void init set layout new border layout 0 5 if display name set border make border add make title panel border layout north vertical panel main panel new vertical panel main panel add create test panel main panel add test panel add main panel border layout center take note of when buttong are changed so can change panel bind add item listener this sbind add item listener this unbind add item listener this compare add item listener this add test add item listener this modify test add item listener this rename add item listener this delete test add item listener this search test add item listener this ldapconfiggui setlayout borderlayout displayname setborder makeborder maketitlepanel borderlayout verticalpanel mainpanel verticalpanel mainpanel createtestpanel mainpanel testpanel mainpanel borderlayout additemlistener additemlistener additemlistener additemlistener addtest additemlistener modifytest additemlistener additemlistener deletetest additemlistener searchtest additemlistener private j meter context jmctx public x path assertion test string arg0 super arg0 jmetercontext xpathassertiontest protected void set up throws exception super set up jmctx j meter context service get context assertion new x path assertion assertion set thread context jmctx this would be done by the run command result new sample result result set response data read file testfiles x path assertion test xml vars new j meter variables jmctx set variables vars jmctx set previous result result test log set priority org apache log priority debug setup setup jmetercontextservice getcontext xpathassertion setthreadcontext sampleresult setresponsedata readfile xpathassertiontest jmetervariables setvariables setpreviousresult testlog setpriority private void set alternate response data string data company xmlext query ret row value field ret code lis ok value value field ret code extension value value field alias value value field positioncount value value field invalidpincount 0 value value field pinposition1 1 value value field pinpositionvalue1 value value field pinposition2 5 value value field pinpositionvalue2 value value field pinposition3 6 value value field pinpositionvalue3 value row company xmlext query ret result set response data data get bytes setalternateresponsedata retcode lis_ok retcodeextension setresponsedata getbytes private byte array output stream readba string name throws io exception buffered input stream bis new buffered input stream new file input stream find test file name byte array output stream baos new byte array output stream 1000 int len 0 byte data new byte 512 while len bis read data 0 baos write data 0 len bis close return baos bytearrayoutputstream ioexception bufferedinputstream bufferedinputstream fileinputstream findtestfile bytearrayoutputstream bytearrayoutputstream private byte read file string name throws io exception return readba name to byte array readfile ioexception tobytearray public void test assertionok throws exception assertion setx path string assertion result res assertion get result result test log debug is error res is error is failure res is failure test log debug failure message res get failure message assert false should not be an error res is error assert false should not be a failure res is failure testassertionok setxpathstring assertionresult getresult testlog iserror iserror isfailure isfailure testlog getfailuremessage assertfalse iserror assertfalse isfailure public void test assertion fail throws exception assertion setx path string x assertion result res assertion get result result test log debug is error res is error is failure res is failure test log debug failure message res get failure message assert false should not be an error res is error assert true should be a failure res is failure testassertionfail setxpathstring assertionresult getresult testlog iserror iserror isfailure isfailure testlog getfailuremessage assertfalse iserror asserttrue isfailure public void test assertion path1 throws exception assertion setx path string code 1 assertion result res assertion get result result test log debug is error res is error is failure res is failure test log debug failure message res get failure message assert false should not be an error res is error assert false should not be a failure res is failure testassertionpath1 setxpathstring assertionresult getresult testlog iserror iserror isfailure isfailure testlog getfailuremessage assertfalse iserror assertfalse isfailure public void test assertion path2 throws exception assertion setx path string code 2 not present assertion result res assertion get result result test log debug is error res is error is failure res is failure test log debug failure message res get failure message assert false should not be an error res is error assert true should be a failure res is failure testassertionpath2 setxpathstring assertionresult getresult testlog iserror iserror isfailure isfailure testlog getfailuremessage assertfalse iserror asserttrue isfailure public void test assertion bool1 throws exception assertion setx path string count error 2 assertion result res assertion get result result test log debug is error res is error is failure res is failure test log debug failure message res get failure message assert false should not be an error res is error assert false should not be a failure res is failure testassertionbool1 setxpathstring assertionresult getresult testlog iserror iserror isfailure isfailure testlog getfailuremessage assertfalse iserror assertfalse isfailure public void test assertion bool2 throws exception assertion setx path string count code 1 1 assertion result res assertion get result result test log debug is error res is error is failure res is failure test log debug failure message res get failure message assert false should not be an error res is error assert false should not be a failure res is failure testassertionbool2 setxpathstring assertionresult getresult testlog iserror iserror isfailure isfailure testlog getfailuremessage assertfalse iserror assertfalse isfailure public void test assertion bool3 throws exception assertion setx path string count error 1 wrong assertion result res assertion get result result test log debug is error res is error is failure res is failure test log debug failure message res get failure message assert false should not be an error res is error assert true should be a failure res is failure testassertionbool3 setxpathstring assertionresult getresult testlog iserror iserror isfailure isfailure testlog getfailuremessage assertfalse iserror asserttrue isfailure public void test assertion bool4 throws exception assertion setx path string count code 2 1 wrong assertion result res assertion get result result test log debug is error res is error is failure res is failure test log debug failure message res get failure message assert false should not be an error res is error assert true should be a failure res is failure testassertionbool4 setxpathstring assertionresult getresult testlog iserror iserror isfailure isfailure testlog getfailuremessage assertfalse iserror asserttrue isfailure public void test assertion number throws exception assertion setx path string count error not yet handled assertion result res assertion get result result test log debug is error res is error is failure res is failure test log debug failure message res get failure message assert false should not be an error res is error assert true should be a failure res is failure testassertionnumber setxpathstring assertionresult getresult testlog iserror iserror isfailure isfailure testlog getfailuremessage assertfalse iserror asserttrue isfailure public void test assertion no result throws exception result set response data not set result new sample result assertion result res assertion get result result test log debug is error res is error is failure res is failure test log debug failure message res get failure message assert equals assertion result response was null res get failure message assert false should not be an error res is error assert true should be a failure res is failure testassertionnoresult setresponsedata sampleresult assertionresult getresult testlog iserror iserror isfailure isfailure testlog getfailuremessage assertequals assertionresult response_was_null getfailuremessage assertfalse iserror asserttrue isfailure public void test assertion empty result throws exception result set response data get bytes assertion result res assertion get result result test log debug is error res is error is failure res is failure test log debug failure message res get failure message assert equals assertion result response was null res get failure message assert false should not be an error res is error assert true should be a failure res is failure testassertionemptyresult setresponsedata getbytes assertionresult getresult testlog iserror iserror isfailure isfailure testlog getfailuremessage assertequals assertionresult response_was_null getfailuremessage assertfalse iserror asserttrue isfailure public void test assertion blank result throws exception result set response data get bytes assertion result res assertion get result result test log debug is error res is error is failure res is failure test log debug failure message res get failure message assert true res get failure message index of premature end of file 0 assert true should be an error res is error assert false should not be a failure res is failure testassertionblankresult setresponsedata getbytes assertionresult getresult testlog iserror iserror isfailure isfailure testlog getfailuremessage asserttrue getfailuremessage indexof asserttrue iserror assertfalse isfailure public void test no tolerance throws exception string data html head title testtitle title head body p i b invalid tag nesting i b hr body html result set response data data get bytes vars new j meter variables jmctx set variables vars jmctx set previous result result assertion setx path string html head title assertion set validating false assertion set tolerant false assertion result res assertion get result result log debug failure message res get failure message assert true res is error assert false res is failure testnotolerance setresponsedata getbytes jmetervariables setvariables setpreviousresult setxpathstring setvalidating settolerant assertionresult getresult failuremessage getfailuremessage asserttrue iserror assertfalse isfailure public void test assertion throws exception set alternate response data assertion setx path string row value field alias assertion result res assertion get result jmctx get previous result log debug res res is error log debug failure res get failure message assert false res is error assert false res is failure testassertion setalternateresponsedata setxpathstring assertionresult getresult getpreviousresult iserror getfailuremessage assertfalse iserror assertfalse isfailure public void test negate assertion throws exception set alternate response data assertion setx path string row value field noalias assertion set negated true assertion result res assertion get result jmctx get previous result log debug res res is error log debug failure res get failure message assert false res is error assert false res is failure testnegateassertion setalternateresponsedata setxpathstring setnegated assertionresult getresult getpreviousresult iserror getfailuremessage assertfalse iserror assertfalse isfailure public void test validation failure throws exception set alternate response data assertion setx path string row value field alias assertion set negated false assertion set validating true assertion result res assertion get result jmctx get previous result log debug res get failure message error res is error failure res is failure assert true res is error assert false res is failure testvalidationfailure setalternateresponsedata setxpathstring setnegated setvalidating assertionresult getresult getpreviousresult getfailuremessage iserror isfailure asserttrue iserror assertfalse isfailure public void test validation success throws exception string data xml version 1 0 doctype book element p pcdata element book opener subtitle introduction section part element opener title text element title text pcdata element subtitle pcdata element introduction header p element part header chapter element section header p element header pcdata element chapter chapter number chapter text element chapter number pcdata element chapter text p book opener title text all about me title text opener part header welcome to my book header chapter chapter number chapter 1 chapter number chapter text p glad you want to hear about me p p there s so much to say p p where should we start p p how about more about me p chapter text chapter part book result set response data data get bytes vars new j meter variables jmctx set variables vars jmctx set previous result result assertion setx path string assertion set validating true assertion result res assertion get result result assert false res is error assert false res is failure testvalidationsuccess title_text title_text chapter_number chapter_text chapter_number chapter_text title_text title_text chapter_number chapter_number chapter_text chapter_text setresponsedata getbytes jmetervariables setvariables setpreviousresult setxpathstring setvalidating assertionresult getresult assertfalse iserror assertfalse isfailure public void test validation failure withdtd throws exception string data xml version 1 0 doctype book element p pcdata element book opener subtitle introduction section part element opener title text element title text pcdata element subtitle pcdata element introduction header p element part header chapter element section header p element header pcdata element chapter chapter number chapter text element chapter number pcdata element chapter text p book opener title text all about me title text opener part header welcome to my book header chapter chapter number chapter 1 chapter number chapter text p glad you want to hear about me p p there s so much to say p p where should we start p p how about more about me p chapter text chapter illegal not defined in dtd illegal part book result set response data data get bytes vars new j meter variables jmctx set variables vars jmctx set previous result result assertion setx path string assertion set validating true assertion result res assertion get result result log debug failure message res get failure message assert true res is error assert false res is failure testvalidationfailurewithdtd title_text title_text chapter_number chapter_text chapter_number chapter_text title_text title_text chapter_number chapter_number chapter_text chapter_text setresponsedata getbytes jmetervariables setvariables setpreviousresult setxpathstring setvalidating assertionresult getresult failuremessage getfailuremessage asserttrue iserror assertfalse isfailure public void test tolerance throws exception string data html head title testtitle title head body p i b invalid tag nesting i b hr body html result set response data data get bytes vars new j meter variables jmctx set variables vars jmctx set previous result result assertion setx path string html head title assertion set validating true assertion set tolerant true assertion result res assertion get result result log debug failure message res get failure message assert false res is failure assert false res is error testtolerance setresponsedata getbytes jmetervariables setvariables setpreviousresult setxpathstring setvalidating settolerant assertionresult getresult failuremessage getfailuremessage assertfalse isfailure assertfalse iserror public class j meter cell renderer extends default tree cell renderer public j meter cell renderer jmetercellrenderer defaulttreecellrenderer jmetercellrenderer public component get tree cell renderer component j tree tree object value boolean sel boolean expanded boolean leaf int row boolean p hasfocus super get tree cell renderer component tree j meter tree node value get name sel expanded leaf row p hasfocus boolean enabled j meter tree node value is enabled image icon ic j meter tree node value get icon enabled if ic null if enabled set icon ic else set disabled icon ic else if enabled i e no disabled icon found must therefore set the enabled icon so there is at least some icon ic j meter tree node value get icon if ic null set icon ic this set enabled enabled return this gettreecellrenderercomponent jtree p_hasfocus gettreecellrenderercomponent jmetertreenode getname p_hasfocus jmetertreenode isenabled imageicon jmetertreenode geticon seticon setdisabledicon jmetertreenode geticon seticon setenabled default constructor public param mask set field name set prefix set lower bound 0 set upper bound 0 set increment 0 set suffix parammask setfieldname setprefix setlowerbound setupperbound setincrement setsuffix sets the prefix for the code long code value the prefix the value and the suffix are concatenated to give the parameter value this allows a wider range of posibilities for the parameter values param prefix a string to prefix to the parameter value public void set prefix string prefix set property prefix prefix setprefix setproperty set the current value of the code long code portion of the parameter value to replace this is usually not used as the method link reset value is used to define a policy for the starting value param val the new parameter value public void set value long val value val resetvalue setvalue _value public void set field name string field name set property field name field name setfieldname fieldname setproperty field_name fieldname sets the lowest possible value that the code long code portion of the parameter value may be param val the new lowest possible parameter value public void set lower bound long val set property new long property lower bound val setlowerbound setproperty longproperty lower_bound sets the highest possible value that the code long code portion of the parameter value may be param val the new highest possible parameter value public void set upper bound long val set property new long property upper bound val setupperbound setproperty longproperty upper_bound sets the number by which the parameter value is incremented between loops param incr the new increment for the parameter value public void set increment long incr set property new long property increment incr setincrement setproperty longproperty sets the suffix for the code long code value the prefix the value and the suffix are concatenated to give the parameter value this allows a wider range of posibilities for the parameter values param suffix a string to suffix to the parameter value public void set suffix string suffix set property suffix suffix setsuffix setproperty accessor method to return the code string code that will be prefixed to the code long code value return the parameter value prefix public string get prefix return get property as string prefix getprefix getpropertyasstring accessor method returns the lowest possible value that the code long code portion of the parameter value may be return the lower bound of the possible values public long get lower bound return get property as long lower bound getlowerbound getpropertyaslong lower_bound accessor method returns the highest possible value that the code long code portion of the parameter value may be return the higher bound of the possible values public long get upper bound return get property as long upper bound getupperbound getpropertyaslong upper_bound accessor method returns the number by which the parameter value is incremented between loops return the increment public long get increment return get property as long increment getincrement getpropertyaslong accessor method to return the code string code that will be suffixed to the code long code value return the parameter value suffix public string get suffix return get property as string suffix getsuffix getpropertyasstring returns the current value prefixed and suffixed as a string then increments it if the incremented value is above the upper bound the value is reset to the lower bound br p this method determines the policy of what happens when an upper bound is reached surpassed return a code string code representing the current code long code value public string get next value return the current value don t forget the prefix string retval get prefix long to string value get suffix increment the value value get increment if value get upper bound value get lower bound return retval getnextvalue getprefix tostring _value getsuffix _value getincrement _value getupperbound _value getlowerbound this method determines the policy of what value to start and re start at public void reset value value get lower bound resetvalue _value getlowerbound public string get field name return get property as string field name getfieldname getpropertyasstring field_name for debugging purposes return a code string code representing the object public string to string string buffer sb new string buffer sb append n sb append dumping param mask object n sb append n sb append name get field name n sb append prefix get prefix n sb append current value value n sb append lower bound get lower bound n sb append upper bound get upper bound n sb append increment get increment n sb append suffix get suffix n sb append n return sb to string tostring stringbuffer stringbuffer parammask getfieldname getprefix _value getlowerbound getupperbound getincrement getsuffix tostring create the ssl context and wrap all the x509 key managers with our x509 key manager so that we can choose our alias param provider description of parameter public jssessl manager provider provider log debug ssl provider provider set provider provider if null this rand surely this is always null in the constructor this rand new secure random try if shared session context log debug creating shared context this default context create context else this threadlocal new thread local set up java defaults n b does not allow slow socket fails with java lang runtime exception export restriction this jsse implementation is non pluggable httpsurl connection set defaultssl socket factory new httpssl protocol socket factory this httpsurl connection set default hostname verifier new hostname verifier public boolean verify string hostname ssl session session return true also set up http client defaults protocol protocol new protocol jssessl manager https protocol socket factory new httpssl protocol socket factory this cps 443 protocol register protocol jssessl manager https protocol log debug ssl stuff all set catch general security exception ex log error could not set up ssl context ex log debug jssessl manager installed sslcontext x509keymanagers x509keymanager jssesslmanager setprovider securerandom shared_session_context defaultcontext createcontext threadlocal slowsocket runtimeexception httpsurlconnection setdefaultsslsocketfactory httpsslprotocolsocketfactory httpsurlconnection setdefaulthostnameverifier hostnameverifier sslsession httpclient jssesslmanager protocolsocketfactory httpsslprotocolsocketfactory registerprotocol jssesslmanager generalsecurityexception sslcontext jssesslmanager httpsurl connection set defaultssl socket factory new httpssl protocol socket factory this httpsurl connection set default hostname verifier new hostname verifier public boolean verify string hostname ssl session session return true httpsurlconnection setdefaultsslsocketfactory httpsslprotocolsocketfactory httpsurlconnection setdefaulthostnameverifier hostnameverifier sslsession sets the context attribute of the jssessl manager object param conn the new context value public void set context httpurl connection conn if conn instanceof httpsurl connection no point doing this on a per connection basis as there is currently no way to configure it so we leave it to the defaults set up in the ssl context httpsurl connection secure conn httpsurl connection conn secure conn setssl socket factory this get context get socket factory else log warn unexpected httpurl connection class conn get class get name jssesslmanager setcontext httpurlconnection httpsurlconnection httpsurlconnection secureconn httpsurlconnection secureconn setsslsocketfactory getcontext getsocketfactory httpurlconnection getclass getname sets the provider attribute of the jssessl manager object param p the new provider value protected final void set provider provider p super set provider p if null this pro this pro p jssesslmanager setprovider setprovider returns the ssl context we are using this is either a context per thread or for backwards compatibility a single shared context return the context value public ssl context get context throws general security exception if shared session context if log is debug enabled log debug using shared ssl context for thread current thread get name return this default context ssl context ssl context ssl context this threadlocal get if ssl context null if log is debug enabled log debug creating thread local ssl context for thread current thread get name ssl context create context this threadlocal set ssl context if log is debug enabled log debug using thread local ssl context for thread current thread get name return ssl context sslcontext sslcontext getcontext generalsecurityexception shared_session_context isdebugenabled currentthread getname defaultcontext sslcontext sslcontext sslcontext sslcontext isdebugenabled threadlocal currentthread getname sslcontext createcontext sslcontext isdebugenabled threadlocal currentthread getname sslcontext resets the ssl context if using per thread contexts public void reset context if shared session context log debug clearing session context for current thread this threadlocal set null sslcontext resetcontext shared_session_context private ssl context create context throws general security exception ssl context context if pro null context ssl context get instance default ssl protocol pro non nls 1 else context ssl context get instance default ssl protocol non nls 1 key manager factory manager factory key manager factory get instance key manager factory get default algorithm jmeter key store keys this get key store manager factory init null defaultpw null new char defaultpw to char array key manager managers manager factory get key managers log debug keys get class to string now wrap the default managers with our key manager for int i 0 i managers length i if managers i instanceof x509 key manager x509 key manager manager x509 key manager managers i managers i new wrappedx509 key manager manager keys get the default trust managers trust manager factory tmfactory trust manager factory get instance trust manager factory get default algorithm tmfactory init this get trust store wrap the defaults in our custom trust manager trust manager trustmanagers tmfactory get trust managers for int i 0 i trustmanagers length i if trustmanagers i instanceof x509 trust manager trustmanagers i new customx509 trust manager x509 trust manager trustmanagers i context init managers trustmanagers this rand if log is debug enabled string d ciphers context get socket factory get default cipher suites string s ciphers context get socket factory get supported cipher suites int len d ciphers length s ciphers length d ciphers length s ciphers length for int i 0 i len i if i d ciphers length log debug default cipher d ciphers i if i s ciphers length log debug supported cipher s ciphers i return context sslcontext createcontext generalsecurityexception sslcontext sslcontext getinstance default_ssl_protocol sslcontext getinstance default_ssl_protocol keymanagerfactory managerfactory keymanagerfactory getinstance keymanagerfactory getdefaultalgorithm jmeterkeystore getkeystore managerfactory tochararray keymanager managerfactory getkeymanagers getclass tostring x509keymanager x509keymanager x509keymanager wrappedx509keymanager trustmanagerfactory trustmanagerfactory getinstance trustmanagerfactory getdefaultalgorithm gettruststore trustmanager gettrustmanagers x509trustmanager customx509trustmanager x509trustmanager isdebugenabled dciphers getsocketfactory getdefaultciphersuites sciphers getsocketfactory getsupportedciphersuites dciphers sciphers dciphers sciphers dciphers dciphers sciphers sciphers instantiate a new wrappedx509 key manager param parent the parent x509 key manager param ks the key store we derive our client certs and keys from public wrappedx509 key manager x509 key manager parent jmeter key store ks this manager parent this store ks wrappedx509keymanager x509keymanager keystore wrappedx509keymanager x509keymanager jmeterkeystore compiles the list of all client aliases with a private key currently key type and issuers are both ignored param key type the type of private key the server expects rsa dsa etc param issuers the ca certificates we are narrowing our selection on return the client aliases value public string get client aliases string key type principal issuers log debug wrappedx509 manager get client aliases log debug this store get alias return new string this store get alias keytype keytype clientaliases getclientaliases keytype wrappedx509manager getclientaliases getalias getalias get the list of server aliases for the ssl server sockets this is not used in j meter param key type the type of private key the server expects rsa dsa etc param issuers the ca certificates we are narrowing our selection on return the server aliases value public string get server aliases string key type principal issuers log debug wrappedx509 manager get server aliases return this manager get server aliases key type issuers sslserversockets jmeter keytype serveraliases getserveraliases keytype wrappedx509manager getserveraliases getserveraliases keytype get the certificate chain for a particular alias param alias the client alias return the certificate chain value public x509 certificate get certificate chain string alias log debug wrappedx509 manager get certificate chain alias return this store get certificate chain certificatechain x509certificate getcertificatechain wrappedx509manager getcertificatechain getcertificatechain get the private key for a particular alias param alias the client alias return the private key value public private key get private key string alias log debug wrappedx509 manager get private key this store get private key return this store get private key privatekey privatekey getprivatekey wrappedx509manager getprivatekey getprivatekey getprivatekey select the alias we will authenticate as if client authentication is required by the server we are connecting to we get the list of aliases and if there is only one alias we automatically select it if there are more than one alias that has a private key we prompt the user to choose which alias using a combo box otherwise we simply provide a text box which may or may not work the alias does have to match one in the keystore todo does not actually allow the user to choose an alias at present see javax net ssl x509 key manager choose client alias string principal socket public string choose client alias string key type principal issuers socket socket string alias this store get alias log debug client alias alias if alias null alias length 0 log debug client alias not found return alias x509keymanager chooseclientalias chooseclientalias keytype getalias clientalias clientalias choose the server alias for the ssl server sockets this are not used in j meter see javax net ssl x509 key manager choose server alias string principal socket public string choose server alias string arg0 principal arg1 socket arg2 return this manager choose server alias arg0 arg1 arg2 sslserversockets jmeter x509keymanager chooseserveralias chooseserveralias chooseserveralias public x path panel super init xpathpanel param is double buffered public x path panel boolean is double buffered super is double buffered init isdoublebuffered xpathpanel isdoublebuffered isdoublebuffered param layout public x path panel layout manager layout super layout init xpathpanel layoutmanager param layout param is double buffered public x path panel layout manager layout boolean is double buffered super layout is double buffered init isdoublebuffered xpathpanel layoutmanager isdoublebuffered isdoublebuffered private void init box hbox box create horizontal box hbox add box create horizontal glue hbox add getx path text field hbox add box create horizontal glue hbox add get checkx path button box vbox box create vertical box vbox add hbox vbox add box create vertical glue vbox add get negated check box add vbox set default values createhorizontalbox createhorizontalglue getxpathtextfield createhorizontalglue getcheckxpathbutton createverticalbox createverticalglue getnegatedcheckbox setdefaultvalues public void set default values setx path non nls 1 set negated false setdefaultvalues setxpath setnegated get the x path string return string public string getx path return this xpath get text xpath getxpath gettext set the string that will be used in the xpath evaluation param xpath public void setx path string xpath this xpath set text xpath setxpath settext does this negate the xpath results return boolean public boolean is negated return this negated is selected isnegated isselected set this to true if you want success when the xpath does not match param negated public void set negated boolean negated this negated set selected negated setnegated setselected negated chechbox return j check box public j check box get negated check box if negated null negated new j check box j meter utils get res string xpath assertion negate false non nls 1 return negated jcheckbox jcheckbox getnegatedcheckbox jcheckbox jmeterutils getresstring xpath_assertion_negate check x path button return j button public j button get checkx path button if checkx path null checkx path new j button j meter utils get res string xpath assertion button non nls 1 checkx path add action listener new action listener public void action performed action event e validx path xpath get text true return checkx path xpath jbutton jbutton getcheckxpathbutton checkxpath checkxpath jbutton jmeterutils getresstring xpath_assertion_button checkxpath addactionlistener actionlistener actionperformed actionevent validxpath gettext checkxpath checkx path new j button j meter utils get res string xpath assertion button non nls 1 checkx path add action listener new action listener public void action performed action event e validx path xpath get text true checkxpath jbutton jmeterutils getresstring xpath_assertion_button checkxpath addactionlistener actionlistener actionperformed actionevent validxpath gettext public j text field getx path text field if xpath null xpath new j text field 50 return xpath jtextfield getxpathtextfield jtextfield return returns the show negate public boolean is show negated return this get negated check box is visible shownegate isshownegated getnegatedcheckbox isvisible param show negate the show negate to set public void set show negated boolean show negate get negated check box set visible show negate shownegate shownegate setshownegated shownegate getnegatedcheckbox setvisible shownegate test weather an x path is valid it seems the xalan has no easy way to check so this creates a test document then tries to evaluate the xpath param xpath string x path string to validate param show dialog weather to show a dialog return returns true if valid valse otherwise public static boolean validx path string xpath string boolean show dialog string ret null boolean success true try if test doc null test doc x path util make document builder false false false new document element el test doc create element root non nls 1 test doc append child el if x pathapi eval test doc xpath string null we really should never get here because eval will throw an exception if xpath is invalid but whatever better safe log warn xpath eval was null ret xpath eval was null success false catch parser configuration exception e success false ret e get localized message catch transformer exception e success false ret e get localized message if show dialog j option pane show message dialog null success j meter utils get res string xpath assertion valid ret non nls 1 success j meter utils get res string xpath assertion valid j meter utils non nls 1 get res string xpath assertion failed success j option pane information message non nls 1 j option pane error message return success xpath xpathstring xpath showdialog validxpath xpathstring showdialog testdoc testdoc xpathutil makedocumentbuilder newdocument testdoc createelement testdoc appendchild xpathapi testdoc xpathstring parserconfigurationexception getlocalizedmessage transformerexception getlocalizedmessage showdialog joptionpane showmessagedialog jmeterutils getresstring xpath_assertion_valid jmeterutils getresstring xpath_assertion_valid jmeterutils getresstring xpath_assertion_failed joptionpane information_message joptionpane error_message private package test class test bean class locale locale resource bundle default bundle super test bean class get name locale get language locale get country this test bean class test bean class this test locale locale this default bundle default bundle packagetest testbeanclass resourcebundle defaultbundle testbeanclass getname getlanguage getcountry testbeanclass testbeanclass testlocale defaultbundle defaultbundle private package test string name super name this test bean class null this test locale null this default bundle null packagetest testbeanclass testlocale defaultbundle public void set up if test locale null return error detected j meter utils set locale test locale introspector flush from caches test bean class try bean info introspector get bean info test bean class bundle resource bundle bean info get bean descriptor get value generic test bean customizer resource bundle catch introspection exception e log error can t get bean info for test bean class get name e throw new error e to string programming error don t continue if bundle null throw new error this can t happen setup testlocale errordetected jmeterutils setlocale testlocale flushfromcaches testbeanclass beaninfo getbeaninfo testbeanclass resourcebundle beaninfo getbeandescriptor getvalue generictestbeancustomizer resource_bundle introspectionexception beaninfo testbeanclass getname tostring public void tear down j meter utils set locale locale get default teardown jmeterutils setlocale getdefault public void run test throws throwable if test locale null super run test return error detected if bundle default bundle check all necessary keys present else check no invented keys runtest testlocale runtest errordetected defaultbundle checkallnecessarykeyspresent checknoinventedkeys public void check no invented keys check that all keys in the bundle are also in the default bundle for enumeration keys bundle get keys keys has more elements string key string keys next element default bundle get string key will throw missing resource exception if key is not there checknoinventedkeys getkeys hasmoreelements nextelement defaultbundle getstring missingresourceexception public void check all necessary keys present check that all necessary keys are there display name is always mandatory string dn default bundle get string display name to upper case locale english skip the rest of this test for alpha experimental beans if dn index of alpha 1 dn index of experimental 1 return check for property and group related texts property descriptor descriptors bean info get property descriptors for int i 0 i descriptors length i skip non editable properties that is ignore hidden read only and write only properties if descriptors i is hidden descriptors i get read method null descriptors i get write method null continue ignore test element properties which don t have an explicit editor if test element class is assignable from descriptors i get property type descriptors i get property editor class null continue done we re working with an editable property string name descriptors i get name bundle get string name display name bundle get string name short description not mandatory string group string descriptors i get value generic test bean customizer group if group null bundle get string group display name checkallnecessarykeyspresent displayname defaultbundle getstring displayname touppercase indexof indexof propertydescriptor beaninfo getpropertydescriptors ishidden getreadmethod getwritemethod testelement testelement isassignablefrom getpropertytype getpropertyeditorclass getname getstring displayname getstring shortdescription getvalue generictestbeancustomizer getstring displayname public static test suite throws exception test suite suite new test suite bean resource test suite iterator iter class finder find classes that extend j meter utils get search paths new class test bean class iterator boolean error detected false j meter utils set locale default locale while iter has next string class name string iter next class test bean class class for name class name resource bundle default bundle null try default bundle resource bundle introspector get bean info test bean class get bean descriptor get value generic test bean customizer resource bundle catch introspection exception e log error can t get bean info for test bean class get name e throw new error e to string programming error don t continue if default bundle null if class name starts with org apache jmeter examples log info no default bundle found for class name continue error detected true log error no default bundle found for class name using default locale to string throw new error no default bundle for class class name continue suite add test new package test test bean class default locale default bundle string languages j meter menu bar get languages for int i 0 i languages length i final string language languages i split if language length 1 suite add test new package test test bean class new locale language 0 default bundle else if language length 2 suite add test new package test test bean class new locale language 0 language 1 default bundle if error detected suite add test new package test error detected return suite testsuite testsuite classfinder findclassesthatextend jmeterutils getsearchpaths testbean errordetected jmeterutils setlocale defaultlocale hasnext classname testbeanclass forname classname resourcebundle defaultbundle defaultbundle resourcebundle getbeaninfo testbeanclass getbeandescriptor getvalue generictestbeancustomizer resource_bundle introspectionexception beaninfo testbeanclass getname tostring defaultbundle classname startswith classname errordetected classname defaultlocale tostring classname addtest packagetest testbeanclass defaultlocale defaultbundle jmetermenubar getlanguages _ addtest packagetest testbeanclass defaultbundle addtest packagetest testbeanclass defaultbundle errordetected addtest packagetest errordetected public void error detected fail one or more errors detected see log file errordetected no arg constructor public constant timer constanttimer set the delay for this timer public void set delay string delay set property delay delay setdelay setproperty set the range not used for this timer public void set range double range setrange get the delay value for display return the delay value for display public string get delay return get property as string delay getdelay getpropertyasstring retrieve the range not used for this timer return the range always zero for this timer public double get range return 0 getrange retrieve the delay to use during test execution return the delay public long delay return delay provide a description of this timer class return the description of this timer class public string to string return j meter utils get res string constant timer memo non nls 1 tostring jmeterutils getresstring constant_timer_memo gain access to any variables that have been defined see loop iteration listener iteration start loop iteration event public void iteration start loop iteration event event delay get property as long delay loopiterationlistener iterationstart loopiterationevent iterationstart loopiterationevent getpropertyaslong public class tidy exception extends exception public tidy exception this 0 0 tidyexception tidyexception public tidy exception int errors int warnings super tidy errors errors warnings warnings tidyexception no arg constructor see java lang object object public include controller super includecontroller public object clone todo fix so that this is only called once per test instead of at every clone perhaps save previous filename and only load if it has changed this resolve replacement sub tree null include controller clone include controller super clone clone set include path this get include path if this subtree null if this subtree key set size 1 iterator itr this subtree key set iterator while itr has next this sub test element itr next clone subtree hash tree this subtree clone clone sub test element this sub clone return clone resolvereplacementsubtree includecontroller includecontroller setincludepath getincludepath keyset keyset hasnext testelement hashtree testelement in the event an user wants to include an external jmx test plan the gui would call this param jmxfile public void set include path string jmxfile this set property include path jmxfile setincludepath setproperty include_path return the jmx file path return the jmx file path public string get include path return this get property as string include path getincludepath getpropertyasstring include_path the way replaceable controller works is clone is called first followed by replace hash tree and finally get replacement public hash tree get replacement sub tree return subtree replaceablecontroller hashtree getreplacement hashtree getreplacementsubtree public void resolve replacement sub tree j meter tree node context this subtree this load included elements resolvereplacementsubtree jmetertreenode loadincludedelements load the included elements using save service protected hash tree load included elements only try to load the jmx test plan if there is one final string include path get include path input stream reader null hash tree tree null if include path null include path length 0 try string file prefix include path log info load included elements try to load included module file reader new file input stream file tree save service load tree reader remove disabled items tree return tree catch no class def found error ex allow for missing optional jars string msg ex get message if msg null msg missing jar file see log for details log warn missing jar file ex j meter utils report error to user msg catch file not found exception ex string msg ex get message j meter utils report error to user msg log warn msg catch exception ex string msg ex get message if msg null msg unexpected error see log for details j meter utils report error to user msg log warn unexpected error ex finally j orphan utils close quietly reader return tree saveservice hashtree loadincludedelements includepath getincludepath inputstream hashtree includepath includepath includepath loadincludedelements fileinputstream saveservice loadtree removedisableditems noclassdeffounderror getmessage jmeterutils reporterrortouser filenotfoundexception getmessage jmeterutils reporterrortouser getmessage jmeterutils reporterrortouser jorphanutils closequietly private void remove disabled items hash tree tree iterator iter new linked list tree list iterator while iter has next test element item test element iter next if item is enabled log info removing item to string tree remove item else log info keeping item to string remove disabled items tree get tree item recursive call removedisableditems hashtree linkedlist hasnext testelement testelement isenabled tostring tostring removedisableditems gettree test plan variables public test value replacer string name super name testplan testvaluereplacer public void set up variables new test plan variables add parameter server jakarta apache org variables add parameter username jack the following used to be jacks password but the arguments class uses hash map for which the order is not defined variables add parameter password his password variables add parameter regex j meter variables vars new j meter variables vars put server jakarta apache org j meter context service get context set variables vars j meter context service get context set sampling started true setup testplan addparameter addparameter jacks_password hashmap addparameter his_password addparameter jmetervariables jmetervariables jmetercontextservice getcontext setvariables jmetercontextservice getcontext setsamplingstarted public void test reverse replacement throws exception value replacer replacer new value replacer variables assert true variables get user defined variables contains key server assert true replacer contains key server test element element new test plan element set property new string property domain jakarta apache org list args new array list args add username is jack args add his password element set property new collection property args args replacer reverse replace element assert equals server element get property as string domain args list element get property args get object value assert equals username is username j meter property args get 0 get string value assert equals password j meter property args get 1 get string value testreversereplacement valuereplacer valuereplacer asserttrue getuserdefinedvariables containskey asserttrue containskey testelement testplan setproperty stringproperty arraylist his_password setproperty collectionproperty reversereplace assertequals getpropertyasstring getproperty getobjectvalue assertequals jmeterproperty getstringvalue assertequals jmeterproperty getstringvalue public void test replace throws exception value replacer replacer new value replacer replacer set user defined variables variables get user defined variables test element element new config test element element set property new string property domain server replacer replace values element log debug domain property element get property domain element set running version true assert equals jakarta apache org element get property as string domain testreplace valuereplacer valuereplacer setuserdefinedvariables getuserdefinedvariables testelement configtestelement setproperty stringproperty replacevalues getproperty setrunningversion assertequals getpropertyasstring see junit framework test case tear down protected void tear down throws exception j meter context service get context set sampling started false testcase teardown teardown jmetercontextservice getcontext setsamplingstarted prepare the bean for work by populating the bean s properties from the property value map p deprecated to limit it s usage in expectation of moving it elsewhere public static void prepare test element el if el instanceof test bean return try bean info bean info introspector get bean info el get class property descriptor desc bean info get property descriptors object param new object 1 if log is debug enabled log debug preparing el get class for int x 0 x desc length x obtain a value of the appropriate type for this property j meter property jprop el get property desc x get name class type desc x get property type object value converter convert jprop get string value type if log is debug enabled log debug setting jprop get name value set the bean s property to the value we just obtained if value null type is primitive we can t assign null to primitive types param 0 value method write method desc x get write method if write method null invoke or bail out el write method param catch introspection exception e log error couldn t set properties for el get class get name e testelement testbean beaninfo beaninfo getbeaninfo getclass propertydescriptor beaninfo getpropertydescriptors isdebugenabled getclass jmeterproperty getproperty getname getpropertytype getstringvalue isdebugenabled getname isprimitive writemethod getwritemethod writemethod invokeorbailout writemethod introspectionexception getclass getname utility method that invokes a method and does the error handling around the invocation param method param params return the result of the method invocation private static object invoke or bail out object invokee method method object params try return method invoke invokee params catch illegal argument exception e log error this should never happen e throw new error e to string programming error bail out catch illegal access exception e log error this should never happen e throw new error e to string programming error bail out catch invocation target exception e log error this should never happen e throw new error e to string programming error bail out invokeorbailout illegalargumentexception tostring illegalaccessexception tostring invocationtargetexception tostring only for unit tests public sample event this null null sampleevent creates sample event without saving any variables use by proxy and statistical sample sender param result sample result param thread group name public sample event sample result result string thread group this result result this thread group thread group this hostname hostname values new string variable names length sampleevent statisticalsamplesender sampleresult threadgroup sampleevent sampleresult threadgroup threadgroup threadgroup variablenames contructor used for normal samples saves variable values if any are defined param result param thread group name param jmvars jmeter variables public sample event sample result result string thread group j meter variables jmvars this result result this thread group thread group this hostname hostname values new string variable names length save vars jmvars threadgroup sampleevent sampleresult threadgroup jmetervariables threadgroup threadgroup variablenames savevars only intended for use when loading results from a file param result param thread group param hostname public sample event sample result result string thread group string hostname this result result this thread group thread group this hostname hostname values new string variable names length threadgroup sampleevent sampleresult threadgroup threadgroup threadgroup variablenames private void save vars j meter variables vars for int i 0 i variable names length i values i vars get variable names i savevars jmetervariables variablenames variablenames return the number of variables defined public static int get var count return var count getvarcount varcount get the nth variable name zero based public static string get var name int i return variable names i getvarname variablenames get the nth variable value zero based public string get var value int i return values i getvarvalue public sample result get result return result sampleresult getresult public string get thread group return thread group getthreadgroup threadgroup public string get hostname return hostname gethostname code public http sampler base set arguments new arguments httpsamplerbase setarguments the name parameter to be applied to the file deprecated use sethttp files instead public void set file field string value file list null force rebuild set file field property value sethttpfiles setfilefield filelist setfilefieldproperty private void set file field property string value if value null throw new illegal argument exception value must not be null set property file field value setfilefieldproperty illegalargumentexception setproperty file_field the name parameter to be applied to the file deprecated use gethttp files array instead public string get file field check count get file field return get property as string file field gethttpfiles getfilefield checkcount getfilefield getpropertyasstring file_field the actual name of the file to post deprecated use sethttp files instead public void set filename string value file list null force rebuild set filename property value sethttpfiles setfilename filelist setfilenameproperty private void set filename property string value if value null throw new illegal argument exception value must not be null set property file name value setfilenameproperty illegalargumentexception setproperty file_name the actual name of the file to post deprecated use gethttp files array instead public string get filename check count get filename return get property as string file name gethttpfiles getfilename checkcount getfilename getpropertyasstring file_name set the files mime type deprecated use sethttp files instead param value public void set mimetype string value file list null force rebuild set mimetype property value sethttpfiles setmimetype filelist setmimetypeproperty private void set mimetype property string value if value null throw new illegal argument exception value must not be null set property mimetype value setmimetypeproperty illegalargumentexception setproperty deprecated use gethttp files array instead public string get mimetype check count get mimetype return get property as string mimetype gethttpfiles getmimetype checkcount getmimetype getpropertyasstring private void check count string method if gethttp file count 1 log warn method called with more than 1 file additional files may be ignored checkcount gethttpfilecount determine if the file should be sent as the entire post body i e without any additional wrapping return true if specified file is to be sent as the body i e file field is blank public boolean get send file as post body if there is one file with no parameter name the file will be sent as post body http file arg files gethttp files return files length 1 files 0 get path length 0 files 0 get param name length 0 filefield getsendfileaspostbody httpfilearg gethttpfiles getpath getparamname determine if none of the parameters have a name and if that is the case it means that the parameter values should be sent as the post body return true if none of the parameters have a name specified public boolean get send parameter values as post body boolean no arguments has name true property iterator args get arguments iterator while args has next http argument arg http argument args next get object value if arg get name null arg get name length 0 no arguments has name false break return no arguments has name getsendparametervaluesaspostbody noargumentshasname propertyiterator getarguments hasnext httpargument httpargument getobjectvalue getname getname noargumentshasname noargumentshasname determine if we should use multipart form data or application x www form urlencoded for the post return true if multipart form data should be used and method is post public boolean get use multipart for post we use multipart if we have been told so or files are present and the files should not be send as the post body http file arg files gethttp files if post equals get method get do multipart post files length 0 get send file as post body return true return false getusemultipartforpost httpfilearg gethttpfiles getmethod getdomultipartpost getsendfileaspostbody public void set protocol string value set property protocol value to lower case java util locale english setprotocol setproperty tolowercase gets the protocol with default return the protocol public string get protocol string protocol get property as string protocol if protocol null protocol length 0 return default protocol return protocol getprotocol getpropertyasstring default_protocol not used public string get client return get property as string client getclient getpropertyasstring not used public void set client string client set property client client setclient setproperty sets the path attribute of the url config object also calls parse arguments to extract and store any query arguments param path the new path value public void set path string path we know that url arguments should always be encoded in utf 8 according to spec set path path encoder cache url argument encoding urlconfig parsearguments setpath setpath encodercache url_argument_encoding sets the path attribute of the url config object also calls parse arguments to extract and store any query arguments param path the new path value param content encoding the encoding used for the querystring parameter values public void set path string path string content encoding if get equals get method delete equals get method int index path index of qry pfx if index 1 set property path path substring 0 index parse the arguments in querystring assuming specified encoding for values parse arguments path substring index 1 content encoding else set property path path else set property path path urlconfig parsearguments contentencoding setpath contentencoding getmethod getmethod indexof qry_pfx setproperty parsearguments contentencoding setproperty setproperty public string get path string p get property as string path if dynamic path return encode spaces p return p getpath getpropertyasstring dynamicpath encodespaces public void set follow redirects boolean value set property new boolean property follow redirects value setfollowredirects setproperty booleanproperty follow_redirects public boolean get follow redirects return get property as boolean follow redirects getfollowredirects getpropertyasboolean follow_redirects public void set auto redirects boolean value set property new boolean property auto redirects value setautoredirects setproperty booleanproperty auto_redirects public boolean get auto redirects return get property as boolean auto redirects getautoredirects getpropertyasboolean auto_redirects public void set method string value set property method value setmethod setproperty public string get method return get property as string method getmethod getpropertyasstring public void set content encoding string value set property content encoding value setcontentencoding setproperty content_encoding public string get content encoding return get property as string content encoding getcontentencoding getpropertyasstring content_encoding public void set use keep alive boolean value set property new boolean property use keepalive value setusekeepalive setproperty booleanproperty use_keepalive public boolean get use keep alive return get property as boolean use keepalive getusekeepalive getpropertyasboolean use_keepalive public void set do multipart post boolean value set property new boolean property do multipart post value setdomultipartpost setproperty booleanproperty do_multipart_post public boolean get do multipart post return get property as boolean do multipart post false getdomultipartpost getpropertyasboolean do_multipart_post public void set monitor string value this set property monitor value setmonitor setproperty public void set monitor boolean truth this set property monitor truth setmonitor setproperty public string get monitor return this get property as string monitor getmonitor getpropertyasstring public boolean is monitor return this get property as boolean monitor ismonitor getpropertyasboolean public void set implementation string value this set property implementation value setimplementation setproperty public string get implementation return this get property as string implementation getimplementation getpropertyasstring public boolean usemd5 return this get property as boolean md5 false getpropertyasboolean public void setmd5 boolean truth this set property md5 truth false setproperty add an argument which has already been encoded public void add encoded argument string name string value this add encoded argument name value arg val sep addencodedargument addencodedargument arg_val_sep public void add encoded argument string name string value string meta data string content encoding if log is debug enabled log debug adding argument name name value value meta data meta data content encoding content encoding http argument arg null if content encoding null arg new http argument name value meta data true content encoding else arg new http argument name value meta data true check if there are any difference between name and value and their encoded name and value string value encoded null if content encoding null try value encoded arg get encoded value content encoding catch unsupported encoding exception e log warn unable to get encoded value using encoding content encoding value encoded arg get encoded value else value encoded arg get encoded value if there is no difference we mark it as not needing encoding if arg get name equals arg get encoded name arg get value equals value encoded arg set always encoded false this get arguments add argument arg addencodedargument metadata contentencoding isdebugenabled metadata metadata contentencoding contentencoding httpargument contentencoding httpargument metadata contentencoding httpargument metadata valueencoded contentencoding valueencoded getencodedvalue contentencoding unsupportedencodingexception contentencoding valueencoded getencodedvalue valueencoded getencodedvalue getname getencodedname getvalue valueencoded setalwaysencoded getarguments addargument public void add encoded argument string name string value string meta data this add encoded argument name value meta data null addencodedargument metadata addencodedargument metadata public void add non encoded argument string name string value string metadata http argument arg new http argument name value metadata false arg set always encoded false this get arguments add argument arg addnonencodedargument httpargument httpargument setalwaysencoded getarguments addargument public void add argument string name string value this get arguments add argument new http argument name value addargument getarguments addargument httpargument public void add argument string name string value string metadata this get arguments add argument new http argument name value metadata addargument getarguments addargument httpargument public boolean has arguments return get arguments get argument count 0 hasarguments getarguments getargumentcount public void add test element test element el if el instanceof cookie manager set cookie manager cookie manager el else if el instanceof cache manager set cache manager cache manager el else if el instanceof header manager set header manager header manager el else if el instanceof auth manager set auth manager auth manager el else super add test element el addtestelement testelement cookiemanager setcookiemanager cookiemanager cachemanager setcachemanager cachemanager headermanager setheadermanager headermanager authmanager setauthmanager authmanager addtestelement public void set port int value set property new integer property port value setport setproperty integerproperty get the port number for a url applying defaults if necessary called by cookie manager param protocol from link url get protocol param port number from link url get port return the default port for the protocol public static int get default port string protocol int port if port url unspecified port return protocol equals ignore case protocol http default http port protocol equals ignore case protocol https default https port port return port cookiemanager getprotocol getport getdefaultport url_unspecified_port equalsignorecase protocol_http default_http_port equalsignorecase protocol_https default_https_port get the port number from the port string allowing for trailing blanks return port number or unspecified port 0 public int get port if specified string port s get property as string port unspecified port as string try return integer parse int port s trim catch number format exception e return unspecified port unspecified_port getportifspecified port_s getpropertyasstring unspecified_port_as_string parseint port_s numberformatexception unspecified_port tell whether the default port for the specified protocol is used return true if the default port number for the protocol is used false otherwise public boolean is protocol default port final int port get port if specified final string protocol get protocol if port unspecified port protocol http equals ignore case protocol port default http port protocol https equals ignore case protocol port default https port return true return false isprotocoldefaultport getportifspecified getprotocol unspecified_port protocol_http equalsignorecase default_http_port protocol_https equalsignorecase default_https_port get the port apply the default for the protocol if necessary return the port number with default applied if required public int get port final int port get port if specified if port unspecified port string prot get protocol if protocol https equals ignore case prot return default https port if protocol http equals ignore case prot log warn unexpected protocol prot todo should this return something else return default http port return port getport getportifspecified unspecified_port getprotocol protocol_https equalsignorecase default_https_port protocol_http equalsignorecase default_http_port public void set domain string value set property domain value setdomain setproperty public string get domain return get property as string domain getdomain getpropertyasstring public void set connect timeout string value set property connect timeout value setconnecttimeout setproperty connect_timeout public int get connect timeout return get property as int connect timeout 0 getconnecttimeout getpropertyasint connect_timeout public void set response timeout string value set property response timeout value setresponsetimeout setproperty response_timeout public int get response timeout return get property as int response timeout 0 getresponsetimeout getpropertyasint response_timeout public void set arguments arguments value set property new test element property arguments value setarguments setproperty testelementproperty public arguments get arguments return arguments get property arguments get object value getarguments getproperty getobjectvalue public void set auth manager auth manager value auth manager mgr get auth manager if mgr null log warn existing auth manager mgr get name superseded by value get name set property new test element property auth manager value setauthmanager authmanager authmanager getauthmanager authmanager getname getname setproperty testelementproperty auth_manager public auth manager get auth manager return auth manager get property auth manager get object value authmanager getauthmanager authmanager getproperty auth_manager getobjectvalue public void set header manager header manager value header manager mgr get header manager if mgr null log warn existing header manager mgr get name merged with value get name value mgr merge value true if log is debug enabled log debug header manager merged value get name for int i 0 i value get headers size i log debug value get header i get name value get header i get value set property new test element property header manager value setheadermanager headermanager headermanager getheadermanager headermanager getname getname isdebugenabled headermanager getname getheaders getheader getname getheader getvalue setproperty testelementproperty header_manager public header manager get header manager return header manager get property header manager get object value headermanager getheadermanager headermanager getproperty header_manager getobjectvalue public void set cookie manager cookie manager value cookie manager mgr get cookie manager if mgr null log warn existing cookie manager mgr get name superseded by value get name set property new test element property cookie manager value setcookiemanager cookiemanager cookiemanager getcookiemanager cookiemanager getname getname setproperty testelementproperty cookie_manager public cookie manager get cookie manager return cookie manager get property cookie manager get object value cookiemanager getcookiemanager cookiemanager getproperty cookie_manager getobjectvalue public void set cache manager cache manager value cache manager mgr get cache manager if mgr null log warn existing cache manager mgr get name superseded by value get name set property new test element property cache manager value setcachemanager cachemanager cachemanager getcachemanager cachemanager getname getname setproperty testelementproperty cache_manager public cache manager get cache manager return cache manager get property cache manager get object value cachemanager getcachemanager cachemanager getproperty cache_manager getobjectvalue public boolean is image parser return get property as boolean image parser isimageparser getpropertyasboolean image_parser public void set image parser boolean parse images set property new boolean property image parser parse images setimageparser parseimages setproperty booleanproperty image_parser parseimages get the regular expression ur ls must match return regular expression or empty string public string get embedded urlre return get property as string embedded url re urls getembeddedurlre getpropertyasstring embedded_url_re public void set embedded urlre string regex set property new string property embedded url re regex setembeddedurlre setproperty stringproperty embedded_url_re obtain a result that will help inform the user that an error has occured during sampling and how long it took to detect the error param e exception representing the error param res sample result return a sampling result useful to inform the user about the exception protected http sample result error result throwable e http sample result res res set sample label error res set data type http sample result text byte array output stream text new byte array output stream 200 e print stack trace new print stream text res set response data text to byte array res set response code non http response code e get class get name res set response message non http response message e get message res set successful false res set monitor this is monitor return res sampleresult httpsampleresult errorresult httpsampleresult setsamplelabel setdatatype httpsampleresult bytearrayoutputstream bytearrayoutputstream printstacktrace printstream setresponsedata tobytearray setresponsecode non_http_response_code getclass getname setresponsemessage non_http_response_message getmessage setsuccessful setmonitor ismonitor get the url built from its component parts p as a special case if the path starts with http s then the path is assumed to be the entire url p return the url to be requested by this sampler throws malformedurl exception public url get url throws malformedurl exception string buffer path and query new string buffer 100 string path this get path hack to allow entire url to be provided in host field if path starts with http prefix path starts with https prefix return new url path if path starts with non nls 1 path and query append non nls 1 path and query append path add the query string if it is a http get or delete request if get equals get method delete equals get method get the query string encoded in specified encoding if no encoding is specified by user we will get it encoded in utf 8 which is what the http spec says string query string get query string get content encoding if query string length 0 if path index of qry pfx 1 already contains a prefix path and query append qry sep else path and query append qry pfx path and query append query string if default port for protocol is used we do not include port in url if is protocol default port return new url get protocol get domain path and query to string return new url get protocol get domain get port path and query to string malformedurlexception geturl malformedurlexception stringbuffer pathandquery stringbuffer getpath startswith http_prefix startswith https_prefix startswith pathandquery pathandquery getmethod getmethod querystring getquerystring getcontentencoding querystring indexof qry_pfx pathandquery qry_sep pathandquery qry_pfx pathandquery querystring isprotocoldefaultport getprotocol getdomain pathandquery tostring getprotocol getdomain getport pathandquery tostring gets the query string attribute of the url config object using utf 8 to encode the url return the query string value public string get query string we use the encoding which should be used according to the http spec which is utf 8 return get query string encoder cache url argument encoding querystring urlconfig querystring getquerystring getquerystring encodercache url_argument_encoding gets the query string attribute of the url config object using the specified encoding to encode the parameter values put into the url param content encoding the encoding to use for encoding parameter values return the query string value public string get query string string content encoding check if the sampler has a specified content encoding if content encoding null content encoding trim length 0 we use the encoding which should be used according to the http spec which is utf 8 content encoding encoder cache url argument encoding string buffer buf new string buffer property iterator iter get arguments iterator boolean first true while iter has next http argument item null n b revision 323346 introduced the class cast check but then used iter next to fetch the item to be cast thus skipping the element that did not cast reverted to work more like the original code but with the check in place added a warning message so can track whether it is necessary object object value iter next get object value try item http argument object value catch class cast exception e log warn unexpected argument type object value get class get name item new http argument argument object value final string encoded name item get encoded name if encoded name length 0 continue skip parameters with a blank name allows use of optional variables in parameter lists if first buf append qry sep else first false buf append encoded name if item get meta data null buf append arg val sep else buf append item get meta data encode the parameter value in the specified content encoding try buf append item get encoded value content encoding catch unsupported encoding exception e log warn unable to encode parameter in encoding content encoding parameter value not included in query string return buf to string querystring urlconfig contentencoding querystring getquerystring contentencoding contentencoding contentencoding contentencoding encodercache url_argument_encoding stringbuffer stringbuffer propertyiterator getarguments hasnext httpargument classcast objectvalue getobjectvalue httpargument objectvalue classcastexception objectvalue getclass getname httpargument objectvalue encodedname getencodedname encodedname qry_sep encodedname getmetadata arg_val_sep getmetadata getencodedvalue contentencoding unsupportedencodingexception contentencoding tostring string where string contains only the parameter name and no equal sign this method allows a proxy server to send over the raw text from a browser s output stream to be parsed and stored correctly into the url config object for each name found add argument is called param query string the query string param content encoding the content encoding of the query string the query string might actually be the post body of a http post request public void parse arguments string query string string content encoding string args j orphan utils split query string qry sep for int i 0 i args length i need to handle four cases string contains name value string contains name string contains name empty string string meta data records the existance of an equal sign string name string value int length args i length int end of name index args i index of arg val sep if end of name index 1 is there a separator case of name value name meta data arg val sep name args i substring 0 end of name index value args i substring end of name index 1 length else meta data name args i value if name length 0 if we know the encoding we can decode the argument value to make it easier to read for the user if content encoding null add encoded argument name value meta data content encoding else if we do not know the encoding we just use the encoded value the browser has already done the encoding so save the values as is add non encoded argument name value meta data urlconfig addargument querystring contentencoding parsearguments querystring contentencoding jorphanutils querystring qry_sep metadata endofnameindex indexof arg_val_sep endofnameindex metadata arg_val_sep endofnameindex endofnameindex metadata contentencoding addencodedargument metadata contentencoding addnonencodedargument metadata public void parse arguments string query string we do not know the content encoding of the query string parse arguments query string null parsearguments querystring parsearguments querystring public string to string try string buffer string buffer new string buffer string buffer append this get url to string append body if it is a post or put if post equals get method put equals get method string buffer append n query data string buffer append get query string return string buffer to string catch malformedurl exception e return tostring stringbuffer stringbuffer stringbuffer stringbuffer geturl tostring getmethod getmethod stringbuffer nquery stringbuffer getquerystring stringbuffer tostring malformedurlexception do a sampling and return its results param e code entry code to be sampled return results of the sampling public sample result sample entry e return sample sampleresult perform a sample and return the results return results of the sampling public sample result sample sample result res null try if protocol file equals ignore case get protocol res file sample new uri protocol file get path null else res sample get url get method false 0 res set sample label get name return res catch malformedurl exception e return error result e new http sample result catch io exception e return error result e new http sample result catch uri syntax exception e return error result e new http sample result sampleresult sampleresult protocol_file equalsignorecase getprotocol filesample protocol_file getpath geturl getmethod setsamplelabel getname malformedurlexception errorresult httpsampleresult ioexception errorresult httpsampleresult urisyntaxexception errorresult httpsampleresult private http sample result file sample uri uri throws io exception string url str uri to string http sample result res new http sample result res set monitor is monitor res sethttp method get dummy res seturl uri tourl res set sample label uri to string file input stream fis null res sample start try byte response data string buffer ctb new string buffer text html non nls 1 fis new file input stream get path string content encoding get content encoding if content encoding length 0 ctb append charset non nls 1 ctb append content encoding response data io utils to byte array fis res sample end res set response data response data res set response codeok res set response messageok res set successful true string ct ctb to string res set content type ct res set encoding and type ct finally io utils close quietly fis res set response headers return res httpsampleresult filesample ioexception urlstr tostring httpsampleresult httpsampleresult setmonitor ismonitor sethttpmethod setsamplelabel tostring fileinputstream samplestart responsedata stringbuffer stringbuffer fileinputstream getpath contentencoding getcontentencoding contentencoding contentencoding responsedata ioutils tobytearray sampleend setresponsedata responsedata setresponsecodeok setresponsemessageok setsuccessful tostring setcontenttype setencodingandtype ioutils closequietly setresponseheaders samples the url passed in and stores the result in code http sample result code following redirects and downloading page resources as appropriate p when getting a redirect target redirects are not followed and resources are not downloaded the caller will take care of this param u url to sample param method http method get post param are following redirect whether we re getting a redirect target param depth depth of this target in the frame structure used only to prevent infinite recursion return results of the sampling protected abstract http sample result sample url u httpsampleresult arefollowingredirect httpsampleresult download the resources of an html page p if create container result is true the returned result will contain one subsample for each request issued including the original one that was passed in it will otherwise look exactly like that original one p if create container result is false one subsample will be added to the provided result for each requests issued param res result of the initial request must contain an html response param container for storing the results param frame depth depth of this target in the frame structure used only to prevent infinite recursion return container result with one subsample per request issued protected http sample result download page resources http sample result res http sample result container int frame depth iterator urls null try final byte response data res get response data if response data length 0 bug 39205 string parser name get parser class res if parser name null final html parser parser parser name length 0 we have a name html parser get parser parser name html parser get parser we don t use the default parser urls parser get embedded resourceur ls response data res geturl catch html parse exception e don t break the world just because this failed res add sub result error result e res res set successful false iterate through the ur ls and download each image if urls null urls has next if container null res new http sample result res else res container get the url matcher string re get embedded urlre perl5 matcher local matcher null pattern pattern null if re length 0 try pattern j meter utils get pattern re local matcher j meter utils get matcher don t fetch unless pattern compiles catch malformed cache pattern exception e log warn ignoring embedded url match string e get message while urls has next object binurl urls next try url url url binurl if url null log warn null url detected should not happen else string urlstr url to string string url str enc encode spaces urlstr if urlstr equals url str enc there were some spaces in the url try url new url url str enc catch malformedurl exception e res add sub result error result new exception url str enc is not a correct uri res res set successful false continue i don t think local matcher can be null here but check just in case if pattern null local matcher null local matcher matches url str enc pattern continue we have a pattern and the url does not match so skip it http sample result bin res sample url get false frame depth 1 res add sub result bin res res set successful res is successful bin res is successful catch class cast exception e res add sub result error result new exception binurl is not a correct uri res res set successful false continue return res createcontainerresult createcontainerresult framedepth httpsampleresult downloadpageresources httpsampleresult httpsampleresult framedepth responsedata getresponsedata responsedata parsername getparserclass parsername htmlparser parsername htmlparser getparser parsername htmlparser getparser getembeddedresourceurls responsedata htmlparseexception addsubresult errorresult setsuccessful urls hasnext httpsampleresult getembeddedurlre perl5matcher localmatcher jmeterutils getpattern localmatcher jmeterutils getmatcher malformedcachepatternexception getmessage hasnext tostring urlstrenc encodespaces urlstrenc urlstrenc malformedurlexception addsubresult errorresult urlstrenc setsuccessful localmatcher localmatcher localmatcher urlstrenc httpsampleresult binres framedepth addsubresult binres setsuccessful issuccessful binres issuccessful classcastexception addsubresult errorresult setsuccessful return parser class name may be or null if entry does not exist private string get parser class http sample result res final string ct res get media type return string parsers for type get ct getparserclass httpsampleresult getmediatype parsersfortype todo make static protected string encode spaces string path return j orphan utils replace all chars path 20 non nls 1 encodespaces jorphanutils replaceallchars see org apache jmeter testelement test listener test ended public void test ended dynamic path false testlistener testended testended dynamicpath see org apache jmeter testelement test listener test ended java lang string public void test ended string host test ended testlistener testended testended testended see org apache jmeter testelement test listener test iteration start org apache jmeter engine event loop iteration event public void test iteration start loop iteration event event testlistener testiterationstart loopiterationevent testiterationstart loopiterationevent public void test started j meter property pathp get property path log debug path property is a pathp get class get name log debug path beginning value pathp get string value if pathp instanceof string property pathp get string value length 0 log debug encoding spaces in path pathp set object value encode spaces pathp get string value dynamic path false else log debug setting dynamic path to true dynamic path true log debug path ending value pathp get string value teststarted jmeterproperty getproperty getclass getname getstringvalue stringproperty getstringvalue setobjectvalue encodespaces getstringvalue dynamicpath dynamicpath getstringvalue see org apache jmeter testelement test listener test started java lang string public void test started string host test started testlistener teststarted teststarted teststarted public object clone http sampler base base http sampler base super clone base dynamic path dynamic path base file list null return base httpsamplerbase httpsamplerbase dynamicpath dynamicpath filelist iteratively download the redirect targets of a redirect response p the returned result will contain one subsample for each request issued including the original one that was passed in it will be an http sample result that should mostly look as if the final destination of the redirect chain had been obtained in a single shot param res result of the initial request must be a redirect response param frame depth depth of this target in the frame structure used only to prevent infinite recursion return container result with one subsample per request issued protected http sample result follow redirects http sample result res int frame depth http sample result total res new http sample result res http sample result last res res int redirect for redirect 0 redirect max redirects redirect boolean invalid redirect url false browsers seem to tolerate location headers with spaces replacing them automatically with 20 we want to emulate this behaviour string location encode spaces last res get redirect location try last res sample conversion utils make relativeurl last res geturl location get true frame depth catch malformedurl exception e last res error result e last res the redirect url we got was not a valid url invalid redirect url true if last res get sub results null last res get sub results length 0 sample result subs last res get sub results for int i 0 i subs length i total res add sub result subs i else only add sample if it is a sample of valid url redirect i e that we have actually sampled the url if invalid redirect url total res add sub result last res if last res is redirect break if redirect max redirects last res error result new io exception exceeeded maximum number of redirects max redirects last res total res add sub result last res now populate the any total res fields that need to come from last res total res set sample label total res get sample label last res get sample label the following three can be discussed should they be from the first request or from the final one i chose to do it this way because that s what browsers do they show the final url of the redirect chain in the location field total res seturl last res geturl total res sethttp method last res gethttp method total res set query string last res get query string total res set request headers last res get request headers total res set response data last res get response data total res set response code last res get response code total res set successful last res is successful total res set response message last res get response message total res set data type last res get data type total res set response headers last res get response headers total res set content type last res get content type total res set data encoding last res get data encoding no default return total res httpsampleresult framedepth httpsampleresult followredirects httpsampleresult framedepth httpsampleresult totalres httpsampleresult httpsampleresult lastres max_redirects invalidredirecturl encodespaces lastres getredirectlocation lastres conversionutils makerelativeurl lastres framedepth malformedurlexception lastres errorresult lastres invalidredirecturl lastres getsubresults lastres getsubresults sampleresult lastres getsubresults totalres addsubresult invalidredirecturl totalres addsubresult lastres lastres isredirect max_redirects lastres errorresult ioexception max_redirects lastres totalres addsubresult lastres totalres lastres totalres setsamplelabel totalres getsamplelabel lastres getsamplelabel totalres lastres totalres sethttpmethod lastres gethttpmethod totalres setquerystring lastres getquerystring totalres setrequestheaders lastres getrequestheaders totalres setresponsedata lastres getresponsedata totalres setresponsecode lastres getresponsecode totalres setsuccessful lastres issuccessful totalres setresponsemessage lastres getresponsemessage totalres setdatatype lastres getdatatype totalres setresponseheaders lastres getresponseheaders totalres setcontenttype lastres getcontenttype totalres setdataencoding lastres getdataencodingnodefault totalres follow redirects and download page resources if appropriate this works but the container stuff here is what s doing it follow redirects is actually doing the work to make sure we have only one container to make this work more naturally i think this method sample needs to take an http sampler result container parameter instead of a boolean are following redirect param are following redirect param frame depth param res return the sample result protected http sample result result processing boolean are following redirect int frame depth http sample result res boolean was redirected false if are following redirect if res is redirect log debug location set to res get redirect location if get follow redirects res follow redirects res frame depth are following redirect true was redirected true if is image parser http sample result text equals res get data type res is successful if frame depth max frame depth res add sub result error result new exception maximum frame iframe nesting depth exceeded res else if we followed redirects we already have a container if are following redirect http sample result container http sample result are following redirect res get parent res only download page resources if we were not redirected if we were redirected the page resources have already been downloaded for the sample made for the redirected url if was redirected res download page resources res container frame depth return res followredirects httpsamplerresult arefollowingredirect arefollowingredirect framedepth httpsampleresult resultprocessing arefollowingredirect framedepth httpsampleresult wasredirected arefollowingredirect isredirect getredirectlocation getfollowredirects followredirects framedepth arefollowingredirect wasredirected isimageparser httpsampleresult getdatatype issuccessful framedepth max_frame_depth addsubresult errorresult arefollowingredirect httpsampleresult httpsampleresult arefollowingredirect getparent wasredirected downloadpageresources framedepth determine if the http status code is successful or not i e in range 200 to 399 inclusive return whether in range 200 399 or not protected boolean is success code int code return code 200 code 399 issuccesscode protected static string encode back slashes string value string buffer new value new string buffer for int i 0 i value length i char char at value char at i if char at non nls 1 new value append non nls 1 else new value append char at return new value to string encodebackslashes stringbuffer newvalue stringbuffer charat charat charat newvalue newvalue charat newvalue tostring http file args object that stores file list to be uploaded private void sethttp file args http file args value set property new test element property file args value httpfileargs sethttpfileargs httpfileargs setproperty testelementproperty file_args method to get files list to be uploaded private http file args gethttp file args return http file args get property file args get object value httpfileargs gethttpfileargs httpfileargs getproperty file_args getobjectvalue http file args object that stores file list to be uploaded private void clearhttp file args remove property file args httpfileargs clearhttpfileargs removeproperty file_args get the collection of files as a list the list is built up from the filename filefield mimetype properties plus any additional entries saved in the file args property if there are no valid file entries then an empty list is returned return an array of file arguments never null public http file arg gethttp files if file list null return file list http file arg out files check for original data names use properties so variables and functions are not resolved too early j meter property file name get property file name j meter property param name get property file field j meter property mime type get property mimetype http file arg file new http file arg file name param name mime type if file is not empty now deal with any additional file arguments final http file args file args gethttp file args if file args null out files new http file arg 1 file args gethttp file arg count out files 0 file first file http file arg infiles file args as array for int i 0 i infiles length i out files i 1 infiles i else out files new http file arg file just one file else out files new http file arg no files empty array file list out files update the list cache return file list file_args httpfilearg gethttpfiles filelist filelist httpfilearg outfiles jmeterproperty filename getproperty file_name jmeterproperty paramname getproperty file_field jmeterproperty mimetype getproperty httpfilearg httpfilearg filename paramname mimetype isnotempty httpfileargs fileargs gethttpfileargs fileargs outfiles httpfilearg fileargs gethttpfileargcount outfiles httpfilearg fileargs asarray outfiles outfiles httpfilearg outfiles httpfilearg filelist outfiles filelist public int gethttp file count return gethttp files length gethttpfilecount gethttpfiles saves the list of files the first file is saved in the filename field mimetype properties any additional files are saved in the file args array param files list of files to save public void sethttp files http file arg files clearhttp file args file list null it will be regenerated by get first weed out the empty files http file arg non empty file int files found 0 if files length 0 non empty file new http file arg files length for int i 0 i files length i http file arg file files i if file is not empty non empty file files found file any files left if files found 0 http file arg file non empty file 0 set filename property file get path set file field property file get param name set mimetype property file get mime type if files found 1 http file args file args new http file args boolean empty true for int i 1 i files found i final http file arg file arg non empty file i if file arg is not empty file args addhttp file arg file arg empty false if empty sethttp file args file args else set filename property set file field property set mimetype property file_args sethttpfiles httpfilearg clearhttpfileargs filelist httpfilearg nonemptyfile filesfound nonemptyfile httpfilearg httpfilearg isnotempty nonemptyfile filesfound filesfound httpfilearg nonemptyfile setfilenameproperty getpath setfilefieldproperty getparamname setmimetypeproperty getmimetype filesfound httpfileargs fileargs httpfileargs filesfound httpfilearg filearg nonemptyfile filearg isnotempty fileargs addhttpfilearg filearg sethttpfileargs fileargs setfilenameproperty setfilefieldproperty setmimetypeproperty public static string get valid methods as array return string methodlist to array new string 0 getvalidmethodsasarray toarray public static boolean is secure string protocol return protocol https equals ignore case protocol issecure protocol_https equalsignorecase public static boolean is secure url url return is secure url get protocol issecure issecure getprotocol implement these here to avoid re implementing for sub classes previously these were implemented in all test elements public void thread started testelements threadstarted public void thread started public void thread finished threadstarted threadfinished read response from the input stream converting to md5 digest if the usemd5 property is set for the md5 case the result byte count is set to the size of the original response param sample result param in input stream param length expected input length or zero return the response or the md5 of the response throws io exception public byte read response sample result sample result input stream in int length throws io exception byte read buffer get thread context get read buffer int buffer size 32 enough for md5 message digest md null boolean asmd5 usemd5 if asmd5 try md message digest get instance md5 non nls 1 catch no such algorithm exception e log error should not happen could not find md5 digest e asmd5 false else if length 0 may also happen if long value int max buffer size 4 1024 else buffer size length byte array output stream w new byte array output stream buffer size int bytes read 0 int total bytes 0 boolean first true while bytes read in read read buffer 1 if first sample result latency end first false if asmd5 md null md update read buffer 0 bytes read total bytes bytes read else w write read buffer 0 bytes read if first bug 46838 if there was no data still need to set latency sample result latency end in close w flush if asmd5 md null byte md5 result md digest w write j orphan utils ba to hex string md5 result get bytes sample result set bytes total bytes w close return w to byte array sampleresult ioexception readresponse sampleresult sampleresult inputstream ioexception readbuffer getthreadcontext getreadbuffer buffersize messagedigest messagedigest getinstance nosuchalgorithmexception buffersize buffersize bytearrayoutputstream bytearrayoutputstream buffersize bytesread totalbytes bytesread readbuffer sampleresult latencyend readbuffer bytesread totalbytes bytesread readbuffer bytesread sampleresult latencyend md5result jorphanutils batohexstring md5result getbytes sampleresult setbytes totalbytes tobytearray private static final string required j meter utils get res string jms auth required non nls 1 public basejms sampler jmeterutils getresstring jms_auth_required basejmssampler see org apache jmeter samplers sampler sample org apache jmeter samplers entry public sample result sample entry e return this sample sampleresult public abstract sample result sample sampleresult get set properties set the initial context factory param icf public void setjndi intial context factory string icf set property jndi initial context fac icf setjndiintialcontextfactory setproperty jndi_initial_context_fac method returns the initial context factory for jndi initial context lookup return the initial context factory public string getjndi initial context factory return get property as string jndi initial context fac getjndiinitialcontextfactory getpropertyasstring jndi_initial_context_fac set the provider user for jndi param url the provider url public void set provider url string url set property provider url url setproviderurl setproperty provider_url method returns the provider url for jndi to connect to return the provider url public string get provider url return get property as string provider url getproviderurl getpropertyasstring provider_url set the connection factory for param factory public void set connection factory string factory set property conn factory factory setconnectionfactory setproperty conn_factory return the connection factory parameter used to lookup the connection factory from the jms server return the connection factory public string get connection factory return get property as string conn factory getconnectionfactory getpropertyasstring conn_factory set the topic param topic public void set topic string topic set property topic topic settopic setproperty return the topic used for the benchmark return the topic public string get topic return get property as string topic gettopic getpropertyasstring set the username to login into the jms server if needed param user public void set username string user set property principal user setusername setproperty return the username used to login to the jms server return the username used to login to the jms server public string get username return get property as string principal getusername getpropertyasstring set the password to login to the jms server param pwd public void set password string pwd set property credentials pwd setpassword setproperty return the password used to login to the jms server return the password used to login to the jms server public string get password return get property as string credentials getpassword getpropertyasstring set the number of iterations the sampler should aggregate param count public void set iterations string count set property iterations count setiterations setproperty get the iterations as string return the number of iterations public string get iterations return get property as string iterations getiterations getpropertyasstring return the number of iterations as int instead of string return the number of iterations as int instead of string public int get iteration count return get property as int iterations getiterationcount getpropertyasint set whether authentication is required for jndi param use auth public void set use auth boolean use auth set property use auth use auth useauth setuseauth useauth setproperty use_auth useauth return whether jndi requires authentication return whether jndi requires authentication public boolean is use auth final string use auth get property as string use auth return use auth equals ignore case true use auth equals required non nls 1 isuseauth useauth getpropertyasstring use_auth useauth equalsignorecase useauth set whether the sampler should read the response or not param read whether the sampler should read the response or not public void set read response string read set property read response read setreadresponse setproperty read_response return whether the sampler should read the response return whether the sampler should read the response public string get read response return get property as string read response getreadresponse getpropertyasstring read_response return whether the sampler should read the response as a boolean value return whether the sampler should read the response as a boolean value public boolean get read response as boolean return get property as boolean read response getreadresponseasboolean getpropertyasboolean read_response if the sampler should use jndi properties file call the method with true param properties public void set usejndi properties string properties set property use properties file properties setusejndiproperties setproperty use_properties_file return whether the sampler should use properties file instead of ui parameters return whether the sampler should use properties file instead of ui parameters public string get usejndi properties return get property as string use properties file getusejndiproperties getpropertyasstring use_properties_file return the properties as boolean true false return whether the sampler should use properties file instead of ui parameters public boolean get usejndi properties as boolean return get property as boolean use properties file getusejndipropertiesasboolean getpropertyasboolean use_properties_file public static synchronized context lookup context string jndi string url boolean use auth string user string pwd context ctx context map get jndi url if ctx null properties props new properties props set property context initial context factory jndi props set property context provider url url if use auth user null pwd null user length 0 pwd length 0 props set property context security principal user props set property context security credentials pwd log info authentication properties set try ctx new initial context props log info created the jndi initial context factory catch naming exception e log error lookup context e get message if ctx null map put jndi url ctx return ctx lookupcontext useauth setproperty initial_context_factory setproperty provider_url useauth setproperty security_principal setproperty security_credentials initialcontext namingexception lookupcontext getmessage method will lookup a given topic using jndi param ctx param name return the topic or null public static synchronized topic lookup topic context ctx string name topic t null if name null ctx null try t topic ctx lookup name catch naming exception e log error jndi error e get message else if name null log error lookup topic name was null else log error lookup topic context was null return t lookuptopic namingexception getmessage lookuptopic lookuptopic clear all the initial context objects public static void close iterator itr map key set iterator while itr has next context ctx context map get itr next try ctx close catch naming exception e log error e get message log info initial context factory close called and context instances cleaned up initialcontext keyset hasnext namingexception getmessage initialcontextfactory default constructor the label and the text field are left empty public j labeled choice super choice list new j combo box init jlabeledchoice choicelist jcombobox public j labeled choice string p label boolean editable super choice list new j combo box m label set text p label choice list set editable editable init jlabeledchoice plabel choicelist jcombobox mlabel settext plabel choicelist seteditable constructs a non edittable combo box with the label displaying the passed text param p label the text to display in the label param items the items to display in the combo box public j labeled choice string p label string items this p label items false plabel jlabeledchoice plabel plabel constructs a combo box with the label displaying the passed text param p label the text to display in the label param items the items to display in the combo box param editable if true then add and delete buttons are created public j labeled choice string p label string items boolean editable super m label set text p label choice list new j combo box items choice list set editable editable init plabel jlabeledchoice plabel mlabel settext plabel choicelist jcombobox choicelist seteditable public list get component list list comps new linked list comps add m label comps add choice list return comps getcomponentlist linkedlist mlabel choicelist public void set editable boolean editable choice list set editable editable seteditable choicelist seteditable public void add value string item choice list add item item addvalue choicelist additem public void set values string items choice list remove all items for int i 0 i items length i choice list add item items i setvalues choicelist removeallitems choicelist additem initialises all of the components on this panel private void init if choice list is editable choice list add action listener new combo listener choice list set border border factory create lowered bevel border register the handler for focus listening this handler will only notify the registered when the text changes from when the focus is gained to when it is lost choice list add item listener new item listener callback method when the focus to the text field component is lost param e the focus event that occured public void item state changed item event e if e get state change item event selected notify change listeners add the sub components this add m label this add choice list if choice list is editable add new j button add add set margin new insets 1 1 1 1 add add action listener new add listener this add add delete new j button del delete set margin new insets 1 1 1 1 delete add action listener new delete listener this add delete choicelist iseditable choicelist addactionlistener combolistener choicelist setborder borderfactory createloweredbevelborder choicelist additemlistener itemlistener itemstatechanged itemevent getstatechange itemevent notifychangelisteners mlabel choicelist choicelist iseditable jbutton setmargin addactionlistener addlistener jbutton setmargin addactionlistener deletelistener choice list add item listener new item listener callback method when the focus to the text field component is lost param e the focus event that occured public void item state changed item event e if e get state change item event selected notify change listeners choicelist additemlistener itemlistener itemstatechanged itemevent getstatechange itemevent notifychangelisteners set the text displayed in the label param p label the new label text public void set label string p label m label set text p label plabel setlabel plabel mlabel settext plabel set the text displayed in the text field param p text the new text to display in the text field public void set text string p text choice list set selected item p text ptext settext ptext choicelist setselecteditem ptext public void set selected index int index choice list set selected index index setselectedindex choicelist setselectedindex returns the text in the text field return the text in the text field never returns null public string get text object item choice list get selected item if item null return else return string item gettext choicelist getselecteditem public int get selected index return choice list get selected index getselectedindex choicelist getselectedindex public object get selected items object list choice list get selected objects if list null return empty object array return list getselecteditems choicelist getselectedobjects empty_object_array public string get items string items new string choice list get item count for int i 0 i items length i items i string choice list get item at i return items getitems choicelist getitemcount choicelist getitemat returns the text of the label return the text of the label public string get label return m label get text getlabel mlabel gettext registers the text to display in a tool tip the text displays when the cursor lingers over the component param text the string to display if the text is null the tool tip is turned off for this component public void set tool tip text string text choice list set tool tip text text settooltiptext choicelist settooltiptext returns the tooltip string that has been set with set tool tip text return the text of the tool tip public string get tool tip text if choice list null necessary to avoid npe when testing serialisation return null return choice list get tool tip text settooltiptext gettooltiptext choicelist choicelist gettooltiptext adds a change listener that will be notified when the text in the text field is changed the change event that will be passed to registered listeners will contain this object as the source allowing the new text to be extracted using the link get text get text method param p change listener the listener to add public void add change listener change listener p change listener m change listeners add p change listener changeevent gettext gettext pchangelistener addchangelistener changelistener pchangelistener mchangelisteners pchangelistener removes a change listener param p change listener the change listener to remove public void remove change listener change listener p change listener m change listeners remove p change listener pchangelistener removechangelistener changelistener pchangelistener mchangelisteners pchangelistener notify all registered change listeners that the text in the text field has changed private void notify change listeners change event ce new change event this for int index 0 index m change listeners size index change listener m change listeners get index state changed ce notifychangelisteners changeevent changeevent mchangelisteners changelistener mchangelisteners statechanged public void action performed action event e object item choice list get selected item int index choice list get selected index if item equals choice list get item at index choice list add item item choice list set selected item item notify change listeners actionperformed actionevent choicelist getselecteditem choicelist getselectedindex choicelist getitemat choicelist additem choicelist setselecteditem notifychangelisteners public void action performed action event e if choice list get item count 1 choice list remove item at choice list get selected index notify change listeners actionperformed actionevent choicelist getitemcount choicelist removeitemat choicelist getselectedindex notifychangelisteners public class uniform random timer extends random timer implements serializable public long delay return long math abs this random next double get range super delay uniformrandomtimer randomtimer nextdouble getrange public string to string return j meter utils get res string uniform timer memo non nls 1 tostring jmeterutils getresstring uniform_timer_memo public class bean shell pre processor bean info extends bean shell bean info support public bean shell pre processor bean info super bean shell pre processor class beanshellpreprocessorbeaninfo beanshellbeaninfosupport beanshellpreprocessorbeaninfo beanshellpreprocessor constructor for the exit command object public exit command exitcommand exitcommand gets the action names attribute of the exit command object return the action names value public set get action names return commands actionnames exitcommand actionnames getactionnames description of the method param e description of parameter public void do action action event e action router get instance do action now new action event e get source e getid action names check dirty if gui package get instance is dirty int chosen option j option pane show confirm dialog gui package get instance get main frame j meter utils get res string cancel exit to save non nls 1 j meter utils get res string save non nls 1 j option pane yes no cancel option j option pane question message if chosen option j option pane no option system exit 0 else if chosen option j option pane yes option action router get instance do action now new action event e get source e getid action names save all as if gui package get instance is dirty system exit 0 else system exit 0 doaction actionevent actionrouter getinstance doactionnow actionevent getsource actionnames check_dirty guipackage getinstance isdirty chosenoption joptionpane showconfirmdialog guipackage getinstance getmainframe jmeterutils getresstring cancel_exit_to_save jmeterutils getresstring joptionpane yes_no_cancel_option joptionpane question_message chosenoption joptionpane no_option chosenoption joptionpane yes_option actionrouter getinstance doactionnow actionevent getsource actionnames save_all_as guipackage getinstance isdirty constructor for the graph visualizer object public distribution graph visualizer model new sampling stat calculator distribution graph new distribution graph model graph set background color white init graphvisualizer distributiongraphvisualizer samplingstatcalculator distributiongraph setbackground gets the image attribute of the graph visualizer object return the image value public image get image image result graph create image graph get width graph get height graph paint component result get graphics return result graphvisualizer getimage createimage getwidth getheight paintcomponent getgraphics public synchronized void update gui if graph get width 10 graph set preferred size new dimension get width 40 get height 160 graph panel updateui graph repaint updategui getwidth setpreferredsize getwidth getheight graphpanel public synchronized void update gui sample s we have received one more sample if delay counter update gui counter 0 else counter updategui updategui public synchronized void add sample result res model add sample res update gui model get current sample sampleresult addsample updategui getcurrentsample public string get label resource return distribution graph title non nls 1 getlabelresource distribution_graph_title public synchronized void clear data this graph clear data model clear repaint cleardata cleardata public string to string return show the samples in a distribution graph tostring initialize the gui private void init this set layout new border layout main panel border margin new empty border 10 10 5 10 this set border margin set up the graph with header footer y axis and graph display j panel lgraph panel new j panel new border layout lgraph panel add create graph panel border layout center lgraph panel add create graph info panel border layout south add the main panel and the graph this add make title panel border layout north this add lgraph panel border layout center setlayout borderlayout emptyborder setborder jpanel lgraphpanel jpanel borderlayout lgraphpanel creategraphpanel borderlayout lgraphpanel creategraphinfopanel borderlayout maketitlepanel borderlayout lgraphpanel borderlayout creates a scroll pane containing the actual graph of the results return a scroll pane containing the graph private component create graph panel graph panel new j panel graph panel set border border factory create bevel border bevel border lowered color light gray color dark gray graph panel add graph graph panel set background color white return graph panel creategraphpanel graphpanel jpanel graphpanel setborder borderfactory createbevelborder bevelborder lightgray darkgray graphpanel graphpanel setbackground graphpanel creates a label for one of the fields used to display the graph s current values neither the label created by this method or the code field code passed as a parameter is added to the gui here param label resource name the name of the label resource this is used to look up the label text using link j meter utils get res string string param field the field this label is being created for private j label create info label string label resource name j text field field j label label new j label j meter utils get res string label resource name label set foreground field get foreground label set label for field return label labelresourcename jmeterutils getresstring jlabel createinfolabel labelresourcename jtextfield jlabel jlabel jmeterutils getresstring labelresourcename setforeground getforeground setlabelfor creates the information panel at the bottom return private box create graph info panel box graph info panel box create horizontal box this note field new j text field graph info panel add this create info label distribution note1 this note field non nls 1 return graph info panel creategraphinfopanel graphinfopanel createhorizontalbox notefield jtextfield graphinfopanel createinfolabel distribution_note1 notefield graphinfopanel method implements printable which is suppose to return the correct internal component the action class can then print or save the graphics to a file public j component get printable component return this graph panel jcomponent getprintablecomponent graphpanel public load super public set get action names return commands getactionnames public void do action action event e j file chooser chooser file dialoger prompt to open file new string jmx non nls 1 if chooser null return file selected file chooser get selected file if selected file null boolean merging e get action command equals action names merge we must ask the user if it is ok to close current project if merging if close perform action e return load project file e selected file merging doaction actionevent jfilechooser filedialoger prompttoopenfile selectedfile getselectedfile selectedfile getactioncommand actionnames performaction loadprojectfile selectedfile static void load project file action event e file f boolean merging gui package gui package gui package get instance input stream reader null try if f null boolean is test plan false if merging log info merging file f else log info loading file f file server get file server set basedir f get absolute path reader new file input stream f hash tree tree save service load tree reader is test plan insert loaded tree e getid tree merging don t change name if merging if merging is test plan gui package set test plan file f get absolute path catch no class def found error ex allow for missing optional jars log warn missing jar file ex string msg ex get message if msg null msg missing jar file see log for details j meter utils report error to user msg catch conversion exception ex log warn could not convert file ex j meter utils report error to user save service c eto string ex catch io exception ex log warn error reading file ex string msg ex get message if msg null msg unexpected error see log for details j meter utils report error to user msg catch exception ex log warn unexpected error ex string msg ex get message if msg null msg unexpected error see log for details j meter utils report error to user msg finally j orphan utils close quietly reader gui package update current gui gui package get main frame repaint loadprojectfile actionevent guipackage guipackage guipackage getinstance inputstream istestplan fileserver getfileserver setbasedir getabsolutepath fileinputstream hashtree saveservice loadtree istestplan insertloadedtree istestplan guipackage settestplanfile getabsolutepath noclassdeffounderror getmessage jmeterutils reporterrortouser conversionexception jmeterutils reporterrortouser saveservice cetostring ioexception getmessage jmeterutils reporterrortouser getmessage jmeterutils reporterrortouser jorphanutils closequietly guipackage updatecurrentgui guipackage getmainframe returns a boolean indicating whether the loaded tree was a full test plan public static boolean insert loaded tree int id hash tree tree boolean merging throws exception illegal user action exception convert tree tree if tree null throw new exception error in test plan see log file boolean is test plan tree get array 0 instanceof test plan if we are loading a new test plan initialize the tree with the testplan node we are loading gui package gui instance gui package get instance if is test plan merging gui instance clear test plan test element tree get array 0 if merging check if target of merge is reasonable test element te test element tree get array 0 if te instanceof work bench te instanceof test plan these are handled specially by add to tree boolean ok menu factory can add to gui instance get current node te if ok string name te get name string class name te get class get name class name class name substring class name last index of 1 throw new illegal user action exception can t merge name class name here hash tree new tree gui instance add sub tree tree gui instance update current gui gui instance get main frame get tree set selection path new tree path j meter tree node new tree get array 0 get path tree gui instance get current sub tree send different event wether we are merging a test plan into another test plan or loading a testplan from scratch action event action event null if merging action event new action event tree get tree get array tree size 1 id action names sub tree loaded else action event new action event tree get tree get array tree size 1 id action names sub tree merged action router get instance action performed action event if expand tree merging don t automatically expand when merging j tree j tree gui instance get main frame get tree for int i 0 i j tree get row count i j tree expand row i return is test plan insertloadedtree hashtree illegaluseractionexception converttree testplan istestplan getarray testplan guipackage guiinstance guipackage getinstance istestplan guiinstance cleartestplan testelement getarray testelement testelement getarray workbench testplan addtotree menufactory canaddto guiinstance getcurrentnode getname classname getclass getname classname classname classname lastindexof illegaluseractionexception classname hashtree newtree guiinstance addsubtree guiinstance updatecurrentgui guiinstance getmainframe gettree setselectionpath treepath jmetertreenode newtree getarray getpath guiinstance getcurrentsubtree actionevent actionevent actionevent actionevent getarray actionnames sub_tree_loaded actionevent actionevent getarray actionnames sub_tree_merged actionrouter getinstance actionperformed actionevent expandtree jtree jtree guiinstance getmainframe gettree jtree getrowcount jtree expandrow istestplan public static boolean insert loaded tree int id hash tree tree throws exception illegal user action exception return insert loaded tree id tree false insertloadedtree hashtree illegaluseractionexception insertloadedtree public regex function template pattern j meter utils get pattern cache get pattern template pattern perl5 compiler read only mask regexfunction templatepattern jmeterutils getpatterncache getpattern template_pattern perl5compiler read_only_mask public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception string value index default value between non nls 1 non nls 2 non nls 3 string name non nls 1 string input variable non nls 1 pattern search pattern object tmplt try search pattern j meter utils get pattern cache get pattern compound variable values 0 execute perl5 compiler read only mask tmplt generate template compound variable values 1 execute if values length 2 value index compound variable values 2 execute if value index length 0 value index 1 non nls 1 if values length 3 between compound variable values 3 execute if values length 4 string dv compound variable values 4 execute if dv length 0 default value dv if values length 5 name compound variable values 5 execute if values length 6 input variable compound variable values 6 execute catch malformed cache pattern exception e throw new invalid variable exception e to string relatively expensive operation so do it once j meter variables vars get variables if vars null can happen if called during test closedown return default value if name length 0 vars put name default value string text to match null if input variable length 0 text to match vars get input variable else if previous result null text to match previous result get response data as string if text to match null text to match length 0 return default value list collect all matches new array list try pattern matcher matcher j meter utils get matcher pattern matcher input input new pattern matcher input text to match while matcher contains input search pattern match result match matcher get match collect all matches add match catch number format exception e todo can this occur log error e non nls 1 return default value finally if name length 0 vars put name matchnr collect all matches size non nls 1 non nls 2 if collect all matches size 0 return default value if value index equals all string buffer value new string buffer iterator it collect all matches iterator boolean first true while it has next if first value append between else first false value append generate result match result it next name tmplt vars return value to string else if value index equals rand match result result match result collect all matches get rand next int collect all matches size return generate result result name tmplt vars else try int index integer parse int value index 1 match result result match result collect all matches get index return generate result result name tmplt vars catch number format exception e float ratio float parse float value index match result result match result collect all matches get int collect all matches size ratio 5 1 return generate result result name tmplt vars catch index out of bounds exception e return default value sampleresult previousresult currentsampler invalidvariableexception valueindex defaultvalue inputvariable searchpattern searchpattern jmeterutils getpatterncache getpattern compoundvariable perl5compiler read_only_mask generatetemplate compoundvariable valueindex compoundvariable valueindex valueindex compoundvariable compoundvariable defaultvalue compoundvariable inputvariable compoundvariable malformedcachepatternexception invalidvariableexception tostring jmetervariables getvariables defaultvalue defaultvalue texttomatch inputvariable texttomatch inputvariable previousresult texttomatch previousresult getresponsedataasstring texttomatch texttomatch defaultvalue collectallmatches arraylist patternmatcher jmeterutils getmatcher patternmatcherinput patternmatcherinput texttomatch searchpattern matchresult getmatch collectallmatches numberformatexception defaultvalue _matchnr collectallmatches collectallmatches defaultvalue valueindex stringbuffer stringbuffer collectallmatches hasnext generateresult matchresult tostring valueindex matchresult matchresult collectallmatches nextint collectallmatches generateresult parseint valueindex matchresult matchresult collectallmatches generateresult numberformatexception parsefloat valueindex matchresult matchresult collectallmatches collectallmatches generateresult indexoutofboundsexception defaultvalue private void save groups match result result string namep j meter variables vars if result null for int x 0 x result groups x vars put namep g x result group x non nls 1 savegroups matchresult jmetervariables _g public list get argument desc return desc getargumentdesc private string generate result match result match string namep object template j meter variables vars save groups match namep vars string buffer result new string buffer for int a 0 a template length a if template a instanceof string result append template a else result append match group integer template a int value if namep length 0 vars put namep result to string return result to string generateresult matchresult jmetervariables savegroups stringbuffer stringbuffer intvalue tostring tostring public string get reference key return key getreferencekey public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters min parameter count max parameter count values parameters to array setparameters invalidvariableexception checkparametercount min_parameter_count max_parameter_count toarray private object generate template string raw template list pieces new array list list combined new linked list pattern matcher matcher j meter utils get matcher util split pieces matcher template pattern raw template pattern matcher input input new pattern matcher input raw template boolean starts with is first element group raw template if starts with pieces remove 0 remove initial empty entry iterator iter pieces iterator while iter has next boolean match exists matcher contains input template pattern if starts with if match exists combined add new integer matcher get match group 1 combined add iter next else combined add iter next if match exists combined add new integer matcher get match group 1 if matcher contains input template pattern combined add new integer matcher get match group 1 return combined to array generatetemplate rawtemplate arraylist linkedlist patternmatcher jmeterutils getmatcher templatepattern rawtemplate patternmatcherinput patternmatcherinput rawtemplate startswith isfirstelementgroup rawtemplate startswith hasnext matchexists templatepattern startswith matchexists getmatch matchexists getmatch templatepattern getmatch toarray private boolean is first element group string raw data pattern pattern j meter utils get pattern cache get pattern d non nls 1 perl5 compiler read only mask return j meter utils get matcher contains raw data pattern isfirstelementgroup rawdata jmeterutils getpatterncache getpattern perl5compiler read_only_mask jmeterutils getmatcher rawdata private long batch send time 1 public batch sample sender log warn constructor only intended for use in testing non nls 1 batchsendtime batchsamplesender constructor param listener that the list of sample events will be sent to batch sample sender remote sample listener listener this listener listener init log info using batching for this run thresholds num num samples threshold time time threshold batchsamplesender remotesamplelistener numsamplesthreshold timethreshold checks for the jmeter properties num sample threshold and time threshold and assigns defaults if not found private void init this num samples threshold j meter utils get prop default num sample threshold default num sample threshold this time threshold j meter utils get prop default time threshold default time threshold num_sample_threshold time_threshold numsamplesthreshold jmeterutils getpropdefault num_sample_threshold default_num_sample_threshold timethreshold jmeterutils getpropdefault time_threshold default_time_threshold checks if any sample events are still present in the sample store and sends them to the listener informs the listener of the testended public void test ended try if sample store size 0 listener process batch sample store sample store clear listener test ended catch remote exception err log error test ended err samplestore testended samplestore processbatch samplestore samplestore testended remoteexception testended checks if any sample events are still present in the sample store and sends them to the listener informs the listener of the testended param host the host that the test has ended on public void test ended string host try if sample store size 0 listener process batch sample store sample store clear listener test ended host catch remote exception err log error test ended host err samplestore testended samplestore processbatch samplestore samplestore testended remoteexception testended stores sample events untill either a time or sample threshold is breached both thresholds are reset if one fires if only one threshold is set it becomes the only value checked against when a threhold is breached the list of sample events is sent to a listener where the event are fired locally param e a sample event public void sample occurred sample event e synchronized sample store sample store add e if num samples threshold 1 if sample store size num samples threshold try log debug firing sample listener process batch sample store sample store clear catch remote exception err log error sample occurred err if time threshold 1 sample result sr e get result long timestamp sr get time stamp checking for and creating initial timestamp to cheak against if batch send time 1 this batch send time timestamp time threshold if batch send time timestamp try log debug firing time if sample store size 0 listener process batch sample store sample store clear this batch send time timestamp time threshold catch remote exception err log error sample occurred err sampleoccurred sampleevent samplestore samplestore numsamplesthreshold samplestore numsamplesthreshold processbatch samplestore samplestore remoteexception sampleoccurred timethreshold sampleresult getresult gettimestamp batchsendtime batchsendtime timethreshold batchsendtime samplestore processbatch samplestore samplestore batchsendtime timethreshold remoteexception sampleoccurred public class sample event converter implements converter returns the converter version used to check for possible incompatibilities public static string get version return revision 674365 non nls 1 sampleeventconverter getversion see com thoughtworks xstream converters converter can convert java lang class public boolean can convert class arg0 return sample event class equals arg0 canconvert canconvert sampleevent todo save hostname save sample type plain or http public void marshal object source hierarchical stream writer writer marshalling context context sample event evt sample event source object res evt get result context convert another res hierarchicalstreamwriter marshallingcontext sampleevent sampleevent getresult convertanother todo does not work yet need to determine the sample type public object unmarshal hierarchical stream reader reader unmarshalling context context sample event evt new sample event return evt hierarchicalstreamreader unmarshallingcontext sampleevent sampleevent public sample result sample entry e sample result res new sample result res set sample label get name res set sampler data my string property res sample start do something res set response data my string property to upper case get bytes res set data type sample result text res sample end res set successful true return res sampleresult sampleresult sampleresult setsamplelabel getname setsamplerdata mystringproperty samplestart setresponsedata mystringproperty touppercase getbytes setdatatype sampleresult sampleend setsuccessful a string property public void set my string property string s my string property s setmystringproperty mystringproperty public string get my string property return my string property getmystringproperty mystringproperty the object table model is a table model whose rows are objects columns are defined as functors on the object param headers column names param objclass object class that will be used param read functors used to get the values param write functors used to set the values param editor classes class for each column public object table model string headers class objclass functor read functors functor write functors class editor classes this headers read functors write functors editor classes this object class objclass objecttablemodel tablemodel _objclass readfunctors writefunctors editorclasses objecttablemodel _objclass readfunctors writefunctors editorclasses readfunctors writefunctors editorclasses objectclass _objclass the object table model is a table model whose rows are objects columns are defined as functors on the object param headers column names param read functors used to get the values param write functors used to set the values param editor classes class for each column public object table model string headers functor read functors functor write functors class editor classes this headers add all arrays as list headers this classes add all arrays as list editor classes this read functors new array list arrays as list read functors this write functors new array list arrays as list write functors int num headers headers length int num classes classes size if num classes num headers log warn header count num headers but classes count num classes functor count 0 is handled specially int num write write functors length if num write 0 num write num headers log warn header count num headers but write functor count num write int num read read functors length if num read 0 num read num headers log warn header count num headers but read functor count num read objecttablemodel tablemodel readfunctors writefunctors editorclasses objecttablemodel readfunctors writefunctors editorclasses addall aslist addall aslist editorclasses readfunctors arraylist aslist readfunctors writefunctors arraylist aslist writefunctors numheaders numclasses numclasses numheaders numheaders numclasses numwrite writefunctors numwrite numwrite numheaders numheaders writefunctor numwrite numread readfunctors numread numread numheaders numheaders readfunctor numread private object read resolve objects new array list headers new array list classes new array list read functors new array list write functors new array list return this readresolve arraylist arraylist arraylist readfunctors arraylist writefunctors arraylist public iterator iterator return objects iterator public void clear data int size get row count objects clear super fire table rows deleted 0 size cleardata getrowcount firetablerowsdeleted public void add row object value log debug adding row value value if object class null final class value class value get class if object class is assignable from value class throw new illegal argument exception trying to add class value class get name expecting class object class get name objects add value super fire table rows inserted objects size 1 objects size addrow objectclass valueclass getclass objectclass isassignablefrom valueclass illegalargumentexception valueclass getname objectclass getname firetablerowsinserted public void insert row object value int index objects add index value super fire table rows inserted index index 1 insertrow firetablerowsinserted see javax swing table table model get column count public int get column count return headers size tablemodel getcolumncount getcolumncount see javax swing table table model get column name int public string get column name int col return string headers get col tablemodel getcolumnname getcolumnname see javax swing table table model get row count public int get row count if objects null return 0 return objects size tablemodel getrowcount getrowcount see javax swing table table model get value at int int public object get value at int row int col log debug getting row value object value objects get row if headers size 1 col read functors size return value functor get method functor read functors get col if get method null value null return get method invoke value return null tablemodel getvalueat getvalueat readfunctors getmethod readfunctors getmethod getmethod see javax swing table table model is cell editable int int public boolean is cell editable int arg0 int arg1 return true tablemodel iscelleditable iscelleditable see javax swing table default table model move row int int int public void move row int start int end int to list sub list objects sub list start end for int x end 1 x start x objects remove x objects add all to sub list super fire table changed new table model event this defaulttablemodel moverow moverow sublist sublist addall sublist firetablechanged tablemodelevent see javax swing table default table model remove row int public void remove row int row objects remove row super fire table rows deleted row row defaulttablemodel removerow removerow firetablerowsdeleted see javax swing table table model set value at java lang object int int public void set value at object cell value int row int col if row objects size object value objects get row if col write functors size functor set method functor write functors get col if set method null set method invoke value new object cell value super fire table data changed else if headers size 1 objects set row cell value tablemodel setvalueat setvalueat cellvalue writefunctors setmethod writefunctors setmethod setmethod cellvalue firetabledatachanged cellvalue see javax swing table table model get column class int public class get column class int arg0 return class classes get arg0 tablemodel getcolumnclass getcolumnclass check all registered functors p b only for use in unit test code b p param value an instance of the table model row data item if null use the class passed to the constructor param caller class of caller return false if at least one functor cannot be found public boolean check functors object value class caller object value if value null object class null try value object class new instance catch instantiation exception e log error cannot create instance of class object class get name e return false catch illegal access exception e log error cannot create instance of class object class get name e return false else value value boolean status true for int i 0 i get column count i functor set method functor write functors get i if set method null if set method check method value get column class i status false log warn caller get name is attempting to use nonexistent set method to string functor get method functor read functors get i if get method null if get method check method value status false log warn caller get name is attempting to use nonexistent get method to string return status _value checkfunctors _value _value objectclass objectclass newinstance instantiationexception objectclass getname illegalaccessexception objectclass getname _value getcolumncount setmethod writefunctors setmethod setmethod checkmethod getcolumnclass getname setmethod tostring getmethod readfunctors getmethod getmethod checkmethod getname getmethod tostring constructor public graph accum visualizer super model new graph accum model model add graph accum listener this init log debug start graph accum visualizer1 log debug end graph accum visualizer1 graphaccumvisualizer graphaccummodel addgraphaccumlistener graphaccumvisualizer1 graphaccumvisualizer1 public string get label resource return graph full results title non nls 1 getlabelresource graph_full_results_title public void add sample result res model add new sample res sampleresult addnewsample returns the panel where labels can be added return a panel where labels can be added public object get white canvas return legend panel getwhitecanvas legendpanel gets the image attribute of the graph visualizer object return the image value public image get image log debug start get image1 image result graph create image graph get width graph get height graph paint component result get graphics log debug end get image1 return result graphvisualizer getimage getimage1 createimage getwidth getheight paintcomponent getgraphics getimage1 updates the gui to reflect changes public void update gui log debug start update gui1 graph update gui log debug end update gui1 updategui updategui1 updategui updategui1 updates gui to reflect small changes param s sample to be added to plot public void update gui sample result s log debug start update gui2 log debug end update gui2 updategui sampleresult updategui2 updategui2 clear this visualizer data public synchronized void clear data model clear data graph clear data log debug start clear1 repaint log debug end clear1 cleardata cleardata cleardata returns a description of this instance return description of this instance public string to string string to string show the samples analysys as dot plots log debug to string1 returning to string return to string tostring tostring tostring1 tostring tostring setup all the swing components private void init log debug start init1 graph new graph accum model graph set visualizer this this set layout new border layout main panel j panel main panel new j panel border margin new empty border 10 10 5 10 main panel set border margin main panel set layout new box layout main panel box layout y axis title j label panel title label new j label j meter utils get res string graph full results title non nls 1 font cur font panel title label get font int cur font size cur font get size cur font size 4 panel title label set font new font cur font get font name cur font get style cur font size main panel add panel title label main panel add get name panel main panel add get file panel j scroll pane graph scroll panel new j scroll pane graph j scroll pane vertical scrollbar never j scroll pane horizontal scrollbar as needed graph scroll panel set viewport border border factory create empty border 2 2 2 2 legend panel new j panel j scroll pane legend scroll panel new j scroll pane legend panel j split pane graph split pane new j split pane j split pane vertical split graph scroll panel legend scroll panel this add main panel border layout north this add graph split pane border layout center log debug end init1 graphaccum setvisualizer setlayout borderlayout jpanel mainpanel jpanel emptyborder mainpanel setborder mainpanel setlayout boxlayout mainpanel boxlayout y_axis jlabel paneltitlelabel jlabel jmeterutils getresstring graph_full_results_title curfont paneltitlelabel getfont curfontsize curfont getsize curfontsize paneltitlelabel setfont curfont getfontname curfont getstyle curfontsize mainpanel paneltitlelabel mainpanel getnamepanel mainpanel getfilepanel jscrollpane graphscrollpanel jscrollpane jscrollpane vertical_scrollbar_never jscrollpane horizontal_scrollbar_as_needed graphscrollpanel setviewportborder borderfactory createemptyborder legendpanel jpanel jscrollpane legendscrollpanel jscrollpane legendpanel jsplitpane graphsplitpane jsplitpane jsplitpane vertical_split graphscrollpanel legendscrollpanel mainpanel borderlayout graphsplitpane borderlayout public class anchor modifier gui extends abstract pre processor gui public anchor modifier gui init anchormodifiergui abstractpreprocessorgui anchormodifiergui public string get label resource return anchor modifier title non nls 1 getlabelresource anchor_modifier_title public test element create test element anchor modifier modifier new anchor modifier modify test element modifier return modifier testelement createtestelement anchormodifier anchormodifier modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element modifier configure test element modifier testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement private void init set layout new border layout set border make border add make title panel border layout north setlayout borderlayout setborder makeborder maketitlepanel borderlayout public spline visualizer super model new spline model graph new spline graph this model set listener this setgui splinevisualizer splinemodel splinegraph setlistener public void add sample result res model add res sampleresult public string get label resource return spline visualizer title non nls 1 getlabelresource spline_visualizer_title public void update gui sample s update gui updategui updategui public void clear data model clear data cleardata cleardata private void setgui color back color background color this set background back color this set layout new border layout main panel j panel main panel new j panel border margin new empty border 10 10 5 10 main panel set border margin main panel set layout new vertical layout 5 vertical layout both name main panel add make title panel maximum label new j label j meter utils get res string spline visualizer maximum non nls 1 maximum label set foreground maximum color maximum label set background back color average label new j label j meter utils get res string spline visualizer average non nls 1 average label set foreground average color average label set background back color incoming label new j label j meter utils get res string spline visualizer incoming non nls 1 incoming label set foreground incoming color incoming label set background back color minimum label new j label j meter utils get res string spline visualizer minimum non nls 1 minimum label set foreground minimum color minimum label set background back color maximum number label new j label 0 ms non nls 1 maximum number label set horizontal alignment j label right maximum number label set foreground maximum color maximum number label set background back color average number label new j label 0 ms non nls 1 average number label set horizontal alignment j label right average number label set foreground average color average number label set background back color incoming number label new j label 0 ms non nls 1 incoming number label set horizontal alignment j label right incoming number label set foreground incoming color incoming number label set background back color minimum number label new j label 0 ms non nls 1 minimum number label set horizontal alignment j label right minimum number label set foreground minimum color minimum number label set background back color description panel j panel label panel new j panel label panel set layout new grid layout 0 1 label panel set border border factory create empty border 0 0 0 20 label panel set background back color label panel add maximum label label panel add average label if model show incoming samples label panel add incoming label label panel add minimum label number panel j panel number panel new j panel number panel set layout new grid layout 0 1 number panel set border border factory create empty border 0 0 0 20 number panel set background back color number panel add maximum number label number panel add average number label if model show incoming samples number panel add incoming number label number panel add minimum number label information display panel j panel info panel new j panel info panel set layout new border layout info panel add label panel border layout center info panel add number panel border layout east this add main panel border layout north this add info panel border layout west this add graph border layout center everyone is free to swing on its side add info panel border layout east backcolor background_color setbackground backcolor setlayout borderlayout jpanel mainpanel jpanel emptyborder mainpanel setborder mainpanel setlayout verticallayout verticallayout mainpanel maketitlepanel maximumlabel jlabel jmeterutils getresstring spline_visualizer_maximum maximumlabel setforeground maximum_color maximumlabel setbackground backcolor averagelabel jlabel jmeterutils getresstring spline_visualizer_average averagelabel setforeground average_color averagelabel setbackground backcolor incominglabel jlabel jmeterutils getresstring spline_visualizer_incoming incominglabel setforeground incoming_color incominglabel setbackground backcolor minimumlabel jlabel jmeterutils getresstring spline_visualizer_minimum minimumlabel setforeground minimum_color minimumlabel setbackground backcolor maximumnumberlabel jlabel maximumnumberlabel sethorizontalalignment jlabel maximumnumberlabel setforeground maximum_color maximumnumberlabel setbackground backcolor averagenumberlabel jlabel averagenumberlabel sethorizontalalignment jlabel averagenumberlabel setforeground average_color averagenumberlabel setbackground backcolor incomingnumberlabel jlabel incomingnumberlabel sethorizontalalignment jlabel incomingnumberlabel setforeground incoming_color incomingnumberlabel setbackground backcolor minimumnumberlabel jlabel minimumnumberlabel sethorizontalalignment jlabel minimumnumberlabel setforeground minimum_color minimumnumberlabel setbackground backcolor jpanel labelpanel jpanel labelpanel setlayout gridlayout labelpanel setborder borderfactory createemptyborder labelpanel setbackground backcolor labelpanel maximumlabel labelpanel averagelabel show_incoming_samples labelpanel incominglabel labelpanel minimumlabel jpanel numberpanel jpanel numberpanel setlayout gridlayout numberpanel setborder borderfactory createemptyborder numberpanel setbackground backcolor numberpanel maximumnumberlabel numberpanel averagenumberlabel show_incoming_samples numberpanel incomingnumberlabel numberpanel minimumnumberlabel jpanel infopanel jpanel infopanel setlayout borderlayout infopanel labelpanel borderlayout infopanel numberpanel borderlayout mainpanel borderlayout infopanel borderlayout borderlayout infopanel borderlayout public void update gui repaint synchronized this set minimum model get minimum set maximum model get maximum set average model get average set incoming model get current updategui setminimum getminimum setmaximum getmaximum setaverage getaverage setincoming getcurrent public string to string return show the samples analysis as a spline curve tostring private string format measure to display long measure string number string string value of measure if fill up with zeros for int i number string length i numbers to display i number string 0 number string non nls 1 return number string formatmeasuretodisplay numberstring valueof fill_up_with_zeros numberstring numbers_to_display numberstring numberstring numberstring private void set minimum long n string text this format measure to display n suffix ms this minimum number label set text text setminimum formatmeasuretodisplay suffix_ms minimumnumberlabel settext private void set maximum long n string text this format measure to display n suffix ms this maximum number label set text text setmaximum formatmeasuretodisplay suffix_ms maximumnumberlabel settext private void set average long n string text this format measure to display n suffix ms this average number label set text text setaverage formatmeasuretodisplay suffix_ms averagenumberlabel settext private void set incoming long n string text this format measure to display n suffix ms this incoming number label set text text setincoming formatmeasuretodisplay suffix_ms incomingnumberlabel settext public j panel get control panel todo is this needed return this jpanel getcontrolpanel public image get image image result graph create image graph get width graph get height graph paint component result get graphics return result getimage createimage getwidth getheight paintcomponent getgraphics protected int plot null public spline graph splinegraph clear the spline graph and get ready for the next wave public void clear last width 1 last height 1 plot null this repaint lastwidth lastheight public void paint component graphics g super paint component g dimension dimension this get size int width dimension width int height dimension height if model get data curve null g set color this get background g fill rect 0 0 width height g set color waiting color g draw string j meter utils get res string spline visualizer waitingmessage non nls 1 width 120 2 height height 12 2 return boolean resized true if width last width height last height dimension of the spline graph is the same resized false else dimension changed resized true last width width last height height this plot model get data curve get plots width height rounds int n plot length int cury plot 0 for int i 1 i n i g set color color black g draw line i 1 height cury 1 i height plot i 1 cury plot i paintcomponent paintcomponent getsize getdatacurve setcolor getbackground fillrect setcolor waiting_color drawstring jmeterutils getresstring spline_visualizer_waitingmessage lastwidth lastheight splinegraph lastwidth lastheight getdatacurve getplots setcolor drawline public report plan this j meter utils get res string report plan reportplan jmeterutils getresstring report_plan public report plan string name set name name set property new collection property report page report pages reportplan setname setproperty collectionproperty report_page reportpages public void set user defined variables arguments vars set property new test element property user defined variables vars setuserdefinedvariables setproperty testelementproperty user_defined_variables public string get basedir return get property as string basedir getbasedir getpropertyasstring public void set basedir string b set property basedir b setbasedir setproperty public map get user defined variables arguments args get variables return args get arguments as map getuserdefinedvariables getvariables getargumentsasmap private arguments get variables arguments args arguments get property user defined variables get object value if args null args new arguments set user defined variables args return args getvariables getproperty user_defined_variables getobjectvalue setuserdefinedvariables gets the static copy of the functional mode return mode public static boolean get functional mode return functional mode getfunctionalmode functionalmode public void add parameter string name string value get variables add argument name value addparameter getvariables addargument public static report plan create report plan string name if plan null if name null plan new report plan else plan new report plan name plan set property new string property test element gui class org apache jmeter control gui report gui return plan reportplan createreportplan reportplan reportplan setproperty stringproperty testelement gui_class reportgui public void add test element test element tg super add test element tg if tg instanceof thread group is running version add report page thread group tg addtestelement testelement addtestelement threadgroup isrunningversion addreportpage threadgroup public void addj meter component test element child if child instanceof thread group add report page thread group child addjmetercomponent testelement threadgroup addreportpage threadgroup gets the thread groups attribute of the test plan object return the thread groups value public collection get report pages return report pages threadgroups testplan threadgroups getreportpages reportpages adds a feature to the config element attribute of the test plan object param c the feature to be added to the config element attribute public void add config element config element c configs add c configelement testplan configelement addconfigelement configelement adds a feature to the thread group attribute of the test plan object param group the feature to be added to the thread group attribute public void add report page thread group group report pages add group threadgroup testplan threadgroup addreportpage threadgroup reportpages public void test ended try file server get file server close files catch io exception e log error problem closing files at end of test e testended fileserver getfileserver closefiles ioexception see org apache jmeter testelement test listener test ended java lang string public void test ended string host test ended testlistener testended testended testended see org apache jmeter testelement test listener test iteration start org apache jmeter engine event loop iteration event public void test iteration start loop iteration event event testlistener testiterationstart loopiterationevent testiterationstart loopiterationevent public void test started if get basedir null get basedir length 0 try file server get file server set basedir file server get file server get base dir get basedir catch io exception e log error failed to set file server base dir with get basedir e teststarted getbasedir getbasedir fileserver getfileserver setbasedir fileserver getfileserver getbasedir getbasedir ioexception getbasedir see org apache jmeter testelement test listener test started java lang string public void test started string host test started testlistener teststarted teststarted teststarted create a new loop control panel as a standalone component public while controller gui init loopcontrolpanel whilecontrollergui a newly created component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui param element the test element to configure public void configure test element element super configure element if element instanceof while controller the condition set text while controller element get condition testelement testelement whilecontroller thecondition settext whilecontroller getcondition implements j metergui component create test element public test element create test element while controller controller new while controller modify test element controller return controller jmeterguicomponent createtestelement testelement createtestelement whilecontroller whilecontroller modifytestelement implements j metergui component modify test element test element public void modify test element test element controller configure test element controller if controller instanceof while controller if the condition get text length 0 while controller controller set condition the condition get text else while controller controller set condition non nls 1 jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement whilecontroller thecondition gettext whilecontroller setcondition thecondition gettext whilecontroller setcondition implements j metergui component clear gui public void clear gui super clear gui the condition set text non nls 1 jmeterguicomponent cleargui cleargui cleargui thecondition settext invoked when an action occurs this implementation assumes that the target component is the infinite loops checkbox param event the event that has occurred public void action performed action event event new focus requester the condition actionperformed actionevent focusrequester thecondition public string get label resource return while controller title non nls 1 getlabelresource while_controller_title initialize the gui components and layout for this component private void init set layout new border layout 0 5 set border make border add make title panel border layout north j panel main panel new j panel new border layout main panel add create condition panel border layout north add main panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout jpanel mainpanel jpanel borderlayout mainpanel createconditionpanel borderlayout mainpanel borderlayout create a gui panel containing the condition todo make use of the field return a gui panel containing the condition components private j panel create condition panel j panel condition panel new j panel new border layout 5 0 condition label j label condition label new j label j meter utils get res string condition label condition panel add condition label border layout west text field this means exit if last sample failed the condition new j text field non nls 1 the condition set name condition condition label set label for the condition condition panel add the condition border layout center the condition add action listener this condition panel add box create horizontal strut condition label get preferred size width the condition get preferred size width border layout north return condition panel jpanel createconditionpanel jpanel conditionpanel jpanel borderlayout jlabel conditionlabel jlabel jmeterutils getresstring condition_label conditionpanel conditionlabel borderlayout thecondition jtextfield thecondition setname conditionlabel setlabelfor thecondition conditionpanel thecondition borderlayout thecondition addactionlistener conditionpanel createhorizontalstrut conditionlabel getpreferredsize thecondition getpreferredsize borderlayout conditionpanel create the coookie public cookie this false 0 false false create the coookie param expires this is in seconds public cookie string name string value string domain string path boolean secure long expires this name value domain path secure expires true true create the coookie param expires this is in seconds param has path was the path explicitly specified param has domain was the domain explicitly specified public cookie string name string value string domain string path boolean secure long expires boolean has path boolean has domain this name value domain path secure expires has path has domain default version haspath hasdomain haspath hasdomain haspath hasdomain default_version create a j meter cookie param name param value param domain param path param secure param expires this is in seconds param has path was the path explicitly specified param has domain was the domain explicitly specified param version cookie spec version public cookie string name string value string domain string path boolean secure long expires boolean has path boolean has domain int version this set name name this set value value this set domain domain this set path path this set secure secure this set expires expires this set path specified has path this set domain specified has domain this set version version jmeter haspath hasdomain haspath hasdomain setname setvalue setdomain setpath setsecure setexpires setpathspecified haspath setdomainspecified hasdomain setversion public void add config element config element config addconfigelement configelement get the value for this object public synchronized string get value return get property as string value getvalue getpropertyasstring set the value for this object public synchronized void set value string value this set property value value setvalue setproperty get the domain for this object public synchronized string get domain return get property as string domain getdomain getpropertyasstring set the domain for this object public synchronized void set domain string domain set property domain domain setdomain setproperty get the expiry time for the cookie return expiry time in seconds since the java epoch public synchronized long get expires return get property as long expires getexpires getpropertyaslong get the expiry time for the cookie return expiry time in milli seconds since the java epoch i e same as system current time millis public synchronized long get expires millis return get property as long expires 1000 currenttimemillis getexpiresmillis getpropertyaslong set the expiry time for the cookie param expires expiry time in seconds since the java epoch public synchronized void set expires long expires set property new long property expires expires setexpires setproperty longproperty get the secure for this object public synchronized boolean get secure return get property as boolean secure getsecure getpropertyasboolean set the secure for this object public synchronized void set secure boolean secure set property new boolean property secure secure setsecure setproperty booleanproperty get the path for this object public synchronized string get path return get property as string path getpath getpropertyasstring set the path for this object public synchronized void set path string path set property path path setpath setproperty public void set path specified boolean b set property path specified b setpathspecified setproperty path_specified public boolean is path specified return get property as boolean path specified ispathspecified getpropertyasboolean path_specified public void set domain specified boolean b set property domain specified b setdomainspecified setproperty domain_specified public boolean is domain specified return get property as boolean domain specified isdomainspecified getpropertyasboolean domain_specified creates a string representation of this cookie public string to string string buffer sb new string buffer 80 sb append get domain flag if all machines within a given domain can access the variable from http www cookiecentral com faq 3 5 sb append tab append true sb append tab append get path sb append tab append j orphan utils boolean tostring get secure sb append tab append get expires sb append tab append get name sb append tab append get value return sb to string tostring stringbuffer stringbuffer getdomain getpath jorphanutils booleantostring getsecure getexpires getname getvalue tostring return the version public synchronized int get version return get property as int version default version getversion getpropertyasint default_version param version the version to set public synchronized void set version int version set property version version default version setversion setproperty default_version private string name public simple variable string name this name name simplevariable public simple variable this name non nls 1 simplevariable public string get name return name getname public void set name string name this name name setname see org apache jmeter functions function execute public string to string string ret null j meter variables vars get variables if vars null ret vars get name if ret null return name return ret tostring jmetervariables getvariables private j meter variables get variables j meter context context j meter context service get context return context get variables jmetervariables getvariables jmetercontext jmetercontextservice getcontext getvariables prevent instantiation private action names actionnames public class bean shell listener bean info extends bean shell bean info support public bean shell listener bean info super bean shell listener class beanshelllistenerbeaninfo beanshellbeaninfosupport beanshelllistenerbeaninfo beanshelllistener public sample result sample entry entry sample result res new sample result res set sample label get name res set sampler data get content res set data type sample result text res sample start try text message msg create message if is oneway producer send msg res set successful true res set response data oneway request has no response data get bytes else if use tempory queue msg setjms reply to receive queue message reply msg executor send and receive msg if reply msg null res set successful false if logger is debug enabled logger debug no reply message received else if reply msg instanceof text message res set response data text message reply msg get text get bytes else res set response data reply msg to string get bytes res set successful true catch exception e logger warn e get localized message e res set response data new byte 0 res set successful false res sample end return res sampleresult sampleresult sampleresult setsamplelabel getname setsamplerdata getcontent setdatatype sampleresult samplestart textmessage createmessage isoneway setsuccessful setresponsedata getbytes usetemporyqueue setjmsreplyto receivequeue replymsg sendandreceive replymsg setsuccessful isdebugenabled replymsg textmessage setresponsedata textmessage replymsg gettext getbytes setresponsedata replymsg tostring getbytes setsuccessful getlocalizedmessage setresponsedata setsuccessful sampleend private text message create message throws jms exception if session null throw new illegal state exception session may not be null while creating message text message msg session create text message msg set text get content addjms properties msg return msg textmessage createmessage jmsexception illegalstateexception textmessage createtextmessage settext getcontent addjmsproperties private void addjms properties text message msg throws jms exception map map get arguments jms sampler jms properties get arguments as map iterator arg it map entry set iterator while arg it has next map entry me map entry arg it next string name string me get key string value string me get value if logger is debug enabled logger debug adding property name value webspheremq does not allow corr id to be set using set string property if jms correlationid equals ignore case name non nls 1 msg setjms correlationid value else msg set string property name value addjmsproperties textmessage jmsexception getarguments jmssampler jms_properties getargumentsasmap argit entryset argit hasnext argit getkey getvalue isdebugenabled setstringproperty jmscorrelationid equalsignorecase setjmscorrelationid setstringproperty public arguments getjms properties return get arguments jms sampler jms properties getjmsproperties getarguments jmssampler jms_properties public void setjms properties arguments args set property new test element property jms sampler jms properties args setjmsproperties setproperty testelementproperty jmssampler jms_properties public arguments getjndi properties return get arguments jms sampler jndi properties getjndiproperties getarguments jmssampler jndi_properties public void setjndi properties arguments args set property new test element property jms sampler jndi properties args setjndiproperties setproperty testelementproperty jmssampler jndi_properties public string get queue connection factory return get property as string queue connection factory jndi getqueueconnectionfactory getpropertyasstring queue_connection_factory_jndi public void set queue connection factory string qcf set property queue connection factory jndi qcf setqueueconnectionfactory setproperty queue_connection_factory_jndi public string get send queue return get property as string send queue getsendqueue getpropertyasstring send_queue public void set send queue string name set property send queue name setsendqueue setproperty send_queue public string get receive queue return get property as string receive queue getreceivequeue getpropertyasstring receive_queue public void set receive queue string name set property receive queue name setreceivequeue setproperty receive_queue public string get content return get property as string xml data getcontent getpropertyasstring xml_data public void set content string content set property xml data content setcontent setproperty xml_data public boolean is oneway return get property as boolean is one way isoneway getpropertyasboolean is_one_way public boolean is non persistent return get property as boolean is non persistent isnonpersistent getpropertyasboolean is_non_persistent public boolean is use req msg id as correl id return get property as boolean use req msgid as correlid isusereqmsgidascorrelid getpropertyasboolean use_req_msgid_as_correlid public string get initial context factory return get property as string jms sampler jndi initial context factory getinitialcontextfactory getpropertyasstring jmssampler jndi_initial_context_factory public string get context provider return get property as string jms sampler jndi context provider url getcontextprovider getpropertyasstring jmssampler jndi_context_provider_url public void set is oneway boolean is oneway set property new boolean property is one way is oneway setisoneway isoneway setproperty booleanproperty is_one_way isoneway public void set non persistent boolean value set property new boolean property is non persistent value setnonpersistent setproperty booleanproperty is_non_persistent public void set use req msg id as correl id boolean value set property new boolean property use req msgid as correlid value setusereqmsgidascorrelid setproperty booleanproperty use_req_msgid_as_correlid public string to string return get queue connection factory queue get send queue tostring getqueueconnectionfactory getsendqueue public void test iteration start loop iteration event event logger debug test iteration start testiterationstart loopiterationevent testiterationstart public void thread started log thread start context context null try context get initial context object obj context lookup get queue connection factory if obj instanceof queue connection factory string msg queue connection factory expected but got obj null null obj get class get name logger fatal error msg throw new illegal state exception msg queue connection factory factory queue connection factory obj queue queue queue context lookup get send queue send queue queue if use tempory queue receive queue queue context lookup get receive queue receiver thread receiver create receiver factory receive queue get principal context get credentials context string principal null string credentials null if use security properties principal get principal context credentials get credentials context if principal null credentials null connection factory create queue connection principal credentials else connection factory create queue connection session connection create queue session false session auto acknowledge if logger is debug enabled logger debug session created if get property as boolean is one way producer session create sender send queue if is non persistent producer set delivery mode delivery mode non persistent else if use tempory queue executor new temporary queue executor session send queue else producer session create sender send queue if is non persistent producer set delivery mode delivery mode non persistent executor new fixed queue executor producer get timeout is use req msg id as correl id if logger is debug enabled logger debug starting connection connection start if logger is debug enabled logger debug connection started catch jms exception e logger warn e get localized message e catch naming exception e logger warn e get localized message e finally if context null try context close catch naming exception ignored ignore threadstarted logthreadstart getinitialcontext getqueueconnectionfactory queueconnectionfactory queueconnectionfactory getclass getname fatalerror illegalstateexception queueconnectionfactory queueconnectionfactory getsendqueue sendqueue usetemporyqueue receivequeue getreceivequeue receiverthread createreceiver receivequeue getprincipal getcredentials use_security_properties getprincipal getcredentials createqueueconnection createqueueconnection createqueuesession auto_acknowledge isdebugenabled getpropertyasboolean is_one_way createsender sendqueue isnonpersistent setdeliverymode deliverymode non_persistent usetemporyqueue temporaryqueueexecutor sendqueue createsender sendqueue isnonpersistent setdeliverymode deliverymode non_persistent fixedqueueexecutor gettimeout isusereqmsgidascorrelid isdebugenabled isdebugenabled jmsexception getlocalizedmessage namingexception getlocalizedmessage namingexception private context get initial context throws naming exception hashtable table new hashtable if get initial context factory null get initial context factory trim length 0 if logger is debug enabled logger debug using initial context get initial context factory table put context initial context factory get initial context factory if get context provider null get context provider trim length 0 if logger is debug enabled logger debug using provider get context provider table put context provider url get context provider map map get arguments jms sampler jndi properties get arguments as map if logger is debug enabled if map is empty logger debug empty jndi properties else logger debug number of jndi properties map size iterator it map entry set iterator while it has next map entry me map entry it next table put me get key me get value context context new initial context table if logger is debug enabled print environment context return context getinitialcontext namingexception getinitialcontextfactory getinitialcontextfactory isdebugenabled initialcontext getinitialcontextfactory initial_context_factory getinitialcontextfactory getcontextprovider getcontextprovider isdebugenabled getcontextprovider provider_url getcontextprovider getarguments jmssampler jndi_properties getargumentsasmap isdebugenabled isempty entryset hasnext getkey getvalue initialcontext isdebugenabled printenvironment private void print environment context context throws naming exception hashtable env context get environment logger debug initial context properties enumeration keys env keys while keys has more elements string key string keys next element logger debug key env get key printenvironment namingexception getenvironment hasmoreelements nextelement private void log thread start if logger is debug enabled logger debug thread started new date logger debug jms sampler thread current thread get name hash code hash code logger debug qcf get queue connection factory send queue get send queue logger debug timeout get timeout logger debug use temporary queue use tempory queue logger debug reply queue get receive queue logthreadstart isdebugenabled jmssampler currentthread getname hashcode hashcode getqueueconnectionfactory sendqueue getsendqueue gettimeout usetemporyqueue getreceivequeue public int get timeout if get property as int timeout 1 return default timeout return get property as int timeout gettimeout getpropertyasint default_timeout getpropertyasint public void thread finished logger debug thread ended new date if session null try session close catch jms exception e logger info e get localized message if connection null try connection close catch jms exception e logger info e get localized message if receiver thread null receiver thread deactivate threadfinished jmsexception getlocalizedmessage jmsexception getlocalizedmessage receiverthread receiverthread private boolean use tempory queue string recv queue get receive queue return recv queue null recv queue trim length 0 usetemporyqueue recvqueue getreceivequeue recvqueue recvqueue public void set arguments arguments args set property new test element property jms sampler jms properties args setarguments setproperty testelementproperty jmssampler jms_properties public arguments get arguments string name return arguments get property name get object value getarguments getproperty getobjectvalue public void set timeout string s set property jms sampler timeout s settimeout setproperty jmssampler param string public void set initial context factory string string set property jndi initial context factory string setinitialcontextfactory setproperty jndi_initial_context_factory param string public void set context provider string string set property jndi context provider url string setcontextprovider setproperty jndi_context_provider_url get the principal from the context property java naming security principal param context return throws naming exception private string get principal context context throws naming exception hashtable env context get environment return string env get java naming security principal non nls 1 namingexception getprincipal namingexception getenvironment get the credentials from the context property java naming security credentials param context return throws naming exception private string get credentials context context throws naming exception hashtable env context get environment return string env get java naming security credentials non nls 1 namingexception getcredentials namingexception getenvironment public class test generic controller extends j meter test case public test generic controller string name super name testgenericcontroller jmetertestcase testgenericcontroller public void test processing throws exception test log debug testing generic controller generic controller controller new generic controller generic controller sub 1 new generic controller sub 1 add test element new test sampler one sub 1 add test element new test sampler two controller add test element sub 1 controller add test element new test sampler three generic controller sub 2 new generic controller generic controller sub 3 new generic controller sub 2 add test element new test sampler four sub 3 add test element new test sampler five sub 3 add test element new test sampler six sub 2 add test element sub 3 sub 2 add test element new test sampler seven controller add test element sub 2 string order new string one two three four five six seven int counter 7 controller initialize for int i 0 i 2 i assert equals 7 counter counter 0 test element sampler null while sampler controller next null assert equals order counter sampler get name testprocessing testlog genericcontroller genericcontroller genericcontroller sub_1 genericcontroller sub_1 addtestelement testsampler sub_1 addtestelement testsampler addtestelement sub_1 addtestelement testsampler genericcontroller sub_2 genericcontroller genericcontroller sub_3 genericcontroller sub_2 addtestelement testsampler sub_3 addtestelement testsampler sub_3 addtestelement testsampler sub_2 addtestelement sub_3 sub_2 addtestelement testsampler addtestelement sub_2 assertequals testelement assertequals getname default constructor takes a string url public wsdl helper string url throws malformedurl exception try wsdlurl new url url catch malformedurl exception exception throw exception wsdlhelper malformedurlexception malformedurlexception public wsdl helper string url auth manager auth throws malformedurl exception this url this auth auth wsdlhelper authmanager malformedurlexception returns the url return the url public url geturl return this wsdlurl return the protocol from the url this is needed so that https works as expected public string get protocol return this bindingurl get protocol getprotocol getprotocol return the host in the wsdl binding address public string get binding host return this bindingurl get host getbindinghost gethost return the path in the wsdl for the binding address public string get binding path return this bindingurl get path getbindingpath getpath return the port for the binding address public int get binding port return this bindingurl get port getbindingport getport returns the binding point for the webservice right now it naively assumes there s only one binding point with numerous soap operations return string public string get binding try node list services this wsdldoc get elements by tag name service if services get length 0 services this wsdldoc get elements by tag name wsdl service the document should only have one service node if it doesn t it may not work element node element services item 0 node list ports node get elements by tag name port if ports get length 0 ports node get elements by tag name wsdl port for int idx 0 idx ports get length idx element pnode element ports item idx notused string portname pnode get attribute name used to check binding but now it doesn t it was failing when wsdl did not using binding as expected node list servlist pnode get elements by tag name soap address check wsdlsoap if servlist get length 0 servlist pnode get elements by tag name wsdlsoap address if servlist get length 0 servlist pnode get elements by tag name soap address element addr element servlist item 0 this soapbinding addr get attribute location this bindingurl new url this soapbinding return this soapbinding return null catch exception exception return null getbinding nodelist getelementsbytagname getlength getelementsbytagname nodelist getelementsbytagname getlength getelementsbytagname getlength getattribute nodelist getelementsbytagname getlength getelementsbytagname getlength getelementsbytagname getattribute method is used internally to connect to the url it s protected therefore external classes should use parse to get the resource at the given location throws io exception protected void connect throws io exception try conn wsdlurl open connection in the rare case the wsdl is protected and requires authentication use the auth manager to set the authorization basic and digest authorization are pretty weak and don t provide real security if conn instanceof httpurl connection this auth null this auth get auth header forurl this wsdlurl null conn set request property authorization this auth get auth header forurl this wsdlurl catch io exception exception throw exception ioexception ioexception openconnection authmanager httpurlconnection getauthheaderforurl setrequestproperty getauthheaderforurl ioexception we try to close the connection to make sure it doesn t hang around protected void close try if conn null conn get input stream close catch io exception ignored do nothing getinputstream ioexception method is used internally to parse the input stream and build the document using javax xml parser api protected void build document throws parser configuration exception io exception sax exception try document builder factory dbfactory document builder factory new instance document builder docbuild dbfactory new document builder wsdldoc docbuild parse conn get input stream catch parser configuration exception exception throw exception catch io exception exception throw exception catch sax exception exception throw exception inputstream builddocument parserconfigurationexception ioexception saxexception documentbuilderfactory documentbuilderfactory newinstance documentbuilder newdocumentbuilder getinputstream parserconfigurationexception ioexception saxexception call this method to retrieve the wsdl this method must be called otherwise a connection to the url won t be made and the stream won t be parsed public void parse throws wsdl exception try this connect this build document soapops this get operations catch io exception exception throw new wsdl exception exception catch sax exception exception throw new wsdl exception exception catch parser configuration exception exception throw new wsdl exception exception finally this close wsdlexception builddocument getoperations ioexception wsdlexception saxexception wsdlexception parserconfigurationexception wsdlexception get a list of the web methods as a string array public string get web methods for int idx 0 idx soapops length idx get the node node act node soapops idx get the soap operation node list opers element act get elements by tag name soap operation if opers get length 0 opers element act get elements by tag name wsdlsoap operation if opers get length 0 opers element act get elements by tag name wsdl operation if opers get length 0 opers element act get elements by tag name operation there should only be one soap operation node per operation element op element opers item 0 string value if op null value op get attribute soap action else value string key element act get attribute name this actions put key value set keys this actions key set string stringmeth new string keys size object string keys keys to array system arraycopy string keys 0 stringmeth 0 keys size return stringmeth getwebmethods nodelist getelementsbytagname getlength getelementsbytagname getlength getelementsbytagname getlength getelementsbytagname getattribute soapaction getattribute keyset stringkeys toarray stringkeys return the soap action matching the operation name public string get soap action string key return string this actions get key getsoapaction get the wsdl document public document getwsdl document return wsdldoc getwsdldocument method will look at the binding nodes and see if the first child is a soap binding if it is it adds it to an array return node public object getsoap bindings array list list new array list node list bindings wsdldoc get elements by tag name binding string soap bind soap binding if bindings get length 0 bindings wsdldoc get elements by tag name wsdl binding if wsdldoc get elements by tag name soap bind get length 0 soap bind wsdlsoap binding if wsdldoc get elements by tag name soap bind get length 0 soap bind soap binding for int idx 0 idx bindings get length idx element nd element bindings item idx node list slist nd get elements by tag name soap bind if slist get length 0 notused element soapbind element slist item 0 this bindname nd get attribute name list add nd if list size 0 return list to array return new object 0 getsoapbindings arraylist arraylist nodelist getelementsbytagname soapbind getlength getelementsbytagname getelementsbytagname soapbind getlength soapbind getelementsbytagname soapbind getlength soapbind getlength nodelist getelementsbytagname soapbind getlength getattribute toarray look at the bindings with soap operations and get the soap operations since wsdl may describe multiple bindings and each binding may have multiple soap operations we iterate through the binding nodes with a first child that is a soap binding if a wsdl doesn t use the same formatting convention it is possible we may not get a list of all the soap operations if that is the case getsoap bindings will need to be changed i should double check the wsdl spec to see what the official requirement is another option is to get all operation nodes and check to see if the first child is a soap operation the benefit of not getting all operation nodes is wsdl could contain duplicate operations that are not soap methods if there are a large number of methods and half of them are http operations getting all operations could slow things down return node public object get operations object res this getsoap bindings array list ops new array list first we iterate through the bindings for int idx 0 idx res length idx element one element res idx node list opnodes one get elements by tag name operation string soap op soap operation if opnodes get length 0 opnodes one get elements by tag name wsdl operation if one get elements by tag name soap op get length 0 soap op wsdlsoap operation now we iterate through the operations for int idz 0 idz opnodes get length idz if the first child is soap operation we add it to the array element child element opnodes item idz todo the following code looks wrong it does the same in both cases node list soapnode child get elements by tag name soap op if soapnode get length 0 ops add child else ops add child return ops to array getsoapbindings getoperations getsoapbindings arraylist arraylist nodelist getelementsbytagname soapop getlength getelementsbytagname getelementsbytagname soapop getlength soapop getlength nodelist getelementsbytagname soapop getlength toarray simple test for the class uses bidbuy wsdl from apache s soap driver examples param args public static void main string args try wsdl helper help new wsdl helper http localhost ws test ws test asmx wsdl new wsdl helper http localhost axiswsdl xml new wsdl helper http localhost 8080 service gateway wsdl new wsdl helper http services bio ifi lmu de 1046 prothesaurus services biological name service wsdl long start system current time millis help parse string methods help get web methods system out println el system current time millis start for int idx 0 idx methods length idx system out println method name methods idx system out println service url help get binding system out println protocol help get protocol system out println port help geturl get port catch exception exception system out println main method catch exception print stack trace wsdlhelper wsdlhelper wstest wstest wsdlhelper wsdlhelper servicegateway wsdlhelper biologicalnameservice currenttimemillis getwebmethods currenttimemillis getbinding getprotocol getport printstacktrace private constructor to permit instantiation only from within this class use link get instance to retrieve a singleton instance private report gui package j meter utils add locale change listener this getinstance reportguipackage jmeterutils addlocalechangelistener retrieve the singleton gui package instance return the gui package instance public static report gui package get instance if gui pack null log error report gui package is null return gui pack guipackage guipackage reportguipackage getinstance guipack reportguipackage guipack when gui package is requested for the first time it should be given handles to j meter s tree listener and tree model param listener the tree listener for j meter s test tree param tree model the model for j meter s test tree return gui package public static report gui package get instance report tree listener listener report tree model tree model if gui pack null gui pack new report gui package gui pack set tree listener listener gui pack set tree model tree model return gui pack guipackage jmeter treemodel treelistener jmeter treemodel jmeter guipackage reportguipackage getinstance reporttreelistener reporttreemodel treemodel guipack guipack reportguipackage guipack settreelistener guipack settreemodel treemodel guipack get a j metergui component for the specified test element if the gui has already been created that instance will be returned otherwise if a gui component of the same type has been created and the component is not marked as an link unshared component that shared component will be returned otherwise a new instance of the component will be created the test element s gui class property will be used to determine the appropriate type of gui component to use param node the test element which this gui is being created for return the gui component corresponding to the specified test element public j metergui component get gui test element node string test class name node get property as string test element test class string gui class name node get property as string test element gui class try class test class if test class name equals test class node get class else test class class for name test class name class gui class null if gui class name equals gui class class for name gui class name return get gui node gui class test class catch class not found exception e log error could not get gui for node e return null jmeterguicomponent unsharedcomponent testelement gui_class jmeterguicomponent getgui testelement testclassname getpropertyasstring testelement test_class guiclassname getpropertyasstring testelement gui_class testclass testclassname testclass getclass testclass forname testclassname guiclass guiclassname guiclass forname guiclassname getgui guiclass testclass classnotfoundexception get a j metergui component for the specified test element if the gui has already been created that instance will be returned otherwise if a gui component of the same type has been created and the component is not marked as an link unshared component that shared component will be returned otherwise a new instance of the component will be created param node the test element which this gui is being created for param gui class the fully qualifed class name of the gui component which will be created if it doesn t already exist param test class the fully qualifed class name of the test elements which have to be edited by the returned gui component return the gui component corresponding to the specified test element public j metergui component get gui test element node class gui class class test class try j metergui component comp j metergui component nodes to gui get node if comp null comp get gui from cache gui class test class nodes to gui put node comp log debug gui retrieved comp return comp catch exception e log error problem retrieving gui e return null jmeterguicomponent unsharedcomponent guiclass testclass jmeterguicomponent getgui testelement guiclass testclass jmeterguicomponent jmeterguicomponent nodestogui getguifromcache guiclass testclass nodestogui remove a test element from the tree this removes the reference to any associated gui component param node the test element being removed public void remove node test element node nodes to gui remove node removenode testelement nodestogui convenience method for grabbing the gui for the current node return the gui component associated with the currently selected node public j metergui component get current gui try update current node test element cur node tree listener get current node get test element j metergui component comp get gui cur node comp clear gui log debug updating gui to new node comp configure cur node current node updated false return comp catch exception e log error problem retrieving gui e return null jmeterguicomponent getcurrentgui updatecurrentnode testelement curnode treelistener getcurrentnode gettestelement jmeterguicomponent getgui curnode cleargui curnode currentnodeupdated find the j meter tree node for a certain test element object param user object the test element to search for return the tree node associated with the test element public report tree node get node of test element user object return tree model get node of user object jmetertreenode testelement userobject reporttreenode getnodeof testelement userobject treemodel getnodeof userobject create a test element corresponding to the specified gui class param gui class the fully qualified class name of the gui component or a test bean class for test beangu is param test class the fully qualified class name of the test elements edited by this gui component return the test element corresponding to the specified gui class public test element create test element class gui class class test class try j metergui component comp get gui from cache gui class test class comp clear gui test element node comp create test element nodes to gui put node comp return node catch exception e log error problem retrieving gui e return null testelement guiclass testbean testbeanguis testclass testelement createtestelement guiclass testclass jmeterguicomponent getguifromcache guiclass testclass cleargui testelement createtestelement nodestogui create a test element for a gui or test bean class p this is a utility method to help actions do with one single string parameter param obj class the fully qualified class name of the gui component or of the test bean subclass for which a test beangui is wanted return the test element corresponding to the specified gui class public test element create test element string obj class j metergui component comp class c try c class for name obj class if test bean class is assignable from c comp get gui from cache test beangui class c else comp get gui from cache c null comp clear gui test element node comp create test element nodes to gui put node comp return node catch no class def found error e log error problem retrieving gui for obj class e throw new runtime exception e to string probably a missing jar catch class not found exception e log error problem retrieving gui for obj class e throw new runtime exception e to string programming error bail out catch instantiation exception e log error problem retrieving gui for obj class e throw new runtime exception e to string programming error bail out catch illegal access exception e log error problem retrieving gui for obj class e throw new runtime exception e to string programming error bail out testelement testbean objclass testbean testbeangui testelement createtestelement objclass jmeterguicomponent forname objclass testbean isassignablefrom getguifromcache testbeangui getguifromcache cleargui testelement createtestelement nodestogui noclassdeffounderror objclass runtimeexception tostring classnotfoundexception objclass runtimeexception tostring instantiationexception objclass runtimeexception tostring illegalaccessexception objclass runtimeexception tostring get an instance of the specified j metergui component class if an instance of the gui class has previously been created and it is not marked as an link unshared component that shared instance will be returned otherwise a new instance of the component will be created and shared components will be cached for future retrieval param gui class the fully qualified class name of the gui component this class must implement j metergui component param test class the fully qualified class name of the test elements edited by this gui component this class must implement test element return an instance of the specified class throws instantiation exception if an instance of the object cannot be created throws illegal access exception if access rights do not allow the default constructor to be called throws class not found exception if the specified gui class cannot be found private j metergui component get gui from cache class gui class class test class throws instantiation exception illegal access exception j metergui component comp if gui class test beangui class comp test beangui test beangu is get test class if comp null comp new test beangui test class test beangu is put test class comp else comp j metergui component guis get gui class if comp null comp j metergui component gui class new instance if comp instanceof unshared component guis put gui class comp return comp jmeterguicomponent unsharedcomponent guiclass jmeterguicomponent testclass testelement instantiationexception illegalaccessexception classnotfoundexception jmeterguicomponent getguifromcache guiclass testclass instantiationexception illegalaccessexception jmeterguicomponent guiclass testbeangui testbeangui testbeanguis testclass testbeangui testclass testbeanguis testclass jmeterguicomponent guiclass jmeterguicomponent guiclass newinstance unsharedcomponent guiclass update the gui for the currently selected node the gui component is configured to reflect the settings in the current tree node public void update current gui update current node current node tree listener get current node test element element current node get test element j metergui component comp get gui element comp configure element current node updated false updatecurrentgui updatecurrentnode currentnode treelistener getcurrentnode testelement currentnode gettestelement jmeterguicomponent getgui currentnodeupdated this method should be called in order for gui package to change the current node this will save any changes made to the earlier node before choosing the new node public void update current node try if current node null current node updated log debug updating current node current node get name j metergui component comp get gui current node get test element test element el current node get test element comp modify test element el if current node tree listener get current node current node updated true current node tree listener get current node catch exception e log error problem retrieving gui e guipackage updatecurrentnode currentnode currentnodeupdated currentnode getname jmeterguicomponent getgui currentnode gettestelement testelement currentnode gettestelement modifytestelement currentnode treelistener getcurrentnode currentnodeupdated currentnode treelistener getcurrentnode public report tree node get current node return tree listener get current node reporttreenode getcurrentnode treelistener getcurrentnode public test element get current element return get current node get test element testelement getcurrentelement getcurrentnode gettestelement the dirty property is a flag that indicates whether there are parts of j meter s test tree that the user has not saved since last modification various link command actions set this property when components are modified created saved param dirty the new value of the dirty flag public void set dirty boolean dirty this dirty dirty jmeter setdirty retrieves the state of the dirty property a flag that indicates if there are test tree components that have been modified since they were last saved return true if some tree components have been modified since they were last saved false otherwise public boolean is dirty return dirty isdirty add a subtree to the currently selected node param sub tree the subtree to add return the resulting subtree starting with the currently selected node throws illegal user action exception if a subtree cannot be added to the currently selected node public hash tree add sub tree hash tree sub tree throws illegal user action exception return tree model add sub tree sub tree tree listener get current node subtree illegaluseractionexception hashtree addsubtree hashtree subtree illegaluseractionexception treemodel addsubtree subtree treelistener getcurrentnode get the currently selected subtree return the subtree of the currently selected node public hash tree get current sub tree return tree model get current sub tree tree listener get current node hashtree getcurrentsubtree treemodel getcurrentsubtree treelistener getcurrentnode get the model for j meter s test tree return the j meter tree model public report tree model get tree model return tree model jmeter jmeter reporttreemodel gettreemodel treemodel set the model for j meter s test tree param new tree model the new j meter tree model public void set tree model report tree model new tree model tree model new tree model jmeter newtreemodel jmeter settreemodel reporttreemodel newtreemodel treemodel newtreemodel get a value replacer for the test tree return a value replacer configured for the test tree public value replacer get replacer return new value replacer report plan report tree node get tree model get report plan get array 0 get test element valuereplacer valuereplacer valuereplacer getreplacer valuereplacer reportplan reporttreenode gettreemodel getreportplan getarray gettestelement set the main j meter frame param new main frame the new j meter main frame public void set main frame report main frame new main frame this main frame new main frame jmeter newmainframe jmeter setmainframe reportmainframe newmainframe mainframe newmainframe get the main j meter frame return the main j meter frame public report main frame get main frame return this main frame jmeter jmeter reportmainframe getmainframe mainframe set the listener for j meter s test tree param new tree listener the new j meter test tree listener public void set tree listener report tree listener new tree listener tree listener new tree listener jmeter newtreelistener jmeter settreelistener reporttreelistener newtreelistener treelistener newtreelistener get the listener for j meter s test tree return the j meter test tree listener public report tree listener get tree listener return tree listener jmeter jmeter reporttreelistener gettreelistener treelistener display the specified popup menu with the source component and location from the specified mouse event param e the mouse event causing this popup to be displayed param popup the popup menu to display public void display pop up mouse event e j popup menu popup display pop up component e get source e popup displaypopup mouseevent jpopupmenu displaypopup getsource display the specified popup menu at the location specified by a mouse event with the specified source component param invoker the source component param e the mouse event causing this popup to be displayed param popup the popup menu to display public void display pop up component invoker mouse event e j popup menu popup if popup null log debug showing pop up for invoker at x y e getx e gety popup pack popup show invoker e getx e gety popup set visible true popup request focus displaypopup mouseevent jpopupmenu setvisible requestfocus public void locale changed locale change event event f irst make sure we save the content of the current gui since we will flush it away update current node forget about all gu is we ve created so far we ll need to re created them all guis new hash map nodes to gui new hash map test beangu is new hash map bean info objects also contain locale sensitive data flush them away introspector flush caches now put the current gui in place this code was copied from the edit command action we can t just trigger the action because that would populate the current node with the contents of the new gui which is empty report main frame mf get main frame fetch once if mf null probably caused by unit testing on headless system log warn mainframe is null else mf set main panel javax swing j component get current gui mf set edit menu get tree listener get current node create popup menu localechanged localechangeevent first updatecurrentnode guis hashmap nodestogui hashmap testbeanguis hashmap beaninfo flushcaches editcommand reportmainframe getmainframe setmainpanel jcomponent getcurrentgui seteditmenu gettreelistener getcurrentnode createpopupmenu sets the filepath of the current test plan it s shown in the main frame title and used on saving param f public void set report plan file string f report plan file f report gui package get instance get main frame set extended frame title report plan file try file server get file server set basedir report plan file catch io exception e1 log error failure setting file server s base dir e1 setreportplanfile reportplanfile reportguipackage getinstance getmainframe setextendedframetitle reportplanfile fileserver getfileserver setbasedir reportplanfile ioexception public string get report plan file return report plan file getreportplanfile reportplanfile public html parse exception super htmlparseexception param message public html parse exception string message super message htmlparseexception param cause public html parse exception throwable cause jdk1 4 super cause super saved cause cause htmlparseexception savedcause param message param cause public html parse exception string message throwable cause jdk1 4 super message cause super message saved cause cause htmlparseexception savedcause local verstion of get cause for jdk1 3 support public throwable get cause return saved cause getcause getcause savedcause used by http test sample gui public multipart url config gui super init httptestsamplegui multiparturlconfiggui not currently used public multipart url config gui boolean value super value init multiparturlconfiggui public void modify test element test element sampler super modify test element sampler files panel modify test element sampler modifytestelement testelement modifytestelement filespanel modifytestelement public void configure test element el super configure el files panel configure el testelement filespanel private void init called from ctor so must not be overridable this set layout new border layout web request panel j panel web request panel new j panel web request panel set layout new border layout web request panel set border border factory create titled border border factory create etched border j meter utils get res string web request non nls 1 j panel north panel new j panel north panel set layout new box layout north panel box layout y axis north panel add get protocol and method panel north panel add get path panel web request panel add north panel border layout north web request panel add get parameter panel border layout center web request panel add gethttp file args panel border layout south this add get web server timeout panel border layout north this add web request panel border layout center setlayout borderlayout jpanel webrequestpanel jpanel webrequestpanel setlayout borderlayout webrequestpanel setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring web_request jpanel northpanel jpanel northpanel setlayout boxlayout northpanel boxlayout y_axis northpanel getprotocolandmethodpanel northpanel getpathpanel webrequestpanel northpanel borderlayout webrequestpanel getparameterpanel borderlayout webrequestpanel gethttpfileargspanel borderlayout getwebservertimeoutpanel borderlayout webrequestpanel borderlayout private j panel gethttp file args panel files panel new http file args panel j meter utils get res string send file non nls 1 return files panel jpanel gethttpfileargspanel filespanel httpfileargspanel jmeterutils getresstring send_file filespanel see org apache jmeter protocol http config gui url config gui clear public void clear super clear files panel clear urlconfiggui filespanel private int no failing samples 0 public transaction sampler log warn constructor only intended for use in testing nofailingsamples transactionsampler public transaction sampler transaction controller controller string name transaction controller controller set name name ensure name is available for debugging transaction sample result new sample result transaction sample result set sample label name assume success transaction sample result set successful true transaction sample result sample start transactionsampler transactioncontroller transactioncontroller setname transactionsampleresult sampleresult transactionsampleresult setsamplelabel transactionsampleresult setsuccessful transactionsampleresult samplestart one cannot sample the transaction sampler directly public sample result sample entry e throw new runtime exception cannot sample transaction sampler directly it is the j meter thread which knows how to sample a real sampler transactionsampler sampleresult runtimeexception transactionsampler jmeterthread public sampler get sub sampler return sub sampler getsubsampler subsampler public sample result get transaction result return transaction sample result sampleresult gettransactionresult transactionsampleresult public transaction controller get transaction controller return transaction controller transactioncontroller gettransactioncontroller transactioncontroller public boolean is transaction done return transaction done istransactiondone transactiondone public void add sub sampler result sample result res another subsample for the transaction calls the transaction fails if any sub sample fails if res is successful transaction sample result set successful false no failing samples add the sub result to the transaction result transaction sample result add sub result res addsubsamplerresult sampleresult issuccessful transactionsampleresult setsuccessful nofailingsamples transactionsampleresult addsubresult protected void set transaction done this transaction done true set the overall status for the transaction sample todo improve e g by adding counts to the sample result class transaction sample result set response message number of samples in transaction calls number of failing samples no failing samples if transaction sample result is successful transaction sample result set response codeok settransactiondone transactiondone sampleresult transactionsampleresult setresponsemessage nofailingsamples transactionsampleresult issuccessful transactionsampleresult setresponsecodeok protected void set sub sampler sampler sub sampler this sub sampler sub sampler setsubsampler subsampler subsampler subsampler public static void stop engine now if engine null may be null if called from unit test engine stop test true stopenginenow stoptest public static void stop engine if engine null may be null if called from unit test engine stop test false stopengine stoptest public static synchronized void register test listener tl test list add tl testlistener testlist public static boolean stop thread string thread name return stop thread thread name false stopthread threadname stopthread threadname public static boolean stop thread now string thread name return stop thread thread name true stopthreadnow threadname stopthread threadname private static boolean stop thread string thread name boolean now if engine null return false e g not yet started j meter thread thrd null synchronized engine all threads protect iterator iterator iter engine all threads key set iterator while iter has next thrd j meter thread iter next if thrd get thread name equals thread name break found matching thread if thrd null thrd stop thrd interrupt if now thread t thread engine all threads get thrd if t null t interrupt return true return false stopthread threadname jmeterthread allthreads allthreads keyset hasnext jmeterthread getthreadname threadname allthreads end of code to allow engine to be controlled remotely public standardj meter engine this null standardjmeterengine public standardj meter engine string host this host host this all threads collections synchronized map new hash map hack to allow external control engine this standardjmeterengine allthreads synchronizedmap hashmap public void configure hash tree test tree test test tree hashtree testtree testtree todo in java1 5 perhaps we can use thread set uncaught exception handler instead private static class my thread group extends java lang thread group public my thread group string s super s setuncaughtexceptionhandler mythreadgroup threadgroup mythreadgroup public void uncaught exception thread t throwable e if e instanceof thread death log error uncaught exception e system err println uncaught exception e see log file for details uncaughtexception threaddeath public void run test throws j meter engine exception if host null long now system current time millis system out println starting the test on host host new date now now try thread running thread new thread new my thread group j meter thread group this running thread start if j meter is nongui udp port 1000 thread waiter new thread public void run wait for signals waiter set daemon true waiter start catch exception err stop test string writer string new string writer print writer writer new print writer string err print stack trace writer throw new j meter engine exception string to string runtest jmeterengineexception currenttimemillis runningthread mythreadgroup jmeterthreadgroup runningthread jmeter isnongui udp_port waitforsignals setdaemon stoptest stringwriter stringwriter printwriter printwriter printstacktrace jmeterengineexception tostring if j meter is nongui udp port 1000 thread waiter new thread public void run wait for signals jmeter isnongui udp_port waitforsignals private void wait for signals byte buf new byte 80 datagram socket socket null system out println waiting for possible shutdown message on port udp port try socket new datagram socket udp port datagram packet request new datagram packet buf buf length while true socket receive request inet address address request get address only accept commands from the local host if address is loopback address string command new string request get data request get offset request get length ascii system out println command command received from address log info command command received from address if command equals stop test now stop test else if command equals shutdown ask threads to stop else catch exception e e print stack trace finally if socket null socket close waitforsignals datagramsocket udp_port datagramsocket udp_port datagrampacket datagrampacket inetaddress getaddress isloopbackaddress getdata getoffset getlength stoptestnow stoptest askthreadstostop printstacktrace private void remove thread groups list elements iterator iter elements iterator while iter has next object item iter next if item instanceof thread group iter remove else if item instanceof test element iter remove removethreadgroups hasnext threadgroup testelement private void notify test listeners of start search by class test listeners iterator iter test listeners get search results iterator while iter has next test listener tl test listener iter next if tl instanceof test bean test bean helper prepare test element tl if host null tl test started else tl test started host notifytestlistenersofstart searchbyclass testlisteners testlisteners getsearchresults hasnext testlistener testlistener testbean testbeanhelper testelement teststarted teststarted private void notify test listeners of end search by class test listeners log info notifying test listeners of end of test iterator iter test listeners get search results iterator while iter has next test listener tl test listener iter next try if host null tl test ended else tl test ended host catch exception e log warn error encountered during shutdown of tl to string e log info test has ended if host null long now system current time millis system out println finished the test on host host new date now now if exit after test exit notifytestlistenersofend searchbyclass testlisteners testlisteners getsearchresults hasnext testlistener testlistener testended testended tostring currenttimemillis exitaftertest private listed hash tree clone tree listed hash tree tree tree cloner cloner new tree cloner true tree traverse cloner return cloner get cloned tree listedhashtree clonetree listedhashtree treecloner treecloner getclonedtree public void reset if running stop test stoptest called by j meter thread when it finishes public synchronized void thread finished j meter thread thread log info ending thread thread get thread name all threads remove thread if starting groups all threads size 0 all threads have exitted new thread ensure that the current sampler thread can exit cleanly public void run log info stopping test notify test listeners of end test listeners save start jmeter threadfinished jmeterthread getthreadname allthreads startinggroups allthreads notifytestlistenersofend testlistenerssave if starting groups all threads size 0 all threads have exitted new thread ensure that the current sampler thread can exit cleanly public void run log info stopping test notify test listeners of end test listeners save startinggroups allthreads notifytestlistenersofend testlistenerssave public synchronized void stop test stop test true stoptest stoptest public synchronized void stop test boolean b thread stop thread new thread new stop test b stop thread start stoptest stopthread stoptest stopthread private final boolean now private stop test boolean b now b stoptest public void run running false engine null if now tell threads to stop pause 10 all threads size boolean stopped verify threads stopped if stopped notify test listeners of end test listeners save if j meter is nongui exit else j meter utils report error to user j meter utils get res string stopping test failed j meter utils get res string stopping test title todo perhaps allow option to stop them else will be done by thread finished else stop all threads tellthreadstostop allthreads verifythreadsstopped notifytestlistenersofend testlistenerssave jmeter isnongui jmeterutils reporterrortouser jmeterutils getresstring stopping_test_failed jmeterutils getresstring stopping_test_title threadfinished stopallthreads public void run log info running the test running true search by class test plan new search by class test plan class test traverse test plan object plan test plan get search results to array if plan length 0 system err println could not find the test plan log error could not find the test plan system exit 1 if test plan plan 0 is serialized serialized true j meter context service start test try pre compiler compiler new pre compiler test traverse compiler catch runtime exception e log error error occurred compiling the tree e j meter utils report error to user error occurred compiling the tree see log file return no point continuing notification of test listeners needs to happen after function replacement but before setting running version to true search by class test listeners new search by class test listener class test traverse test listeners merge in any additional test listeners currently only used by the function parser test listeners get search results add all test list test list clear no longer needed test listeners save test listeners if start listeners later notify test listeners of start test listeners test traverse new turn elements on if start listeners later notify test listeners of start test listeners list test level elements new linked list test list test get array 0 remove thread groups test level elements search by class searcher new search by class thread group class test traverse searcher test compiler initialize for each thread group generate threads hand each thread the sampler controller and the listeners and the timer iterator iter searcher get search results iterator here s where the test really starts run a full gc now it s no harm at all just delays test start by a tiny amount and hitting one too early in the test can impair results for short tests system gc listener notifier notifier new listener notifier j meter context service get context set sampling started true int group count 0 j meter context service clear total threads starting groups true while running iter has next for each thread group group count thread group group thread group iter next int num threads group get num threads j meter context service add total threads num threads boolean on error stop test group get on error stop test boolean on error stop test now group get on error stop test now boolean on error stop thread group get on error stop thread string group name group get name int ramp up group get ramp up float per thread delay float ramp up 1000 float num threads log info starting num threads threads for group group name ramp up ramp up if on error stop test log info test will stop on error else if on error stop test now log info test will stop abruptly on error else if on error stop thread log info thread will stop on error else log info thread will continue on error listed hash tree thread group tree listed hash tree searcher get sub tree group thread group tree add group test level elements for int i 0 running i num threads i final j meter thread jmeter thread new j meter thread clone tree thread group tree this notifier jmeter thread set thread num i jmeter thread set thread group group jmeter thread set initial context j meter context service get context jmeter thread set initial delay int per thread delay i final string thread name group name group count i 1 jmeter thread set thread name thread name schedule thread jmeter thread group set up variables for stop handling jmeter thread set engine this jmeter thread set on error stop test on error stop test jmeter thread set on error stop test now on error stop test now jmeter thread set on error stop thread on error stop thread thread new thread new thread jmeter thread new thread set name thread name all threads put jmeter thread new thread new thread start end of thread startup for this thread group if serialized iter has next log info waiting for thread group group name to finish before starting next group while running all threads size 0 pause 1000 end of thread groups if running log info all threads have been started else log info test stopped no more threads will be started starting groups false searchbyclass testplan searchbyclass testplan testplan testplan getsearchresults toarray testplan testplan testplan isserialized jmetercontextservice starttest precompiler precompiler runtimeexception jmeterutils reporterrortouser runningversion searchbyclass testlisteners searchbyclass testlistener testlisteners testlisteners getsearchresults addall testlist testlist testlistenerssave testlisteners startlistenerslater notifytestlistenersofstart testlisteners turnelementson startlistenerslater notifytestlistenersofstart testlisteners testlevelelements linkedlist getarray removethreadgroups testlevelelements searchbyclass searchbyclass threadgroup testcompiler getsearchresults listenernotifier listenernotifier jmetercontextservice getcontext setsamplingstarted groupcount jmetercontextservice cleartotalthreads startinggroups hasnext groupcount threadgroup threadgroup numthreads getnumthreads jmetercontextservice addtotalthreads numthreads onerrorstoptest getonerrorstoptest onerrorstoptestnow getonerrorstoptestnow onerrorstopthread getonerrorstopthread groupname getname rampup getrampup perthreaddelay rampup numthreads numthreads groupname rampup onerrorstoptest onerrorstoptestnow onerrorstopthread listedhashtree threadgrouptree listedhashtree getsubtree threadgrouptree testlevelelements numthreads jmeterthread jmeterthread jmeterthread clonetree threadgrouptree jmeterthread setthreadnum jmeterthread setthreadgroup jmeterthread setinitialcontext jmetercontextservice getcontext jmeterthread setinitialdelay perthreaddelay threadname groupname groupcount jmeterthread setthreadname threadname schedulethread jmeterthread jmeterthread setengine jmeterthread setonerrorstoptest onerrorstoptest jmeterthread setonerrorstoptestnow onerrorstoptestnow jmeterthread setonerrorstopthread onerrorstopthread newthread jmeterthread newthread setname threadname allthreads jmeterthread newthread newthread hasnext groupname allthreads startinggroups this will schedule the time for the j meter thread param thread param group private void schedule thread j meter thread thread thread group group if true the scheduler is enabled if group get scheduler long now system current time millis set the start time for the thread if group get delay 0 duration is in seconds thread set start time group get delay 1000 now else long start group get start time if start now start now force a sensible start time thread set start time start set the endtime for the thread if group get duration 0 duration is in seconds thread set end time group get duration 1000 thread get start time else thread set end time group get end time enables the scheduler thread set scheduled true jmeterthread schedulethread jmeterthread threadgroup getscheduler currenttimemillis getdelay setstarttime getdelay getstarttime setstarttime getduration setendtime getduration getstarttime setendtime getendtime setscheduled private boolean verify threads stopped boolean stopped all true list thread threads to check new array list thread all threads size synchronized all threads protect iterator iterator thread iter all threads key set iterator while iter has next thread t thread all threads get iter next if t null threads to check add t do work later to reduce time in synch block for int i 0 i threads to check size i thread t thread threads to check get i if t is alive try t join wait to die catch interrupted exception e if t is alive stopped all false log warn thread won t exit t get name return stopped all verifythreadsstopped stoppedall threadstocheck arraylist allthreads allthreads allthreads keyset hasnext allthreads threadstocheck threadstocheck threadstocheck isalive wait_to_die interruptedexception isalive stoppedall getname stoppedall private void tell threads to stop synchronized all threads protect iterator iterator iter new hash set all threads key set iterator while iter has next j meter thread item j meter thread iter next item stop set stop flag item interrupt interrupt sampler if possible thread t thread all threads get item t interrupt also interrupt jvm thread tellthreadstostop allthreads hashset allthreads keyset hasnext jmeterthread jmeterthread allthreads public void ask threads to stop engine stop test false askthreadstostop stoptest private void stop all threads synchronized all threads protect iterator iterator iter new hash set all threads key set iterator while iter has next j meter thread item j meter thread iter next item stop this is quick stopallthreads allthreads hashset allthreads keyset hasnext jmeterthread jmeterthread remote exit public void exit needs to be run in a separate thread to allow rmi call to return ok thread t new thread public void run log info pausing pause 1000 allow rmi to complete log info bye system exit 0 log info starting closedown t start thread t new thread public void run log info pausing pause 1000 allow rmi to complete log info bye system exit 0 private void pause long ms try thread sleep ms catch interrupted exception e interruptedexception public void set properties properties p log info applying properties p j meter utils getj meter properties put all p setproperties jmeterutils getjmeterproperties putall private xml conf panel xml public x path assertion gui init xmlconfpanel xpathassertiongui returns the label to be shown within the j tree component public string get label resource return xpath assertion title non nls 1 jtree getlabelresource xpath_assertion_title create test element public test element create test element x path assertion el new x path assertion modify test element el return el testelement createtestelement xpathassertion xpathassertion modifytestelement public string getx path attributes title return j meter utils get res string xpath assertion test non nls 1 getxpathattributestitle jmeterutils getresstring xpath_assertion_test public void configure test element el super configure el x path assertion assertion x path assertion el xpath setx path assertion getx path string xpath set negated assertion is negated xml configure assertion testelement xpathassertion xpathassertion setxpath getxpathstring setnegated isnegated private void init set layout new vertical layout 5 vertical layout both vertical layout top set border make border add make title panel user input j panel size panel new j panel new border layout size panel set border border factory create empty border 0 10 10 10 size panel set border border factory create titled border border factory create etched border getx path attributes title xpath new x path panel size panel add xpath xml new xml conf panel xml set border border factory create titled border border factory create etched border j meter utils get res string xpath assertion option non nls 1 add xml add size panel setlayout verticallayout verticallayout verticallayout setborder makeborder maketitlepanel user_input jpanel sizepanel jpanel borderlayout sizepanel setborder borderfactory createemptyborder sizepanel setborder borderfactory createtitledborder borderfactory createetchedborder getxpathattributestitle xpathpanel sizepanel xmlconfpanel setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring xpath_assertion_option sizepanel modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element el super configure test element el if el instanceof x path assertion x path assertion assertion x path assertion el assertion set negated xpath is negated assertion setx path string xpath getx path xml modify test element assertion testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement xpathassertion xpathassertion xpathassertion setnegated isnegated setxpathstring getxpath modifytestelement implements j metergui component clear gui public void clear gui super clear gui xpath setx path non nls 1 xpath set negated false xml set default values jmeterguicomponent cleargui cleargui cleargui setxpath setnegated setdefaultvalues float saved value public float property string name float value super name this value value savedvalue floatproperty public float property floatproperty see org apache jmeter testelement property j meter property set running version boolean public void set running version boolean running version saved value value super set running version running version jmeterproperty setrunningversion setrunningversion runningversion savedvalue setrunningversion runningversion see org apache jmeter testelement property j meter property recover running version org apache jmeter testelement test element public void recover running version test element owner value saved value jmeterproperty recoverrunningversion testelement recoverrunningversion testelement savedvalue public void set value float value this value value setvalue protected void set number value number n value n float value setnumbervalue floatvalue protected void set number value string n throws number format exception value float parse float n setnumbervalue numberformatexception parsefloat see j meter property get string value public string get string value return float to string value jmeterproperty getstringvalue getstringvalue tostring see j meter property get object value public object get object value return new float value jmeterproperty getobjectvalue getobjectvalue public object clone float property prop float property super clone prop value value return prop floatproperty floatproperty see j meter property get boolean value public boolean get boolean value return value 0 true false jmeterproperty getbooleanvalue getbooleanvalue see j meter property get double value public double get double value return value jmeterproperty getdoublevalue getdoublevalue see j meter property get float value public float get float value return value jmeterproperty getfloatvalue getfloatvalue see j meter property get int value public int get int value return int value jmeterproperty getintvalue getintvalue see j meter property get long value public long get long value return long value jmeterproperty getlongvalue getlongvalue construct a bean info for the given class protected bean info support class bean class notread this bean class bean class try root bean info introspector get bean info bean class introspector ignore immediate beaninfo catch introspection exception e log error can t introspect e throw new error e to string programming error bail out try resource bundle resource bundle resource bundle get bundle bean class get name resources non nls 1 j meter utils get locale store the resource bundle as an attribute of the bean descriptor get bean descriptor set value resource bundle resource bundle localize the bean name try get bean descriptor set display name resource bundle get string display name non nls 1 catch missing resource exception e log debug localized display name not available for bean bean class get name localize the property names and descriptions property descriptor properties get property descriptors for int i 0 i properties length i string name properties i get name try properties i set display name resource bundle get string name display name non nls 1 catch missing resource exception e log debug localized display name not available for property name try properties i set short description resource bundle get string name short description catch missing resource exception e log debug localized short description not available for property name catch missing resource exception e log warn localized strings not available for bean bean class e catch exception e log warn something bad happened when loading bean info e beaninfo beaninfosupport beanclass beanclass beanclass rootbeaninfo getbeaninfo beanclass ignore_immediate_beaninfo introspectionexception tostring resourcebundle resourcebundle resourcebundle getbundle beanclass getname jmeterutils getlocale beandescriptor getbeandescriptor setvalue resource_bundle resourcebundle getbeandescriptor setdisplayname resourcebundle getstring displayname missingresourceexception beanclass getname propertydescriptor getpropertydescriptors getname setdisplayname resourcebundle getstring displayname missingresourceexception setshortdescription resourcebundle getstring shortdescription missingresourceexception missingresourceexception beanclass get the property descriptor for the property of the given name param name property name return descriptor for a property of that name or null if there s none protected property descriptor property string name property descriptor properties get property descriptors for int i 0 i properties length i if properties i get name equals name return properties i log warn cannot find property name return null propertydescriptor propertydescriptor getpropertydescriptors getname set the bean s 16x16 colour icon param resource name a pathname relative to the directory holding the class file of the current class protected void set icon string resource name icons icon color 16x16 load image resource name resourcename seticon resourcename icon_color_16x16 loadimage resourcename utility method to group and order properties p it will assing the given group name to each of the named properties and set their order attribute so that they are shown in the given order p the created groups will get order 1 2 3 in the order in which they are created param group name of the group param names property names in the desired order protected void create property group string group string names for int i 0 i names length i log debug getting property for names i property descriptor p property names i p set value generic test bean customizer group group p set value generic test bean customizer order new integer i num created groups get bean descriptor set value generic test bean customizer order group new integer num created groups createpropertygroup propertydescriptor setvalue generictestbeancustomizer setvalue generictestbeancustomizer numcreatedgroups getbeandescriptor setvalue generictestbeancustomizer numcreatedgroups public bean info get additional bean info return root bean info get additional bean info beaninfo getadditionalbeaninfo rootbeaninfo getadditionalbeaninfo public bean descriptor get bean descriptor return root bean info get bean descriptor beandescriptor getbeandescriptor rootbeaninfo getbeandescriptor public int get default event index return root bean info get default event index getdefaulteventindex rootbeaninfo getdefaulteventindex public int get default property index return root bean info get default property index getdefaultpropertyindex rootbeaninfo getdefaultpropertyindex public event set descriptor get event set descriptors return root bean info get event set descriptors eventsetdescriptor geteventsetdescriptors rootbeaninfo geteventsetdescriptors public image get icon int icon kind return icons icon kind geticon iconkind iconkind public method descriptor get method descriptors return root bean info get method descriptors methoddescriptor getmethoddescriptors rootbeaninfo getmethoddescriptors public property descriptor get property descriptors return root bean info get property descriptors propertydescriptor getpropertydescriptors rootbeaninfo getpropertydescriptors retrieve argument to option if it takes arguments return the first argument public final string get argument return get argument 0 getargument getargument retrieve indexed argument to option if it takes arguments param index the argument index from 0 to link get argument count 1 return the argument public final string get argument final int index if null m arguments index 0 index m arguments length return null else return m arguments index getargumentcount getargument m_arguments m_arguments m_arguments public final cl option descriptor get descriptor return m descriptor cloptiondescriptor getdescriptor m_descriptor constructor taking an descriptor param descriptor the descriptor iff null will default to a text argument descriptor public cl option final cl option descriptor descriptor if descriptor null m descriptor descriptor cloption cloptiondescriptor m_descriptor constructor taking argument for option param argument the argument public cl option final string argument this cl option descriptor null add argument argument cloption cloptiondescriptor addargument mutator of argument property param argument the argument public final void add argument final string argument if null m arguments m arguments new string argument else final string arguments new string m arguments length 1 system arraycopy m arguments 0 arguments 0 m arguments length arguments m arguments length argument m arguments arguments addargument m_arguments m_arguments m_arguments m_arguments m_arguments m_arguments m_arguments get number of arguments return the number of arguments public final int get argument count if null m arguments return 0 else return m arguments length getargumentcount m_arguments m_arguments convert to string return the string value public final string to string final string buffer sb new string buffer sb append final char id char m descriptor get id if id text argument sb append text else sb append option sb append id if null m arguments sb append sb append arrays as list m arguments sb append return sb to string tostring stringbuffer stringbuffer m_descriptor getid text_argument m_arguments aslist m_arguments tostring final string to short string final string buffer sb new string buffer final char id char m descriptor get id if id text argument sb append sb append id if null m arguments if id text argument sb append sb append arrays as list m arguments return sb to string toshortstring stringbuffer stringbuffer m_descriptor getid text_argument m_arguments text_argument aslist m_arguments tostring public clear public set get action names return commands getactionnames public void do action action event e gui package gui package gui package get instance final string action command e get action command if action command equals action names clear j metergui component gui comp gui package get current gui if gui comp instanceof clearable clearable gui comp clear data else if action command equals action names reset gui j metergui component gui comp gui package get current gui gui comp clear gui else iterator iter gui package get tree model get nodes of type clearable class iterator while iter has next j meter tree node node null j metergui component gui comp null try object next iter next node j meter tree node next gui comp gui package get gui node get test element if gui comp instanceof clearable clearable item clearable gui comp item clear data catch exception ex log error can t clear node gui comp ex doaction actionevent guipackage guipackage guipackage getinstance actioncommand getactioncommand actioncommand actionnames jmeterguicomponent guicomp guipackage getcurrentgui guicomp guicomp cleardata actioncommand actionnames reset_gui jmeterguicomponent guicomp guipackage getcurrentgui guicomp cleargui guipackage gettreemodel getnodesoftype hasnext jmetertreenode jmeterguicomponent guicomp jmetertreenode guicomp guipackage getgui gettestelement guicomp guicomp cleardata guicomp public class default tree table model extends abstract tree table model public default tree table model this new default mutable tree node defaulttreetablemodel abstracttreetablemodel defaulttreetablemodel defaultmutabletreenode param root public default tree table model tree node root super root defaulttreetablemodel treenode param root param editable public default tree table model tree node root boolean editable super root editable defaulttreetablemodel treenode param headers param read functors param write functors param editor classes public default tree table model string headers functor read functors functor write functors class editor classes super headers read functors write functors editor classes readfunctors writefunctors editorclasses defaulttreetablemodel readfunctors writefunctors editorclasses readfunctors writefunctors editorclasses public stat visualizer super model new object table model columns sampling stat calculator class new functor new functor get label non nls 1 new functor get count non nls 1 new functor get mean as number non nls 1 new functor get median non nls 1 new functor get percent point non nls 1 new object new float 900 new functor get min non nls 1 new functor get max non nls 1 new functor get error percentage non nls 1 new functor get rate non nls 1 new functor getkb per second non nls 1 new functor null null null null null null null null null null new class string class long class long class long class long class long class long class string class string class string class clear data init statvisualizer objecttablemodel samplingstatcalculator getlabel getcount getmeanasnumber getmedian getpercentpoint getmin getmax geterrorpercentage getrate getkbpersecond cleardata deprecated only for use in testing public static boolean test functors stat visualizer instance new stat visualizer return instance model check functors null instance get class testfunctors statvisualizer statvisualizer checkfunctors getclass public string get label resource return aggregate report non nls 1 getlabelresource aggregate_report public void add sample result res sampling stat calculator row null final string sample label res get sample label use group name is selected synchronized table rows row sampling stat calculator table rows get sample label if row null row new sampling stat calculator sample label table rows put row get label row model insert row row model get row count 1 synch is needed because multiple threads can update the counts synchronized row row add sample res sampling stat calculator tot sampling stat calculator table rows get total row label synchronized tot tot add sample res model fire table data changed sampleresult samplingstatcalculator samplelabel getsamplelabel usegroupname isselected tablerows samplingstatcalculator tablerows samplelabel samplingstatcalculator samplelabel tablerows getlabel insertrow getrowcount addsample samplingstatcalculator samplingstatcalculator tablerows total_row_label addsample firetabledatachanged clears this visualizer and its model and forces a repaint of the table public void clear data synchronized table rows model clear data table rows clear table rows put total row label new sampling stat calculator total row label model add row table rows get total row label cleardata tablerows cleardata tablerows tablerows total_row_label samplingstatcalculator total_row_label addrow tablerows total_row_label main visualizer setup private void init this set layout new border layout main panel j panel main panel new j panel border margin new empty border 10 10 5 10 main panel set border margin main panel set layout new box layout main panel box layout y axis main panel add make title panel sort filter model my sorted model new sort filter model my stat table model myj table new j table model myj table get table header set default renderer new header as property renderer myj table set preferred scrollable viewport size new dimension 500 70 renderer utils apply renderers myj table renderers my scroll pane new j scroll pane myj table this add main panel border layout north this add my scroll pane border layout center save table add action listener this j panel opts new j panel opts add use group name border layout west opts add save table border layout center this add opts border layout south setlayout borderlayout jpanel mainpanel jpanel emptyborder mainpanel setborder mainpanel setlayout boxlayout mainpanel boxlayout y_axis mainpanel maketitlepanel sortfiltermodel mysortedmodel sortfiltermodel mystattablemodel myjtable jtable myjtable gettableheader setdefaultrenderer headeraspropertyrenderer myjtable setpreferredscrollableviewportsize rendererutils applyrenderers myjtable myscrollpane jscrollpane myjtable mainpanel borderlayout myscrollpane borderlayout savetable addactionlistener jpanel jpanel usegroupname borderlayout savetable borderlayout borderlayout public void modify test element test element c super modify test element c c set property use group name use group name is selected false modifytestelement testelement modifytestelement setproperty use_group_name usegroupname isselected public void configure test element el super configure el use group name set selected el get property as boolean use group name false testelement usegroupname setselected getpropertyasboolean use_group_name public void action performed action event ev if ev get source save table j file chooser chooser file dialoger prompt to save file aggregate csv non nls 1 if chooser null return file writer writer null try writer new file writer chooser get selected file csv save service savecsv stats model writer catch file not found exception e log warn e get message catch io exception e log warn e get message finally j orphan utils close quietly writer actionperformed actionevent getsource savetable jfilechooser filedialoger prompttosavefile filewriter filewriter getselectedfile csvsaveservice savecsvstats filenotfoundexception getmessage ioexception getmessage jorphanutils closequietly add a receive client to the client pool this is so that we can make sure to close all clients and make sure all threads are destroyed param client public static synchronized void add client receive subscriber client clients add client receiveclient clientpool addclient receivesubscriber add a on message client to the client pool this is so that we can make sure to close all clients and make sure all threads are destroyed param client public static synchronized void add client on message subscriber client clients add client onmessageclient clientpool addclient onmessagesubscriber add a publisher to the client pool this is so that we can make sure to close all clients and make sure all threads are destroyed param client public static synchronized void add client publisher client clients add client clientpool addclient clear all the clients created by either publish or subscribe sampler we need to do this to make sure all the threads creatd during the test are destroyed and cleaned up in some cases the client provided by the manufacturer of the jms server may have bugs and some threads may become zombie in those cases it is not the responsibility of j meter for those bugs public static synchronized void clear client iterator itr clients iterator while itr has next object client itr next if client instanceof receive subscriber receive subscriber sub receive subscriber client sub close sub null else if client instanceof publisher publisher pub publisher client pub close pub null else if client instanceof on message subscriber on message subscriber sub on message subscriber client sub close sub null clients clear client map clear jmeter clearclient hasnext receivesubscriber receivesubscriber receivesubscriber onmessagesubscriber onmessagesubscriber onmessagesubscriber client_map public static synchronized void put object key on message subscriber client client map put key client onmessagesubscriber client_map public static synchronized void put object key publisher client client map put key client client_map public static synchronized object get object key return client map get key client_map private j meter context jmctx null public test regex function string name super name jmetercontext testregexfunction public void set up variable new regex function result new sample result jmctx j meter context service get context string data company xmlext query ret row value field ret code lis ok value value field ret code extension value value field alias value value field positioncount value value field invalidpincount 0 value value field pinposition1 1 value value field pinpositionvalue1 value value field pinposition2 5 value value field pinpositionvalue2 value value field pinposition3 6 value value field pinpositionvalue3 value row company xmlext query ret result set response data data get bytes vars new j meter variables string data2 the quick brown fox jumped over the lazy dog 123 times vars put input variable name data2 jmctx set variables vars jmctx set previous result result setup regexfunction sampleresult jmetercontextservice getcontext retcode lis_ok retcodeextension setresponsedata getbytes jmetervariables input_variable_name setvariables setpreviousresult public void test variable extraction throws exception params new linked list params add new compound variable value field pinposition d d value params add new compound variable 2 params add new compound variable 2 variable set parameters params string match variable execute result null assert equals 5 match testvariableextraction linkedlist compoundvariable compoundvariable compoundvariable setparameters assertequals test with output variable name public void test variable extraction1a throws exception params new linked list params add new compound variable value field pinposition d d value params add new compound variable 2 template params add new compound variable 2 match number params add new compound variable all separator params add new compound variable default params add new compound variable outvar variable set parameters params string match variable execute result null assert equals 3 vars get object outvar matchnr assert equals 5 match assert equals 5 vars get object outvar assert equals value field pinposition2 5 value vars get object outvar g0 assert equals pinposition2 vars get object outvar g1 assert equals 5 vars get object outvar g2 testvariableextraction1a linkedlist compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable setparameters assertequals getobject outvar_matchnr assertequals assertequals getobject assertequals getobject outvar_g0 assertequals getobject outvar_g1 assertequals getobject outvar_g2 test with empty output variable name public void test variable extraction1b throws exception params new linked list params add new compound variable value field pinposition d d value params add new compound variable 2 template params add new compound variable 2 match number params add new compound variable all separator params add new compound variable default params add new compound variable variable set parameters params string match variable execute result null assert equals 5 match assert null vars get object outvar testvariableextraction1b linkedlist compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable setparameters assertequals assertnull getobject public void test variable extraction from variable throws exception params new linked list params add new compound variable d s w params add new compound variable 2 template params add new compound variable 1 match number params add new compound variable all separator params add new compound variable default params add new compound variable outvar params add new compound variable input variable name variable set parameters params string match variable execute result null assert equals 1 vars get object outvar matchnr assert equals times match assert equals times vars get object outvar assert equals 123 times vars get object outvar g0 assert equals 123 vars get object outvar g1 assert equals times vars get object outvar g2 testvariableextractionfromvariable linkedlist compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable input_variable_name setparameters assertequals getobject outvar_matchnr assertequals assertequals getobject assertequals getobject outvar_g0 assertequals getobject outvar_g1 assertequals getobject outvar_g2 public void test variable extraction from variable2 throws exception params new linked list params add new compound variable d s w params add new compound variable 1 2 template params add new compound variable 1 match number params add new compound variable all separator params add new compound variable default params add new compound variable outvar params add new compound variable input variable name variable set parameters params string match variable execute result null assert equals 1 vars get object outvar matchnr assert equals 123times match assert equals 123times vars get object outvar assert equals 123 times vars get object outvar g0 assert equals 123 vars get object outvar g1 assert equals times vars get object outvar g2 testvariableextractionfromvariable2 linkedlist compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable input_variable_name setparameters assertequals getobject outvar_matchnr assertequals assertequals getobject assertequals getobject outvar_g0 assertequals getobject outvar_g1 assertequals getobject outvar_g2 public void test variable extraction from variable3 throws exception params new linked list params add new compound variable d s w params add new compound variable pre 2 post template params add new compound variable 1 match number params add new compound variable all separator params add new compound variable default params add new compound variable outvar params add new compound variable input variable name variable set parameters params string match variable execute result null assert equals 1 vars get object outvar matchnr assert equals pretimespost match assert equals pretimespost vars get object outvar assert equals 123 times vars get object outvar g0 assert equals 123 vars get object outvar g1 assert equals times vars get object outvar g2 testvariableextractionfromvariable3 linkedlist compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable input_variable_name setparameters assertequals getobject outvar_matchnr assertequals assertequals getobject assertequals getobject outvar_g0 assertequals getobject outvar_g1 assertequals getobject outvar_g2 public void test variable extraction from variable4 throws exception params new linked list params add new compound variable d s w params add new compound variable pre 2 template params add new compound variable 1 match number params add new compound variable all separator params add new compound variable default params add new compound variable outvar params add new compound variable input variable name variable set parameters params string match variable execute result null assert equals 1 vars get object outvar matchnr assert equals pretimes match assert equals pretimes vars get object outvar assert equals 123 times vars get object outvar g0 assert equals 123 vars get object outvar g1 assert equals times vars get object outvar g2 testvariableextractionfromvariable4 linkedlist compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable input_variable_name setparameters assertequals getobject outvar_matchnr assertequals assertequals getobject assertequals getobject outvar_g0 assertequals getobject outvar_g1 assertequals getobject outvar_g2 public void test variable extraction from variable5 throws exception params new linked list params add new compound variable d s w params add new compound variable 2 post template params add new compound variable 1 match number params add new compound variable all separator params add new compound variable default params add new compound variable outvar params add new compound variable input variable name variable set parameters params string match variable execute result null assert equals 1 vars get object outvar matchnr assert equals timespost match assert equals timespost vars get object outvar assert equals 123 times vars get object outvar g0 assert equals 123 vars get object outvar g1 assert equals times vars get object outvar g2 testvariableextractionfromvariable5 linkedlist compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable input_variable_name setparameters assertequals getobject outvar_matchnr assertequals assertequals getobject assertequals getobject outvar_g0 assertequals getobject outvar_g1 assertequals getobject outvar_g2 public void test variable extraction from variable6 throws exception params new linked list params add new compound variable d s w params add new compound variable 2 2 template params add new compound variable 1 match number params add new compound variable all separator params add new compound variable default params add new compound variable outvar params add new compound variable input variable name variable set parameters params string match variable execute result null assert equals 1 vars get object outvar matchnr assert equals timestimes match assert equals timestimes vars get object outvar assert equals 123 times vars get object outvar g0 assert equals 123 vars get object outvar g1 assert equals times vars get object outvar g2 testvariableextractionfromvariable6 linkedlist compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable input_variable_name setparameters assertequals getobject outvar_matchnr assertequals assertequals getobject assertequals getobject outvar_g0 assertequals getobject outvar_g1 assertequals getobject outvar_g2 public void test variable extraction from variable7 throws exception params new linked list params add new compound variable d s w params add new compound variable pre 1 mid 2 post template params add new compound variable 1 match number params add new compound variable all separator params add new compound variable default params add new compound variable outvar params add new compound variable input variable name variable set parameters params string match variable execute result null assert equals 1 vars get object outvar matchnr assert equals pre123midtimespost match assert equals pre123midtimespost vars get object outvar assert equals 123 times vars get object outvar g0 assert equals 123 vars get object outvar g1 assert equals times vars get object outvar g2 testvariableextractionfromvariable7 linkedlist compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable input_variable_name setparameters assertequals getobject outvar_matchnr assertequals assertequals getobject assertequals getobject outvar_g0 assertequals getobject outvar_g1 assertequals getobject outvar_g2 public void test variable extraction from variable8 throws exception params new linked list params add new compound variable d s w params add new compound variable pre 1 mid 2 template params add new compound variable 1 match number params add new compound variable all separator params add new compound variable default params add new compound variable outvar params add new compound variable input variable name variable set parameters params string match variable execute result null assert equals 1 vars get object outvar matchnr assert equals pre123midtimes match assert equals pre123midtimes vars get object outvar assert equals 123 times vars get object outvar g0 assert equals 123 vars get object outvar g1 assert equals times vars get object outvar g2 testvariableextractionfromvariable8 linkedlist compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable input_variable_name setparameters assertequals getobject outvar_matchnr assertequals assertequals getobject assertequals getobject outvar_g0 assertequals getobject outvar_g1 assertequals getobject outvar_g2 public void test variable extraction from variable9 throws exception params new linked list params add new compound variable d s w params add new compound variable 1 mid 2 post template params add new compound variable 1 match number params add new compound variable all separator params add new compound variable default params add new compound variable outvar params add new compound variable input variable name variable set parameters params string match variable execute result null assert equals 1 vars get object outvar matchnr assert equals 123midtimespost match assert equals 123midtimespost vars get object outvar assert equals 123 times vars get object outvar g0 assert equals 123 vars get object outvar g1 assert equals times vars get object outvar g2 testvariableextractionfromvariable9 linkedlist compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable input_variable_name setparameters assertequals getobject outvar_matchnr assertequals assertequals getobject assertequals getobject outvar_g0 assertequals getobject outvar_g1 assertequals getobject outvar_g2 public void test variable extraction2 throws exception params new linked list params add new compound variable value field pinposition d d value params add new compound variable 1 params add new compound variable 3 variable set parameters params string match variable execute result null assert equals pinposition3 match testvariableextraction2 linkedlist compoundvariable compoundvariable compoundvariable setparameters assertequals public void test variable extraction5 throws exception params new linked list params add new compound variable value field pinposition d d value params add new compound variable 1 params add new compound variable all params add new compound variable variable set parameters params string match variable execute result null assert equals pinposition1 pinposition2 pinposition3 match testvariableextraction5 linkedlist compoundvariable compoundvariable compoundvariable compoundvariable _ setparameters assertequals pinposition1_pinposition2_pinposition3 public void test variable extraction6 throws exception params new linked list params add new compound variable value field pinposition d d value params add new compound variable 2 params add new compound variable 4 params add new compound variable params add new compound variable default variable set parameters params string match variable execute result null assert equals default match testvariableextraction6 linkedlist compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable setparameters assertequals public void test comma throws exception params new linked list params add new compound variable value field pinposition d d value params add new compound variable 1 params add new compound variable 3 variable set parameters params string match variable execute result null assert equals pinposition3 match testcomma linkedlist compoundvariable compoundvariable compoundvariable setparameters assertequals public void test variable extraction3 throws exception params new linked list params add new compound variable value field pinposition d d value params add new compound variable 1 params add new compound variable 2 variable set parameters params string match variable execute result null assert equals pinposition2 match testvariableextraction3 linkedlist compoundvariable compoundvariable _ compoundvariable setparameters assertequals _pinposition2 public void test variable extraction4 throws exception params new linked list params add new compound variable value field pinposition d d value params add new compound variable 2 params add new compound variable 333 variable set parameters params string match variable execute result null assert equals 1 match testvariableextraction4 linkedlist compoundvariable compoundvariable compoundvariable setparameters assertequals public void test default value throws exception params new linked list params add new compound variable value field pinposition d d value params add new compound variable 2 params add new compound variable 333 params add new compound variable params add new compound variable no value found variable set parameters params string match variable execute result null assert equals no value found match testdefaultvalue linkedlist compoundvariable compoundvariable compoundvariable compoundvariable compoundvariable setparameters assertequals public j meter exception super todo auto generated constructor stub jmeterexception param s public j meter exception string s super s todo auto generated constructor stub jmeterexception param cause public j meter exception throwable cause jdk1 4 super cause saved cause cause jmeterexception savedcause param message param cause public j meter exception string message throwable cause jdk1 4 super message cause super message saved cause cause jmeterexception savedcause local version of get cause for jdk1 3 support public throwable get cause return saved cause getcause getcause savedcause private boolean display name true public tcp config gui this true displayname tcpconfiggui public tcp config gui boolean display name this display name display name init tcpconfiggui displayname displayname displayname public string get label resource return tcp config title non nls 1 getlabelresource tcp_config_title public void configure test element element super configure element n b this will be a config element so we cannot use the getxxx methods classname set text element get property as string tcp sampler classname server set text element get property as string tcp sampler server default to original behaviour i e re use connection re use connection set selected element get property as boolean tcp sampler re use connection true port set text element get property as string tcp sampler port filename set text element get property as string tcp sampler filename timeout set text element get property as string tcp sampler timeout set no delay set selected element get property as boolean tcp sampler nodelay request data set text element get property as string tcp sampler request testelement settext getpropertyasstring tcpsampler settext getpropertyasstring tcpsampler reuseconnection setselected getpropertyasboolean tcpsampler re_use_connection settext getpropertyasstring tcpsampler settext getpropertyasstring tcpsampler settext getpropertyasstring tcpsampler setnodelay setselected getpropertyasboolean tcpsampler requestdata settext getpropertyasstring tcpsampler public test element create test element config test element element new config test element modify test element element return element testelement createtestelement configtestelement configtestelement modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element element configure test element element n b this will be a config element so we cannot use the setxxx methods element set property tcp sampler classname classname get text element set property tcp sampler server server get text element set property tcp sampler re use connection re use connection is selected element set property tcp sampler port port get text element set property tcp sampler filename filename get text element set property tcp sampler nodelay set no delay is selected element set property tcp sampler timeout timeout get text element set property tcp sampler request request data get text testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement setproperty tcpsampler gettext setproperty tcpsampler gettext setproperty tcpsampler re_use_connection reuseconnection isselected setproperty tcpsampler gettext setproperty tcpsampler gettext setproperty tcpsampler setnodelay isselected setproperty tcpsampler gettext setproperty tcpsampler requestdata gettext implements j metergui component clear gui public void clear gui super clear gui classname set text non nls 1 server set text non nls 1 port set text non nls 1 timeout set text non nls 1 request data set text non nls 1 re use connection set selected true set no delay set selected false jmeterguicomponent cleargui cleargui cleargui settext settext settext settext requestdata settext reuseconnection setselected setnodelay setselected private j panel create timeout panel j label label new j label j meter utils get res string tcp timeout non nls 1 timeout new j text field 10 label set label for timeout j panel timeout panel new j panel new border layout 5 0 timeout panel add label border layout west timeout panel add timeout border layout center return timeout panel jpanel createtimeoutpanel jlabel jlabel jmeterutils getresstring tcp_timeout jtextfield setlabelfor jpanel timeoutpanel jpanel borderlayout timeoutpanel borderlayout timeoutpanel borderlayout timeoutpanel private j panel create no delay panel j label label new j label j meter utils get res string tcp nodelay non nls 1 set no delay new j check box label set label for set no delay j panel nodelay panel new j panel new border layout 5 0 nodelay panel add label border layout west nodelay panel add set no delay border layout center return nodelay panel jpanel createnodelaypanel jlabel jlabel jmeterutils getresstring tcp_nodelay setnodelay jcheckbox setlabelfor setnodelay jpanel nodelaypanel jpanel borderlayout nodelaypanel borderlayout nodelaypanel setnodelay borderlayout nodelaypanel private j panel create server panel j label label new j label j meter utils get res string server non nls 1 server new j text field 10 label set label for server j panel server panel new j panel new border layout 5 0 server panel add label border layout west server panel add server border layout center return server panel jpanel createserverpanel jlabel jlabel jmeterutils getresstring jtextfield setlabelfor jpanel serverpanel jpanel borderlayout serverpanel borderlayout serverpanel borderlayout serverpanel private j panel create close port panel j label label new j label j meter utils get res string reuseconnection non nls 1 re use connection new j check box true label set label for re use connection j panel close port panel new j panel new border layout 5 0 close port panel add label border layout west close port panel add re use connection border layout center return close port panel jpanel createcloseportpanel jlabel jlabel jmeterutils getresstring reuseconnection jcheckbox setlabelfor reuseconnection jpanel closeportpanel jpanel borderlayout closeportpanel borderlayout closeportpanel reuseconnection borderlayout closeportpanel private j panel create port panel j label label new j label j meter utils get res string tcp port non nls 1 port new j text field 10 label set label for port j panel port panel new j panel new border layout 5 0 port panel add label border layout west port panel add port border layout center return port panel jpanel createportpanel jlabel jlabel jmeterutils getresstring tcp_port jtextfield setlabelfor jpanel portpanel jpanel borderlayout portpanel borderlayout portpanel borderlayout portpanel private j panel create request panel j label req label new j label j meter utils get res string tcp request data non nls 1 request data new j text area 3 0 request data set line wrap true req label set label for request data j panel req data panel new j panel new border layout 5 0 req data panel add req label border layout west req data panel add request data border layout center return req data panel jpanel createrequestpanel jlabel reqlabel jlabel jmeterutils getresstring tcp_request_data requestdata jtextarea requestdata setlinewrap reqlabel setlabelfor requestdata jpanel reqdatapanel jpanel borderlayout reqdatapanel reqlabel borderlayout reqdatapanel requestdata borderlayout reqdatapanel private void init set layout new border layout 0 5 if display name set border make border add make title panel border layout north vertical panel main panel new vertical panel classname new j labeled text field j meter utils get res string tcp classname main panel add classname final j panel server panel create server panel server panel add create port panel border layout east main panel add server panel main panel add create close port panel main panel add create timeout panel main panel add create no delay panel main panel add create request panel main panel add create filename panel add main panel border layout center setlayout borderlayout displayname setborder makeborder maketitlepanel borderlayout verticalpanel mainpanel verticalpanel jlabeledtextfield jmeterutils getresstring tcp_classname mainpanel jpanel serverpanel createserverpanel serverpanel createportpanel borderlayout mainpanel serverpanel mainpanel createcloseportpanel mainpanel createtimeoutpanel mainpanel createnodelaypanel mainpanel createrequestpanel mainpanel createfilenamepanel mainpanel borderlayout public report add parent reportaddparent public void do action action event e string name component e get source get name try test element controller report gui package get instance create test element name add parent to tree controller catch exception err log error err doaction actionevent getsource getname testelement reportguipackage getinstance createtestelement addparenttotree public set get action names return commands getactionnames protected void add parent to tree test element new parent report gui package gui package report gui package get instance report tree node new node new report tree node new parent gui package get tree model report tree node current node gui package get tree listener get current node report tree node parent node report tree node current node get parent int index parent node get index current node gui package get tree model insert node into new node parent node index report tree node nodes gui package get tree listener get selected nodes for int i 0 i nodes length i move node gui package nodes i new node addparenttotree testelement newparent reportguipackage guipackage reportguipackage getinstance reporttreenode newnode reporttreenode newparent guipackage gettreemodel reporttreenode currentnode guipackage gettreelistener getcurrentnode reporttreenode parentnode reporttreenode currentnode getparent parentnode getindex currentnode guipackage gettreemodel insertnodeinto newnode parentnode reporttreenode guipackage gettreelistener getselectednodes movenode guipackage newnode private void move node report gui package gui package report tree node node report tree node new parent node gui package get tree model remove node from parent node gui package get tree model insert node into node new parent node new parent node get child count movenode reportguipackage guipackage reporttreenode reporttreenode newparentnode guipackage gettreemodel removenodefromparent guipackage gettreemodel insertnodeinto newparentnode newparentnode getchildcount see command do action action event public void do action action event e string action e get action command gui package gui package gui package get instance j meter tree node dragged nodes gui package get tree listener get dragged nodes j meter tree listener tree listener gui package get tree listener j meter tree node current node tree listener get current node j meter tree node parent node j meter tree node current node get parent test element te current node get test element if te instanceof test plan te instanceof work bench parent node null so elements can only be added as children if action names drag add equals action can add to current node dragged nodes remove nodes from parents dragged nodes for int i 0 i dragged nodes length i gui package get instance get tree model insert node into dragged nodes i current node current node get child count else if parent node null if action names insert before equals action can add to parent node dragged nodes remove nodes from parents dragged nodes for int i 0 i dragged nodes length i int index parent node get index current node gui package get instance get tree model insert node into dragged nodes i parent node index else if action names insert after equals action can add to parent node dragged nodes remove nodes from parents dragged nodes for int i 0 i dragged nodes length i int index parent node get index current node 1 gui package get instance get tree model insert node into dragged nodes i parent node index gui package get instance get main frame repaint doaction actionevent doaction actionevent getactioncommand guipackage guipackage guipackage getinstance jmetertreenode draggednodes guipackage gettreelistener getdraggednodes jmetertreelistener treelistener guipackage gettreelistener jmetertreenode currentnode treelistener getcurrentnode jmetertreenode parentnode jmetertreenode currentnode getparent testelement currentnode gettestelement testplan workbench parentnode actionnames drag_add canaddto currentnode draggednodes removenodesfromparents draggednodes draggednodes guipackage getinstance gettreemodel insertnodeinto draggednodes currentnode currentnode getchildcount parentnode actionnames insert_before canaddto parentnode draggednodes removenodesfromparents draggednodes draggednodes parentnode getindex currentnode guipackage getinstance gettreemodel insertnodeinto draggednodes parentnode actionnames insert_after canaddto parentnode draggednodes removenodesfromparents draggednodes draggednodes parentnode getindex currentnode guipackage getinstance gettreemodel insertnodeinto draggednodes parentnode guipackage getinstance getmainframe private static boolean can add to j meter tree node parent node j meter tree node dragged nodes boolean ok menu factory can add to parent node dragged nodes if ok toolkit get default toolkit beep return ok canaddto jmetertreenode parentnode jmetertreenode draggednodes menufactory canaddto parentnode draggednodes getdefaulttoolkit protected void remove nodes from parents j meter tree node nodes for int i 0 i nodes length i gui package get instance get tree model remove node from parent nodes i removenodesfromparents jmetertreenode guipackage getinstance gettreemodel removenodefromparent see command get action names public set get action names return commands getactionnames getactionnames private j text area script field script area public bean shell sampler gui init jtextarea scriptfield beanshellsamplergui public void configure test element element script field set text element get property as string bean shell sampler script filename set text element get property as string bean shell sampler filename parameters set text element get property as string bean shell sampler parameters reset interpreter set selected element get property as boolean bean shell sampler reset interpreter super configure element testelement scriptfield settext getpropertyasstring beanshellsampler settext getpropertyasstring beanshellsampler settext getpropertyasstring beanshellsampler resetinterpreter setselected getpropertyasboolean beanshellsampler reset_interpreter public test element create test element bean shell sampler sampler new bean shell sampler modify test element sampler return sampler testelement createtestelement beanshellsampler beanshellsampler modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element te te clear this configure test element te te set property bean shell sampler script script field get text te set property bean shell sampler filename filename get text te set property bean shell sampler parameters parameters get text te set property new boolean property bean shell sampler reset interpreter reset interpreter is selected testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement setproperty beanshellsampler scriptfield gettext setproperty beanshellsampler gettext setproperty beanshellsampler gettext setproperty booleanproperty beanshellsampler reset_interpreter resetinterpreter isselected implements j metergui component clear gui public void clear gui super clear gui filename set text non nls 1 parameters set text non nls 1 script field set text non nls 1 reset interpreter set selected false jmeterguicomponent cleargui cleargui cleargui settext settext scriptfield settext resetinterpreter setselected public string get label resource return bsh sampler title non nls 1 getlabelresource bsh_sampler_title private j panel create filename panel todo ought to be a file chooser j label label new j label j meter utils get res string bsh script file non nls 1 filename new j text field 10 filename set name bean shell sampler filename label set label for filename j panel filename panel new j panel new border layout 5 0 filename panel add label border layout west filename panel add filename border layout center return filename panel jpanel createfilenamepanel filechooser jlabel jlabel jmeterutils getresstring bsh_script_file jtextfield setname beanshellsampler setlabelfor jpanel filenamepanel jpanel borderlayout filenamepanel borderlayout filenamepanel borderlayout filenamepanel private j panel create parameter panel j label label new j label j meter utils get res string bsh script parameters non nls 1 parameters new j text field 10 parameters set name bean shell sampler parameters label set label for parameters j panel parameter panel new j panel new border layout 5 0 parameter panel add label border layout west parameter panel add parameters border layout center return parameter panel jpanel createparameterpanel jlabel jlabel jmeterutils getresstring bsh_script_parameters jtextfield setname beanshellsampler setlabelfor jpanel parameterpanel jpanel borderlayout parameterpanel borderlayout parameterpanel borderlayout parameterpanel private j panel create reset panel reset interpreter new j check box j meter utils get res string bsh script reset interpreter non nls 1 reset interpreter set name bean shell sampler parameters j panel reset interpreter panel new j panel new border layout reset interpreter panel add reset interpreter border layout west return reset interpreter panel jpanel createresetpanel resetinterpreter jcheckbox jmeterutils getresstring bsh_script_reset_interpreter resetinterpreter setname beanshellsampler jpanel resetinterpreterpanel jpanel borderlayout resetinterpreterpanel resetinterpreter borderlayout resetinterpreterpanel private void init set layout new border layout 0 5 set border make border box box box create vertical box box add make title panel box add create reset panel box add create parameter panel box add create filename panel add box border layout north j panel panel create script panel add panel border layout center don t let the input field shrink too much add box create vertical strut panel get preferred size height border layout west setlayout borderlayout setborder makeborder createverticalbox maketitlepanel createresetpanel createparameterpanel createfilenamepanel borderlayout jpanel createscriptpanel borderlayout createverticalstrut getpreferredsize borderlayout private j panel create script panel script field new j text area script field set rows 4 script field set line wrap true script field set wrap style word true j label label new j label j meter utils get res string bsh script non nls 1 label set label for script field j panel panel new j panel new border layout panel add label border layout north panel add new j scroll pane script field border layout center j text area explain new j text area j meter utils get res string bsh script variables non nls 1 explain set line wrap true explain set editable false explain set background this get background panel add explain border layout south return panel jpanel createscriptpanel scriptfield jtextarea scriptfield setrows scriptfield setlinewrap scriptfield setwrapstyleword jlabel jlabel jmeterutils getresstring bsh_script setlabelfor scriptfield jpanel jpanel borderlayout borderlayout jscrollpane scriptfield borderlayout jtextarea jtextarea jmeterutils getresstring bsh_script_variables setlinewrap seteditable setbackground getbackground borderlayout public final class color helper private constructor to prevent instantiation private color helper colorhelper colorhelper given the code color code get the red green and blue components increment the lowest of the components by the indicated increment value if all the components are the same value increment in the order of red green and blue param inc value to increment the color components return the color after change public static color change color cyclic increment color col int inc int red col get red int green col get green int blue col get blue int temp1 math min red green int temp2 math min temp1 blue now temp2 has the lowest of the three components if red temp2 red inc red 256 else if green temp2 green inc green 256 else if blue temp2 blue inc blue 256 return new color red green blue changecolorcyclicincrement getred getgreen getblue public check dirty previous gui items new hash map action router get instance add pre action listener exit command class this checkdirty previousguiitems hashmap actionrouter getinstance addpreactionlistener exitcommand public void action performed action event e if e get action command equals action names exit do action e actionperformed actionevent getactioncommand actionnames doaction see command do action action event public void do action action event e string action e get action command if action equals action names sub tree saved hash tree sub tree hash tree e get source sub tree traverse this else if action equals action names sub tree loaded listed hash tree add tree listed hash tree e get source add tree traverse this else if action equals action names add all previous gui items clear gui package get instance get tree model get test plan traverse this else if action equals action names check remove gui package gui package gui package get instance j meter tree node nodes gui package get tree listener get selected nodes remove mode true for int i nodes length 1 i 0 i gui package get tree model get current sub tree nodes i traverse this remove mode false if we are merging in another test plan we know the test plan is dirty now if action equals action names sub tree merged dirty true else dirty false check mode true hash tree whole tree gui package get instance get tree model get test plan whole tree traverse this check mode false gui package get instance set dirty dirty doaction actionevent doaction actionevent getactioncommand actionnames sub_tree_saved hashtree subtree hashtree getsource subtree actionnames sub_tree_loaded listedhashtree addtree listedhashtree getsource addtree actionnames add_all previousguiitems guipackage getinstance gettreemodel gettestplan actionnames check_remove guipackage guipackage guipackage getinstance jmetertreenode guipackage gettreelistener getselectednodes removemode guipackage gettreemodel getcurrentsubtree removemode actionnames sub_tree_merged checkmode hashtree wholetree guipackage getinstance gettreemodel gettestplan wholetree checkmode guipackage getinstance setdirty the tree traverses itself depth first calling process node for each object it encounters as it goes public void add node object node hash tree sub tree log debug node is class node get class j meter tree node tree node j meter tree node node if check mode only check if we have not found any differences so far if dirty if previous gui items contains key tree node if previous gui items get tree node equals tree node get test element dirty true else dirty true else if remove mode previous gui items remove tree node else previous gui items put tree node tree node get test element clone processnode addnode hashtree subtree getclass jmetertreenode treenode jmetertreenode checkmode previousguiitems containskey treenode previousguiitems treenode treenode gettestelement removemode previousguiitems treenode previousguiitems treenode treenode gettestelement indicates traversal has moved up a step and the visitor should remove the top node from it s stack structure public void subtract node subtractnode process path is called when a leaf is reached if a visitor wishes to generate lists of path elements to each leaf it should keep a stack data structure of nodes passed to it with add node and removing top items for every subtract node call public void process path addnode subtractnode processpath see command get action names public set get action names return commands getactionnames getactionnames public abstract report gui this name panel new name panel this name panel set background color white set name get static label abstractreportgui namepanel namepanel namepanel setbackground setname getstaticlabel see org apache jmeter gui j metergui component get label resource public string get label resource return report page jmeterguicomponent getlabelresource getlabelresource report_page public void configure test element test element element super configure test element element configuretestelement testelement configuretestelement public j popup menu create popup menu j popup menu pop new j popup menu j menu add menu new j menu j meter utils get res string add add menu add report menu factory make menu report menu factory config elements add add menu add report menu factory make menu report menu factory pre processors add add menu add report menu factory make menu report menu factory post processors add pop add add menu report menu factory add file menu pop return pop jpopupmenu createpopupmenu jpopupmenu jpopupmenu jmenu addmenu jmenu jmeterutils getresstring addmenu reportmenufactory makemenu reportmenufactory config_elements addmenu reportmenufactory makemenu reportmenufactory pre_processors addmenu reportmenufactory makemenu reportmenufactory post_processors addmenu reportmenufactory addfilemenu see org apache jmeter gui j metergui component get menu categories public collection get menu categories return arrays as list new string report menu factory tables jmeterguicomponent getmenucategories getmenucategories aslist reportmenufactory this implementaion differs a bit from the normal jmeter gui it uses a white background instead of the default grey return a panel containing the component title and name panel protected container make title panel vertical panel title panel new vertical panel title panel set background color white title panel add create title label title panel add get name panel return title panel maketitlepanel verticalpanel titlepanel verticalpanel titlepanel setbackground titlepanel createtitlelabel titlepanel getnamepanel titlepanel this implementaion differs a bit from the normal jmeter gui it uses a white background instead of the default grey protected component create title label j label title label new j label get static label font cur font title label get font title label set font cur font derive font float cur font get size 4 title label set background color white return title label createtitlelabel jlabel titlelabel jlabel getstaticlabel curfont titlelabel getfont titlelabel setfont curfont derivefont curfont getsize titlelabel setbackground titlelabel private static final string client choice jms client choice non nls 1 public subscriber sampler client_choice client_choice subscribersampler public void test ended string test test ended testended testended public void test started string test test started teststarted teststarted test ended is called by jmeter s engine clears the client pool public void test ended log debug subscriber sampler test ended called client pool clear client testended testended subscribersampler testended clientpool clearclient see junit framework test listener start test junit framework test public void test started testlistener starttest teststarted public void test iteration start loop iteration event event testiterationstart loopiterationevent create the on message subscriber client and set the sampler as the message listener private on message subscriber init listener client on message subscriber sub on message subscriber client pool get this if sub null sub new on message subscriber this get usejndi properties as boolean this getjndi initial context factory this get provider url this get connection factory this get topic this is use auth this get username this get password sub set message listener this sub resume client pool add client sub client pool put this sub log debug subscriber sampler init listener client called log debug loop count this get iterations return sub onmessagesubscriber onmessagesubscriber initlistenerclient onmessagesubscriber onmessagesubscriber clientpool onmessagesubscriber getusejndipropertiesasboolean getjndiinitialcontextfactory getproviderurl getconnectionfactory gettopic isuseauth getusername getpassword setmessagelistener clientpool addclient clientpool subscribersampler initlistenerclient getiterations create the receive subscriber client for the sampler private void init receive client this subscriber new receive subscriber this get usejndi properties as boolean this getjndi initial context factory this get provider url this get connection factory this get topic this is use auth this get username this get password this subscriber resume client pool add client this subscriber log debug subscriber sampler init receive client called receivesubscriber initreceiveclient receivesubscriber getusejndipropertiesasboolean getjndiinitialcontextfactory getproviderurl getconnectionfactory gettopic isuseauth getusername getpassword clientpool addclient subscribersampler initreceiveclient sample method will check which client it should use and call the appropriate client specific sample method return the appropriate sample result public sample result sample if this get client choice equals jms subscriber gui receive rsc return sample with receive else return sample with listener sampleresult getclientchoice jmssubscribergui receive_rsc samplewithreceive samplewithlistener sample will block until messages are received return the sample result private sample result sample with listener sample result result new sample result result set sample label get name init listener client int loop this get iteration count result sample start while this count 0 loop try thread sleep 0 50 catch interrupted exception e log debug e get message result sample end result set response message loop samples messages recieved synchronized this need to synch because buffer is shared with on message handler if this get read response as boolean result set response data this buffer to string get bytes else result set bytes this buffer to string get bytes length result set successful true result set response code loop message s recieved successfully result set sampler data not applicable result set sample count loop this reset count return result sampleresult samplewithlistener sampleresult sampleresult setsamplelabel getname initlistenerclient getiterationcount samplestart interruptedexception getmessage sampleend setresponsemessage onmessagehandler getreadresponseasboolean setresponsedata tostring getbytes setbytes tostring getbytes setsuccessful setresponsecode setsamplerdata setsamplecount resetcount sample method uses the receive subscriber client instead of on message approach return the sample result private sample result sample with receive sample result result new sample result result set sample label get name if this subscriber null this init receive client this subscriber start int loop this get iteration count this subscriber set loop loop result sample start while this subscriber count 0 loop try thread sleep 0 50 catch interrupted exception e log debug e get message result sample end result set response message loop samples messages recieved if this get read response as boolean result set response data this subscriber get message get bytes else result set bytes this subscriber get message get bytes length result set successful true result set response code loop message s recieved successfully result set sampler data not applicable result set sample count loop this subscriber reset return result receivesubscriber onmessage sampleresult samplewithreceive sampleresult sampleresult setsamplelabel getname initreceiveclient getiterationcount setloop samplestart interruptedexception getmessage sampleend setresponsemessage getreadresponseasboolean setresponsedata getmessage getbytes setbytes getmessage getbytes setsuccessful setresponsecode setsamplerdata setsamplecount the sampler implements message listener directly and sets itself as the listener with the topic subscriber public synchronized void on message message message try if message instanceof text message text message msg text message message string content msg get text if content null this buffer append content count 1 catch jms exception e log error e get message messagelistener topicsubscriber onmessage textmessage textmessage textmessage gettext jmsexception getmessage increment the count and return the new value param increment return the new value private synchronized int count int increment this counter increment return this counter reset count will set the counter to zero and set the length of the string buffer to zero private synchronized void reset count this counter 0 this buffer set length 0 resetcount stringbuffer resetcount setlength get set methods set the client choice there are two options receive susbscriber and on message subscriber public void set client choice string choice set property client choice choice receivesusbscriber onmessagesubscriber setclientchoice setproperty client_choice return the client choice return the client choice either receive rsc or on message rsc public string get client choice string choice get property as string client choice convert the old test plan entry which is the language dependent string to the resource name if choice equals receive str choice jms subscriber gui receive rsc else if choice equals jms subscriber gui receive rsc choice jms subscriber gui on message rsc return choice receive_rsc on_message_rsc getclientchoice getpropertyasstring client_choice receive_str jmssubscribergui receive_rsc jmssubscribergui receive_rsc jmssubscribergui on_message_rsc constructor public graph accum log debug start graph annum1 log debug end graph annum1 graphaccum graphannum1 graphannum1 constructor with model set param model model which this object represents public graph accum graph accum model model this log debug start graph annum2 set model model log debug end graph annum2 graphaccum graphaccummodel graphannum2 setmodel graphannum2 set model which this object represents param model model which this object represents private void set model object model log debug start set model1 this model graph accum model model this model add graph accum listener this repaint log debug end set model1 setmodel setmodel1 graphaccummodel addgraphaccumlistener setmodel1 set the visualizer param visualizer visualizer of this object public void set visualizer object visualizer if log is debug enabled log debug set visualizer1 setting visualizer visualizer this visualizer graph accum visualizer visualizer setvisualizer isdebugenabled setvisualizer1 graphaccumvisualizer the legend is only printed once during sampling this sets the variable that indicates whether the legend has been printed yet or not param value variable that indicates whether the legend has been printed yet public void set no legend yet boolean value no legend yet value setnolegendyet nolegendyet gets the preferred scrollable viewport size attribute of the graph object return the preferred scrollable viewport size value public dimension get preferred scrollable viewport size return this get preferred size preferredscrollableviewportsize preferredscrollableviewportsize getpreferredscrollableviewportsize getpreferredsize gets the scrollable unit increment attribute of the graph object return the scrollable unit increment value public int get scrollable unit increment rectangle visible rect int orientation int direction return 5 scrollableunitincrement scrollableunitincrement getscrollableunitincrement visiblerect gets the scrollable block increment attribute of the graph object return the scrollable block increment value public int get scrollable block increment rectangle visible rect int orientation int direction return int visible rect width 9 scrollableblockincrement scrollableblockincrement getscrollableblockincrement visiblerect visiblerect gets the scrollable tracks viewport width attribute of the graph object return the scrollable tracks viewport width value public boolean get scrollable tracks viewport width return false scrollabletracksviewportwidth scrollabletracksviewportwidth getscrollabletracksviewportwidth gets the scrollable tracks viewport height attribute of the graph object return the scrollable tracks viewport height value public boolean get scrollable tracks viewport height return true scrollabletracksviewportheight scrollabletracksviewportheight getscrollabletracksviewportheight the legend is only printed once during sampling this returns the variable that indicates whether the legend has been printed yet or not return value variable that indicates whether the legend has been printed yet public boolean get no legend yet return no legend yet getnolegendyet nolegendyet redraws the gui public void update gui log debug start update gui1 repaint log debug end update gui1 updategui updategui1 updategui1 redraws the gui if no rescaling of the graph is needed param one sample sample to be added public void update gui final sample result one sample log debug start update gui2 final int x pos model get sample count swing utilities invoke later new runnable public void run graphics g get graphics if g null draw sample x pos plot x width one sample g log debug end update gui2 onesample updategui sampleresult onesample updategui2 xpos getsamplecount swingutilities invokelater getgraphics drawsample xpos plot_x_width onesample updategui2 swing utilities invoke later new runnable public void run graphics g get graphics if g null draw sample x pos plot x width one sample g swingutilities invokelater getgraphics drawsample xpos plot_x_width onesample public void paint component graphics g super paint component g log debug start paint component1 synchronized model get list for repainting set this to false because all the points needs to be redrawn so no need shouldn t use the previous pts previous pts alloc false iterator e model get list iterator for int i 0 e has next i sample result s sample result e next draw sample i plot x width s g log debug end paint component1 paintcomponent paintcomponent paintcomponent1 getlist previouspts previousptsalloc getlist hasnext sampleresult sampleresult drawsample plot_x_width paintcomponent1 clears this graph public void clear data set no legend yet true j panel visualizer get white canvas remove all previous pts null cleardata setnolegendyet jpanel getwhitecanvas removeall previouspts private void draw sample int x sample result one sample graphics g log debug start draw sample1 used to keep track of accumulated load times of components int last level 0 number of components int comp count 0 sample result result list one sample get sub results int result list count 0 allocate previous pts only the first time if previous pts alloc result list count result list length previous pts new point result list count 2 color curr color color black j panel l panel j panel visualizer get white canvas j panel legend panel new j panel grid bag layout grid bag new grid bag layout grid bag constraints gbc new grid bag constraints legend panel set layout grid bag l panel add legend panel dimension d this get size set the total time to load the sample long total time one sample get time if the page has other components then set the total time to be that including all its components load time if log is debug enabled log debug draw sample1 total time total time int data int total time d height model get max g set color curr color if previous pts alloc if first dot just draw the point g draw line x width d height data x width d height data 1 else otherwise draw from previous point g draw line previous pts 0 x width previous pts 0 y x width d height data store current total time point previous pts 0 new point x width d height data if no legend yet gbc gridx 0 gbc gridy comp count gbc anchor grid bag constraints west gbc weightx 1 0 gbc insets new insets 0 10 0 0 j label total time label new j label total time one sample to string total time label set foreground curr color grid bag set constraints total time label gbc legend panel add total time label plot the time of the page itself without all its components if log is debug enabled log debug draw sample1 main page load time one sample get time data int one sample get time d height model get max curr color color helper change color cyclic increment curr color 40 g set color curr color if previous pts alloc if first dot just draw the point g draw line x width d height data x width d height data 1 else otherwise draw from previous point g draw line previous pts 1 x width previous pts 1 y x width d height data store load time without components previous pts 1 new point x width d height data if no legend yet gbc gridx 0 gbc gridy comp count gbc anchor grid bag constraints west gbc weightx 1 0 gbc insets new insets 0 10 0 0 j label main time label new j label one sample to string main time label set foreground curr color grid bag set constraints main time label gbc legend panel add main time label last level data plot the times of the total times components int curr previous pts 2 if result list null for int i 0 i result list length i sample result component res result list i if log is debug enabled log debug draw sample1 component res component res get sample label loading time component res get time data int component res get time d height model get max data last level curr color color helper change color cyclic increment curr color 100 g set color curr color if previous pts alloc if first dot just draw the point g draw line x width d height data x width d height data 1 else otherwise draw from previous point g draw line previous pts curr previous pts x width previous pts curr previous pts y x width d height data store the current plot previous pts curr previous pts new point x width d height data if no legend yet gbc gridx 0 gbc gridy comp count gbc anchor grid bag constraints west gbc weightx 1 0 gbc insets new insets 0 10 0 0 j label comp time label new j label component res get sample label comp time label set foreground curr color grid bag set constraints comp time label gbc legend panel add comp time label last level data if no legend yet no legend yet false l panel repaint l panel revalidate set the previous pts alloc to true here and not after allocation because the rest of the codes also depend on previous pts alloc to be false if first time plotting the graph i e there are no previous points if previous pts alloc previous pts alloc true log debug end draw sample1 drawsample sampleresult onesample drawsample1 lastlevel compcount sampleresult resultlist onesample getsubresults resultlistcount previouspts previousptsalloc resultlistcount resultlist previouspts resultlistcount currcolor jpanel lpanel jpanel getwhitecanvas jpanel legendpanel jpanel gridbaglayout gridbag gridbaglayout gridbagconstraints gridbagconstraints legendpanel setlayout gridbag lpanel legendpanel getsize totaltime onesample gettime isdebugenabled drawsample1 totaltime totaltime getmax setcolor currcolor previousptsalloc drawline drawline previouspts previouspts previouspts nolegendyet compcount gridbagconstraints jlabel totaltimelabel jlabel onesample tostring totaltimelabel setforeground currcolor gridbag setconstraints totaltimelabel legendpanel totaltimelabel isdebugenabled drawsample1 onesample gettime onesample gettime getmax currcolor colorhelper changecolorcyclicincrement currcolor setcolor currcolor previousptsalloc drawline drawline previouspts previouspts previouspts nolegendyet compcount gridbagconstraints jlabel maintimelabel jlabel onesample tostring maintimelabel setforeground currcolor gridbag setconstraints maintimelabel legendpanel maintimelabel lastlevel currpreviouspts resultlist resultlist sampleresult componentres resultlist isdebugenabled drawsample1 componentres componentres getsamplelabel componentres gettime componentres gettime getmax lastlevel currcolor colorhelper changecolorcyclicincrement currcolor setcolor currcolor previousptsalloc drawline drawline previouspts currpreviouspts previouspts currpreviouspts previouspts currpreviouspts nolegendyet compcount gridbagconstraints jlabel comptimelabel jlabel componentres getsamplelabel comptimelabel setforeground currcolor gridbag setconstraints comptimelabel legendpanel comptimelabel lastlevel nolegendyet nolegendyet lpanel lpanel previousptsalloc previousptsalloc previousptsalloc previousptsalloc drawsample1 protected field string editor super text field new j text field text field add action listener this text field add focus listener this fieldstringeditor textfield jtextfield textfield addactionlistener textfield addfocuslistener public string get as text return text field get text getastext textfield gettext public void set as text string value initial value value text field set text value setastext initialvalue textfield settext public object get value return get as text getvalue getastext public void set value object value if value instanceof string set as text string value else throw new illegal argument exception setvalue setastext illegalargumentexception see java beans property editor get custom editor public component get custom editor return text field propertyeditor getcustomeditor getcustomeditor textfield public void fire property change string new value get as text if initial value equals new value return initial value new value super fire property change firepropertychange newvalue getastext initialvalue newvalue initialvalue newvalue firepropertychange see java awt event action listener action performed java awt event action event public void action performed action event e fire property change actionlistener actionperformed actionevent actionperformed actionevent firepropertychange see java awt event focus listener focus gained java awt event focus event public void focus gained focus event e focuslistener focusgained focusevent focusgained focusevent see java awt event focus listener focus lost java awt event focus event public void focus lost focus event e fire property change focuslistener focuslost focusevent focuslost focusevent firepropertychange handle the about action by displaying the about apache j meter dialog box the dialog box is not modal because those should be avoided if at all possible public void do action action event e if e get action command equals action names about this about jmeter doaction actionevent getactioncommand actionnames provide the list of action names that are available in this command public set get action names return about command command set getactionnames aboutcommand commandset called by about button raises about dialog currently the about box has the product image and the copyright notice the dialog box is centered over the main frame void about j frame main frame gui package get instance get main frame if about null about new j dialog main frame about apache j meter false about add mouse listener new mouse adapter public void mouse clicked mouse event e about set visible false j label jmeter new j label j meter utils get image jmeter jpg j label copyright new j label j meter utils getj meter copyright j label center j label rights new j label all rights reserved j label center j label version new j label apache j meter version j meter utils getj meter version j label center j panel infos new j panel infos set opaque false infos set layout new grid layout 0 1 infos set border new empty border 5 5 5 5 infos add copyright infos add rights infos add version container panel about get content pane panel set layout new border layout panel set background color white panel add jmeter border layout north panel add infos border layout south note these lines center the about dialog in the current window some older swing versions have a bug in get location on screen and they may not make this behave properly point p main frame get location on screen dimension d1 main frame get size dimension d2 about get size about set location p x d1 width d2 width 2 p y d1 height d2 height 2 about pack about set visible true mainframe jframe mainframe guipackage getinstance getmainframe jdialog mainframe jmeter addmouselistener mouseadapter mouseclicked mouseevent setvisible jlabel jlabel jmeterutils getimage jlabel jlabel jmeterutils getjmetercopyright jlabel jlabel jlabel jlabel jlabel jlabel jmeter jmeterutils getjmeterversion jlabel jpanel jpanel setopaque setlayout gridlayout setborder emptyborder getcontentpane setlayout borderlayout setbackground borderlayout borderlayout getlocationonscreen mainframe getlocationonscreen mainframe getsize getsize setlocation setvisible about new j dialog main frame about apache j meter false about add mouse listener new mouse adapter public void mouse clicked mouse event e about set visible false jdialog mainframe jmeter addmouselistener mouseadapter mouseclicked mouseevent setvisible constructor for the work bench object public work bench string name boolean is root node set name name workbench workbench isrootnode setname public work bench workbench no arg constructor public constant timer gui init constanttimergui handle an error param e the exception that was thrown param thrower the j component that threw the exception public static void error exception e j component thrower j option pane show message dialog thrower e error j option pane error message jcomponent jcomponent joptionpane showmessagedialog joptionpane error_message public string get label resource return constant timer title non nls 1 getlabelresource constant_timer_title create the test element underlying this gui component see org apache jmeter gui j metergui component create test element public test element create test element constant timer timer new constant timer modify test element timer return timer jmeterguicomponent createtestelement testelement createtestelement constanttimer constanttimer modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element timer this configure test element timer constant timer timer set delay delay field get text testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement constanttimer setdelay delayfield gettext configure this gui component from the underlying test element see org apache jmeter gui j metergui component configure test element public void configure test element el super configure el delay field set text constant timer el get delay testelement jmeterguicomponent testelement testelement delayfield settext constanttimer getdelay initialize this component private void init set layout new vertical layout 5 vertical layout both vertical layout top set border make border add make title panel box delay panel box create horizontal box j label delay label new j label j meter utils get res string constant timer delay non nls 1 delay panel add delay label delay field new j text field 6 delay field set text default delay delay field set name delay field delay panel add delay field add delay panel setlayout verticallayout verticallayout verticallayout setborder makeborder maketitlepanel delaypanel createhorizontalbox jlabel delaylabel jlabel jmeterutils getresstring constant_timer_delay delaypanel delaylabel delayfield jtextfield delayfield settext default_delay delayfield setname delay_field delaypanel delayfield delaypanel see org apache jmeter gui j metergui component clear gui public void clear gui delay field set text default delay super clear gui jmeterguicomponent cleargui cleargui delayfield settext default_delay cleargui private transient thread local thread cache public cache manager set property new boolean property clear false clear cache threadlocal threadcache cachemanager setproperty booleanproperty clearcache private final string last modified private final string etag public cache entry string last modified string etag this last modified last modified this etag etag lastmodified cacheentry lastmodified lastmodified lastmodified this etag etag public string get last modified return last modified getlastmodified lastmodified return last modified public string get etag return etag lastmodified getetag return etag public string to string return last modified etag tostring lastmodified save the last modified and etag headers if the result is cacheable param conn connection param res result public void save details url connection conn sample result res if is cacheable res string last modified conn get header field http constants interface last modified string etag conn get header field http constants interface etag string url conn geturl to string set cache last modified etag url savedetails urlconnection sampleresult iscacheable lastmodified getheaderfield httpconstantsinterface last_modified getheaderfield httpconstantsinterface tostring setcache lastmodified save the last modified and etag headers if the result is cacheable param method param res result public void save details http method method sample result res throws uri exception if is cacheable res string last modified get header method http constants interface last modified string etag get header method http constants interface etag string url method geturi to string set cache last modified etag url savedetails httpmethod sampleresult uriexception iscacheable lastmodified getheader httpconstantsinterface last_modified getheader httpconstantsinterface tostring setcache lastmodified helper method to save the cache entry private void set cache string last modified string etag string url if log is debug enabled log debug set both url last modified etag get cache put url new cache entry last modified etag setcache lastmodified isdebugenabled lastmodified getcache cacheentry lastmodified helper method to deal with missing headers private string get header http method method string name header hdr method get response header name return hdr null hdr get value null getheader httpmethod getresponseheader getvalue private boolean is cacheable sample result res final string response code res get response code return 200 compare to response code 0 non nls 1 299 compare to response code 0 non nls 1 iscacheable sampleresult responsecode getresponsecode compareto responsecode compareto responsecode check the cache and if there is a match set the headers br if modified since br if none match br param url url to look up in cache param method where to set the headers public void set headers url url http method method cache entry entry cache entry get cache get url to string if log is debug enabled log debug method get name oahc url to string entry if entry null final string last modified entry get last modified if last modified null method set request header http constants interface if modified since last modified final string etag entry get etag if etag null method set request header http constants interface if none match etag setheaders httpmethod cacheentry cacheentry getcache tostring isdebugenabled getname tostring lastmodified getlastmodified lastmodified setrequestheader httpconstantsinterface if_modified_since lastmodified getetag setrequestheader httpconstantsinterface if_none_match check the cache and if there is a match set the headers br if modified since br if none match br param url url to look up in cache param conn where to set the headers public void set headers httpurl connection conn url url cache entry entry cache entry get cache get url to string if log is debug enabled log debug conn get request method java url to string entry if entry null final string last modified entry get last modified if last modified null conn add request property http constants interface if modified since last modified final string etag entry get etag if etag null conn add request property http constants interface if none match etag setheaders httpurlconnection cacheentry cacheentry getcache tostring isdebugenabled getrequestmethod tostring lastmodified getlastmodified lastmodified addrequestproperty httpconstantsinterface if_modified_since lastmodified getetag addrequestproperty httpconstantsinterface if_none_match private map get cache return map thread cache get getcache threadcache public boolean get clear each iteration return get property as boolean clear getcleareachiteration getpropertyasboolean public void set clear each iteration boolean clear set property new boolean property clear clear setcleareachiteration setproperty booleanproperty public void clear super clear clear cache clearcache private void clear cache log debug clear cache thread cache new thread local protected object initial value return new hash map clearcache threadcache threadlocal initialvalue hashmap log debug clear cache thread cache new thread local protected object initial value return new hash map threadcache threadlocal initialvalue hashmap public void test started teststarted public void test ended testended public void test started string host teststarted public void test ended string host testended public void test iteration start loop iteration event event if get clear each iteration clear cache testiterationstart loopiterationevent getcleareachiteration clearcache private static class mutable integer private int integer mutable integer int value integer value mutableinteger mutableinteger integer value int incr return integer return integer public int int value return integer intvalue public throughput controller set style bynumber set per thread true set max throughput 1 set percent throughput 100 run this time false throughputcontroller setstyle setperthread setmaxthroughput setpercentthroughput runthistime public void set style int style set property new integer property style style setstyle setproperty integerproperty public int get style return get property as int style getstyle getpropertyasint public void set per thread boolean per thread set property new boolean property perthread per thread setperthread perthread setproperty booleanproperty perthread public boolean is per thread return get property as boolean perthread isperthread getpropertyasboolean public void set max throughput int max throughput set property new integer property maxthroughput max throughput setmaxthroughput maxthroughput setproperty integerproperty maxthroughput public void set max throughput string max throughput set property new string property maxthroughput max throughput setmaxthroughput maxthroughput setproperty stringproperty maxthroughput public string get max throughput return get property as string maxthroughput getmaxthroughput getpropertyasstring protected int get max throughput as int j meter property prop get property maxthroughput int ret val 1 if prop instanceof integer property ret val integer property prop get int value else try ret val integer parse int prop get string value catch number format exception e return ret val getmaxthroughputasint jmeterproperty getproperty retval integerproperty retval integerproperty getintvalue retval parseint getstringvalue numberformatexception retval public void set percent throughput float percent throughput set property new float property percentthroughput percent throughput setpercentthroughput percentthroughput setproperty floatproperty percentthroughput public void set percent throughput string percent throughput set property new string property percentthroughput percent throughput setpercentthroughput percentthroughput setproperty stringproperty percentthroughput public string get percent throughput return get property as string percentthroughput getpercentthroughput getpropertyasstring protected float get percent throughput as float j meter property prop get property percentthroughput float ret val 100 if prop instanceof float property ret val float property prop get float value else try ret val float parse float prop get string value catch number format exception e return ret val getpercentthroughputasfloat jmeterproperty getproperty retval floatproperty retval floatproperty getfloatvalue retval parsefloat getstringvalue numberformatexception retval private int get executions if is per thread synchronized counter lock return global num executions int value return num executions getexecutions isperthread counterlock globalnumexecutions intvalue numexecutions see org apache jmeter control controller next public sampler next if run this time return super next return null runthistime decide whether to return any samplers on this iteration private boolean decide int executions int iterations if get style bynumber return executions get max throughput as int return 100 0 executions 50 0 iterations 1 get percent throughput as float getstyle getmaxthroughputasint getpercentthroughputasfloat see org apache jmeter control controller is done public boolean is done if sub controllers and samplers size 0 return true else if get style bynumber get executions get max throughput as int current get sub controllers size return true else return false isdone isdone subcontrollersandsamplers getstyle getexecutions getmaxthroughputasint getsubcontrollers public object clone throughput controller clone throughput controller super clone clone num executions num executions clone iteration iteration clone run this time false ensure global counters and lock are shared across threads in the group clone global iteration global iteration clone global num executions global num executions clone counter lock counter lock return clone throughputcontroller throughputcontroller numexecutions numexecutions runthistime globaliteration globaliteration globalnumexecutions globalnumexecutions counterlock counterlock public void iteration start loop iteration event iter event if is per thread synchronized counter lock global iteration incr run this time decide global num executions int value global iteration int value if run this time global num executions incr else iteration run this time decide num executions iteration if run this time num executions iterationstart loopiterationevent iterevent isperthread counterlock globaliteration runthistime globalnumexecutions intvalue globaliteration intvalue runthistime globalnumexecutions runthistime numexecutions runthistime numexecutions public void test started synchronized counter lock global num executions new mutable integer 0 global iteration new mutable integer 1 teststarted counterlock globalnumexecutions mutableinteger globaliteration mutableinteger public void test started string host test started teststarted teststarted public void test ended testended public void test ended string host testended public void test iteration start loop iteration event event testiterationstart loopiterationevent no arg constructor public uniform random timer gui init uniformrandomtimergui handle an error param e the exception that was thrown param thrower the j component that threw the exception public static void error exception e j component thrower j option pane show message dialog thrower e error j option pane error message jcomponent jcomponent joptionpane showmessagedialog joptionpane error_message public string get label resource return uniform timer title non nls 1 getlabelresource uniform_timer_title create the test element underlying this gui component see org apache jmeter gui j metergui component create test element public test element create test element random timer timer new uniform random timer modify test element timer return timer jmeterguicomponent createtestelement testelement createtestelement randomtimer uniformrandomtimer modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element timer this configure test element timer random timer timer set delay delay field get text random timer timer set range range field get text testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement randomtimer setdelay delayfield gettext randomtimer setrange rangefield gettext configure this gui component from the underlying test element see org apache jmeter gui j metergui component configure test element public void configure test element el super configure el delay field set text el get property as string random timer delay range field set text el get property as string random timer range testelement jmeterguicomponent testelement testelement delayfield settext getpropertyasstring randomtimer rangefield settext getpropertyasstring randomtimer initialize this component private void init set layout new vertical layout 5 vertical layout both set border make border add make title panel thread delay properties j panel thread delay props panel new j panel thread delay props panel set layout new vertical layout 5 vertical layout left thread delay props panel set border border factory create titled border j meter utils get res string thread delay properties non nls 1 delay deviation box delay dev panel box create horizontal box delay dev panel add new j label j meter utils get res string uniform timer range non nls 1 delay dev panel add box create horizontal strut 5 range field new j text field 6 range field set text default range range field set name range field delay dev panel add range field thread delay props panel add delay dev panel avg delay box avg delay panel box create horizontal box avg delay panel add new j label j meter utils get res string uniform timer delay non nls 1 avg delay panel add box create horizontal strut 5 delay field new j text field 6 delay field set text default delay delay field set name delay field avg delay panel add delay field thread delay props panel add avg delay panel add thread delay props panel set the initial focus to the range field new focus requester range field setlayout verticallayout verticallayout setborder makeborder maketitlepanel jpanel threaddelaypropspanel jpanel threaddelaypropspanel setlayout verticallayout verticallayout threaddelaypropspanel setborder borderfactory createtitledborder jmeterutils getresstring thread_delay_properties delaydevpanel createhorizontalbox delaydevpanel jlabel jmeterutils getresstring uniform_timer_range delaydevpanel createhorizontalstrut rangefield jtextfield rangefield settext default_range rangefield setname range_field delaydevpanel rangefield threaddelaypropspanel delaydevpanel avgdelaypanel createhorizontalbox avgdelaypanel jlabel jmeterutils getresstring uniform_timer_delay avgdelaypanel createhorizontalstrut delayfield jtextfield delayfield settext default_delay delayfield setname delay_field avgdelaypanel delayfield threaddelaypropspanel avgdelaypanel threaddelaypropspanel focusrequester rangefield public void clear gui range field set text default range delay field set text default delay super clear gui cleargui rangefield settext default_range delayfield settext default_delay cleargui public workers impl super worker new linked list workersimpl linkedlist public list get worker return worker getworker public void add worker worker value this worker add value addworker private ldap config gui ldap default panel public ldap test sampler gui init ldapconfiggui ldapdefaultpanel ldaptestsamplergui a newly created component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui param element the test element to configure public void configure test element element super configure element login panel configure element ldap default panel configure element testelement testelement loginpanel ldapdefaultpanel public test element create test element ldap sampler sampler new ldap sampler modify test element sampler return sampler testelement createtestelement ldapsampler ldapsampler modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element sampler sampler clear ldap sampler sampler add test element ldap default panel create test element ldap sampler sampler add test element login panel create test element this configure test element sampler testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement ldapsampler addtestelement ldapdefaultpanel createtestelement ldapsampler addtestelement loginpanel createtestelement configuretestelement implements j metergui component clear gui public void clear gui super clear gui ldap default panel clear gui login panel clear gui jmeterguicomponent cleargui cleargui cleargui ldapdefaultpanel cleargui loginpanel cleargui public string get label resource return ldap testing title non nls 1 getlabelresource ldap_testing_title private void init set layout new border layout 0 5 set border make border main panel vertical panel main panel new vertical panel login panel new login config gui false ldap default panel new ldap config gui false login panel set border border factory create titled border j meter utils get res string login config non nls 1 add make title panel border layout north main panel add login panel main panel add ldap default panel add main panel border layout center setlayout borderlayout setborder makeborder verticalpanel mainpanel verticalpanel loginpanel loginconfiggui ldapdefaultpanel ldapconfiggui loginpanel setborder borderfactory createtitledborder jmeterutils getresstring login_config maketitlepanel borderlayout mainpanel loginpanel mainpanel ldapdefaultpanel mainpanel borderlayout create the authorization authorization string url string user string pass string domain string realm seturl url set user user set pass pass set domain domain set realm realm setuser setpass setdomain setrealm public boolean expects modification return false expectsmodification public authorization this public void add config element config element config addconfigelement configelement public synchronized string geturl return get property as string url getpropertyasstring public synchronized void seturl string url set property url url setproperty public synchronized string get user return get property as string username getuser getpropertyasstring public synchronized void set user string user set property username user setuser setproperty public synchronized string get pass return get property as string password getpass getpropertyasstring public synchronized void set pass string pass set property password pass setpass setproperty public synchronized string get domain return get property as string domain getdomain getpropertyasstring public synchronized void set domain string domain set property domain domain setdomain setproperty public synchronized string get realm return get property as string realm getrealm getpropertyasstring public synchronized void set realm string realm set property realm realm setrealm setproperty used for saving entries to a file public string to string return geturl tab get user tab get pass tab get domain tab get realm tostring getuser getpass getdomain getrealm public string to basic header return basic base64 encoder encode get user get pass tobasicheader base64encoder getuser getpass protected buffered image image null public abstract chart super bufferedimage abstractchart public string getx axis return get property as string report chart x axis getxaxis getpropertyasstring report_chart_x_axis public string get formattedx axis string text getx axis if text index of 1 text text substring text index of 1 text j orphan utils replace all chars text return text getformattedxaxis getxaxis indexof indexof jorphanutils replaceallchars _ return text public void setx axis string field set property report chart x axis field setxaxis setproperty report_chart_x_axis public string gety axis return get property as string report chart y axis getyaxis getpropertyasstring report_chart_y_axis public void sety axis string scale set property report chart y axis scale setyaxis setproperty report_chart_y_axis public string getx label return get property as string report chart x label getxlabel getpropertyasstring report_chart_x_label the x data labels should be either the filename date or some other series of values param label public void setx label string label set property report chart x label label setxlabel setproperty report_chart_x_label public string gety label return get property as string report chart y label getylabel getpropertyasstring report_chart_y_label public void sety label string label set property report chart y label label setylabel setproperty report_chart_y_label the title is a the name for the chart a page link will be generated using the title the title will also be used for a page index return chart title public string get title return get property as string report chart title gettitle getpropertyasstring report_chart_title the title is a the name for the chart a page link will be generated using the title the title will also be used for a page index param title public void set title string title set property report chart title title settitle setproperty report_chart_title the caption is a description for the chart explaining what the chart means return caption public string get caption return get property as string report chart caption getcaption getpropertyasstring report_chart_caption the caption is a description for the chart explaining what the chart means param caption public void set caption string caption set property report chart caption caption setcaption setproperty report_chart_caption if no width is set the default is returned return width public int get width int w get property as int report chart width if w 0 return default width else return w getwidth getpropertyasint report_chart_width default_width set the width of the graph param width public void set width string width set property report chart width string value of width setwidth setproperty report_chart_width valueof if the height is not set the default is returned return height public int get height int h get property as int report chart height if h 0 return default height else return h getheight getpropertyasint report_chart_height default_height set the height of the graph param height public void set height string height set property report chart height string value of height setheight setproperty report_chart_height valueof subclasses will need to implement the method by doing the following 1 get the x and y axis 2 filter the table data 3 pass the data to the chart library 4 return the generated chart this makes it easy to get the buffered image return image public buffered image get buffered image return this image bufferedimage bufferedimage getbufferedimage in case an user wants set the bufferd image param img public void set buffered image buffered image img this image img bufferdimage setbufferedimage bufferedimage convienance method for getting the selected value rather than use method invoke object object it s simpler to just check which column is selected and call the method directly param stat return value public double get value sampling stat calculator stat if this getx axis equals abstract table report table 50 percent return stat get percent point 50 double value else if this getx axis equals abstract table report table 90 percent return stat get percent point 90 double value else if this getx axis equals abstract table report table error rate return stat get error percentage else if this getx axis equals abstract table report table max return stat get max double value else if this getx axis equals abstract table report table mean return stat get mean else if this getx axis equals abstract table report table median return stat get median double value else if this getx axis equals abstract table report table min return stat get min double value else if this getx axis equals abstract table report table response rate return stat get rate else if this getx axis equals abstract table report table transfer rate return the pagesize divided by 1024 to get kilobytes return stat getkb per second else return double nan getvalue samplingstatcalculator getxaxis abstracttable report_table_50_percent getpercentpoint doublevalue getxaxis abstracttable report_table_90_percent getpercentpoint doublevalue getxaxis abstracttable report_table_error_rate geterrorpercentage getxaxis abstracttable report_table_max getmax doublevalue getxaxis abstracttable report_table_mean getmean getxaxis abstracttable report_table_median getmedian doublevalue getxaxis abstracttable report_table_min getmin doublevalue getxaxis abstracttable report_table_response_rate getrate getxaxis abstracttable report_table_transfer_rate getkbpersecond private button group group public regex extractor gui super init buttongroup regexextractorgui public string get label resource return regex extractor title non nls 1 getlabelresource regex_extractor_title public void configure test element el super configure el if el instanceof regex extractor regex extractor re regex extractor el use headers set selected re use headers use body set selected re use body use unescaped body set selected re use unescaped body useurl set selected re use url use code set selected re use code use message set selected re use message regex field set text re get regex template field set text re get template default field set text re get default value match number field set text re get match number as string ref name field set text re get ref name testelement regexextractor regexextractor regexextractor useheaders setselected useheaders usebody setselected usebody useunescapedbody setselected useunescapedbody setselected useurl usecode setselected usecode usemessage setselected usemessage regexfield settext getregex templatefield settext gettemplate defaultfield settext getdefaultvalue matchnumberfield settext getmatchnumberasstring refnamefield settext getrefname see org apache jmeter gui j metergui component create test element public test element create test element regex extractor extractor new regex extractor modify test element extractor return extractor jmeterguicomponent createtestelement testelement createtestelement regexextractor regexextractor modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element extractor super configure test element extractor if extractor instanceof regex extractor regex extractor regex regex extractor extractor regex set use field group get selection get action command regex set ref name ref name field get text regex set regex regex field get text regex set template template field get text regex set default value default field get text regex set match number match number field get text testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement regexextractor regexextractor regexextractor setusefield getselection getactioncommand setrefname refnamefield gettext setregex regexfield gettext settemplate templatefield gettext setdefaultvalue defaultfield gettext setmatchnumber matchnumberfield gettext implements j metergui component clear gui public void clear gui super clear gui use body set selected true regex field set text non nls 1 template field set text non nls 1 default field set text non nls 1 ref name field set text non nls 1 match number field set text non nls 1 jmeterguicomponent cleargui cleargui cleargui usebody setselected regexfield settext templatefield settext defaultfield settext refnamefield settext matchnumberfield settext private void init set layout new border layout set border make border box box box create vertical box box add make title panel box add make source panel add box border layout north add make parameter panel border layout center setlayout borderlayout setborder makeborder createverticalbox maketitlepanel makesourcepanel borderlayout makeparameterpanel borderlayout private j panel make source panel j panel panel new j panel panel set border border factory create titled border j meter utils get res string regex source non nls 1 use body new j radio button j meter utils get res string regex src body non nls 1 use unescaped body new j radio button j meter utils get res string regex src body unescaped non nls 1 use headers new j radio button j meter utils get res string regex src hdrs non nls 1 useurl new j radio button j meter utils get res string regex src url non nls 1 use code new j radio button j meter utils get res string assertion code resp non nls 1 use message new j radio button j meter utils get res string assertion message resp non nls 1 group new button group group add use body group add use unescaped body group add use headers group add useurl group add use code group add use message panel add use body panel add use unescaped body panel add use headers panel add useurl panel add use code panel add use message use body set selected true so we know which button is selected use body set action command regex extractor use body use unescaped body set action command regex extractor use body unescaped use headers set action command regex extractor use hdrs useurl set action command regex extractor use url use code set action command regex extractor use code use message set action command regex extractor use message return panel jpanel makesourcepanel jpanel jpanel setborder borderfactory createtitledborder jmeterutils getresstring regex_source usebody jradiobutton jmeterutils getresstring regex_src_body useunescapedbody jradiobutton jmeterutils getresstring regex_src_body_unescaped useheaders jradiobutton jmeterutils getresstring regex_src_hdrs jradiobutton jmeterutils getresstring regex_src_url usecode jradiobutton jmeterutils getresstring assertion_code_resp usemessage jradiobutton jmeterutils getresstring assertion_message_resp buttongroup usebody useunescapedbody useheaders usecode usemessage usebody useunescapedbody useheaders usecode usemessage usebody setselected usebody setactioncommand regexextractor use_body useunescapedbody setactioncommand regexextractor use_body_unescaped useheaders setactioncommand regexextractor use_hdrs setactioncommand regexextractor use_url usecode setactioncommand regexextractor use_code usemessage setactioncommand regexextractor use_message private j panel make parameter panel regex field new j labeled text field j meter utils get res string regex field non nls 1 template field new j labeled text field j meter utils get res string template field non nls 1 default field new j labeled text field j meter utils get res string default value field non nls 1 ref name field new j labeled text field j meter utils get res string ref name field non nls 1 match number field new j labeled text field j meter utils get res string match num field non nls 1 j panel panel new j panel new grid bag layout grid bag constraints gbc new grid bag constraints init constraints gbc add field panel ref name field gbc reset contraints gbc add field panel regex field gbc reset contraints gbc add field panel template field gbc reset contraints gbc add field panel match number field gbc reset contraints gbc gbc weighty 1 add field panel default field gbc return panel jpanel makeparameterpanel regexfield jlabeledtextfield jmeterutils getresstring regex_field templatefield jlabeledtextfield jmeterutils getresstring template_field defaultfield jlabeledtextfield jmeterutils getresstring default_value_field refnamefield jlabeledtextfield jmeterutils getresstring ref_name_field matchnumberfield jlabeledtextfield jmeterutils getresstring match_num_field jpanel jpanel gridbaglayout gridbagconstraints gridbagconstraints initconstraints addfield refnamefield resetcontraints addfield regexfield resetcontraints addfield templatefield resetcontraints addfield matchnumberfield resetcontraints addfield defaultfield private void add field j panel panel j labeled text field field grid bag constraints gbc list item field get component list panel add component item get 0 gbc clone gbc gridx gbc weightx 1 gbc fill grid bag constraints horizontal panel add component item get 1 gbc clone addfield jpanel jlabeledtextfield gridbagconstraints getcomponentlist gridbagconstraints next line private void reset contraints grid bag constraints gbc gbc gridx 0 gbc gridy gbc weightx 0 gbc fill grid bag constraints none resetcontraints gridbagconstraints gridbagconstraints private void init constraints grid bag constraints gbc gbc anchor grid bag constraints northwest gbc fill grid bag constraints none gbc gridheight 1 gbc gridwidth 1 gbc gridx 0 gbc gridy 0 gbc weightx 0 gbc weighty 0 initconstraints gridbagconstraints gridbagconstraints gridbagconstraints public final static string on error action on error action protected on error test element super on_error_action onerror onerrortestelement public void set error action int value set property new integer property on error action value seterroraction setproperty integerproperty on_error_action public int get error action int value get property as int on error action return value geterroraction getpropertyasint on_error_action public boolean is continue return get error action on error continue iscontinue geterroraction on_error_continue public boolean is stop thread return get error action on error stopthread isstopthread geterroraction on_error_stopthread public boolean is stop test return get error action on error stoptest isstoptest geterroraction on_error_stoptest public boolean is stop test now return get error action on error stoptest now isstoptestnow geterroraction on_error_stoptest_now no arg constructor public thread group threadgroup set the total number of threads to start param num threads the number of threads public void set num threads int num threads set property new integer property num threads num threads numthreads setnumthreads numthreads setproperty integerproperty num_threads numthreads increment the number of active threads synchronized void incr number of threads number of threads incrnumberofthreads numberofthreads decrement the number of active threads synchronized void decr number of threads number of threads decrnumberofthreads numberofthreads get the number of active threads public synchronized int get number of threads return number of threads getnumberofthreads numberofthreads inherit doc public boolean is done return get sampler controller is done inheritdoc isdone getsamplercontroller isdone inherit doc public sampler next return get sampler controller next inheritdoc getsamplercontroller set whether scheduler is being used param scheduler true is scheduler is to be used public void set scheduler boolean scheduler set property new boolean property scheduler scheduler setscheduler setproperty booleanproperty get whether scheduler is being used return true if scheduler is being used public boolean get scheduler return get property as boolean scheduler getscheduler getpropertyasboolean set the absolute start time value param stime the start time value public void set start time long stime set property new long property start time stime starttime starttime setstarttime setproperty longproperty start_time get the absolute start time value return the start time value public long get start time return get property as long start time getstarttime getpropertyaslong start_time get the desired duration of the thread group test run return the duration in secs public long get duration return get property as long duration getduration getpropertyaslong set the desired duration of the thread group test run param duration in seconds public void set duration long duration set property new long property duration duration setduration setproperty longproperty get the startup delay return the delay in secs public long get delay return get property as long delay getdelay getpropertyaslong set the startup delay param delay in seconds public void set delay long delay set property new long property delay delay setdelay setproperty longproperty set the end time value param etime the end time value public void set end time long etime set property new long property end time etime endtime endtime setendtime setproperty longproperty end_time get the end time value return the end time value public long get end time return get property as long end time getendtime getpropertyaslong end_time set the ramp up value param ramp up the ramp up value public void set ramp up int ramp up set property new integer property ramp time ramp up rampup setrampup rampup setproperty integerproperty ramp_time rampup get the ramp up value return the ramp up value public int get ramp up return get property as int thread group ramp time getrampup getpropertyasint threadgroup ramp_time get the sampler controller return the sampler controller public controller get sampler controller controller c controller get property main controller get object value return c getsamplercontroller getproperty main_controller getobjectvalue set the sampler controller param c the sampler controller public void set sampler controller loop controller c c set continue forever false set property new test element property main controller c setsamplercontroller loopcontroller setcontinueforever setproperty testelementproperty main_controller get the number of threads return the number of threads public int get num threads return this get property as int thread group num threads getnumthreads getpropertyasint threadgroup num_threads add a test element param child the test element to add public void add test element test element child get sampler controller add test element child addtestelement testelement getsamplercontroller addtestelement inherit doc public void add iteration listener loop iteration listener lis get sampler controller add iteration listener lis inheritdoc additerationlistener loopiterationlistener getsamplercontroller additerationlistener inherit doc public void initialize controller c get sampler controller j meter property property c get property test element name property set object value get name copy our name into that of the controller property set running version property is running version otherwise name reverts c initialize inheritdoc getsamplercontroller jmeterproperty getproperty testelement setobjectvalue getname setrunningversion isrunningversion check if a sampler error should cause thread to stop return true if thread should stop public boolean get on error stop thread return get property as string thread group on sample error equals ignore case on sample error stopthread getonerrorstopthread getpropertyasstring threadgroup on_sample_error equalsignorecase on_sample_error_stopthread check if a sampler error should cause test to stop return true if test all threads should stop public boolean get on error stop test return get property as string thread group on sample error equals ignore case on sample error stoptest getonerrorstoptest getpropertyasstring threadgroup on_sample_error equalsignorecase on_sample_error_stoptest check if a sampler error should cause test to stop now return true if test all threads should stop immediately public boolean get on error stop test now return get property as string thread group on sample error equals ignore case on sample error stoptest now getonerrorstoptestnow getpropertyasstring threadgroup on_sample_error equalsignorecase on_sample_error_stoptest_now long saved value public long property string name long value super name this value value savedvalue longproperty public long property super longproperty see org apache jmeter testelement property j meter property set running version boolean public void set running version boolean running version saved value value super set running version running version jmeterproperty setrunningversion setrunningversion runningversion savedvalue setrunningversion runningversion see org apache jmeter testelement property j meter property recover running version org apache jmeter testelement test element public void recover running version test element owner value saved value jmeterproperty recoverrunningversion testelement recoverrunningversion testelement savedvalue public void set value int value this value value setvalue protected void set number value number n value n long value setnumbervalue longvalue protected void set number value string n throws number format exception value long parse long n setnumbervalue numberformatexception parselong see j meter property get string value public string get string value return long to string value jmeterproperty getstringvalue getstringvalue tostring see j meter property get object value public object get object value return new long value jmeterproperty getobjectvalue getobjectvalue public object clone long property prop long property super clone prop value value return prop longproperty longproperty see j meter property get boolean value public boolean get boolean value return get long value 0 true false jmeterproperty getbooleanvalue getbooleanvalue getlongvalue see j meter property get double value public double get double value return value jmeterproperty getdoublevalue getdoublevalue see j meter property get float value public float get float value return value jmeterproperty getfloatvalue getfloatvalue see j meter property get int value public int get int value return int value jmeterproperty getintvalue getintvalue see j meter property get long value public long get long value return value jmeterproperty getlongvalue getlongvalue public class bsf assertion bean info extends bsf bean info support public bsf assertion bean info super bsf assertion class bsfassertionbeaninfo bsfbeaninfosupport bsfassertionbeaninfo bsfassertion private boolean search found entries todo turn into parameter public ldap sampler searchfoundentries ldapsampler gets the username attribute of the ldap object return the username public string get username return get property as string config test element username getusername getpropertyasstring configtestelement gets the password attribute of the ldap object return the password public string get password return get property as string config test element password getpassword getpropertyasstring configtestelement sets the servername attribute of the server config object param servername the new servername value public void set servername string servername set property new string property servername servername serverconfig setservername setproperty stringproperty sets the port attribute of the server config object param port the new port value public void set port string port set property new string property port port serverconfig setport setproperty stringproperty gets the servername attribute of the ldap sampler object return the servername value public string get servername return get property as string servername ldapsampler getservername getpropertyasstring gets the port attribute of the ldap sampler object return the port value public string get port return get property as string port ldapsampler getport getpropertyasstring sets the rootdn attribute of the ldap sampler object param new rootdn the new rootdn value public void set rootdn string new rootdn this set property rootdn new rootdn ldapsampler newrootdn setrootdn newrootdn setproperty newrootdn gets the rootdn attribute of the ldap sampler object return the rootdn value public string get rootdn return get property as string rootdn ldapsampler getrootdn getpropertyasstring sets the test attribute of the ldap config object param new test the new test value add modify delete and search public void set test string new test this set property test new test ldapconfig newtest settest newtest setproperty newtest gets the test attribute of the ldap sampler object return the test value add modify delete and search public string get test return get property as string test ldapsampler gettest getpropertyasstring sets the user defined test attribute of the ldap sampler object param value the new user defined test value public void set user defined test boolean value set property new boolean property user defined value userdefinedtest ldapsampler userdefinedtest setuserdefinedtest setproperty booleanproperty user_defined gets the user defined test attribute of the ldap sampler object return the test value true or false if true it will do the user defined test else our own inbuild test case public boolean get user defined test return get property as boolean user defined userdefinedtest ldapsampler userdefinedtest getuserdefinedtest getpropertyasboolean user_defined sets the base entry dn attribute of the ldap sampler object param newbaseentry the new base entry dn value public void set base entrydn string newbaseentry set property new string property base entry dn newbaseentry ldapsampler setbaseentrydn setproperty stringproperty base_entry_dn gets the base entrydn attribute of the ldap sampler object return the base entry dn value public string get base entrydn return get property as string base entry dn baseentrydn ldapsampler getbaseentrydn getpropertyasstring base_entry_dn sets the arguments attribute of the ldap config object this will collect values from the table for user defined test case param value the arguments public void set arguments arguments value set property new test element property arguments value ldapconfig setarguments setproperty testelementproperty gets the arguments attribute of the ldap config object return the arguments user defined test case public arguments get arguments return arguments get property arguments get object value ldapconfig getarguments getproperty getobjectvalue collect all the value from the table arguments using this create the basic attributes this will create the basic attributes for the user defined test case for add test return the basic attributes private basic attributes get user attributes basic attribute basicattribute new basic attribute objectclass non nls 1 basicattribute add top non nls 1 basicattribute add person non nls 1 basicattribute add organizational person non nls 1 basicattribute add inet org person non nls 1 basic attributes attrs new basic attributes true attrs put basicattribute basic attribute attr property iterator iter get arguments iterator while iter has next argument item argument iter next get object value attr get basic attribute item get name item get value attrs put attr return attrs basicattributes testcase basicattributes basicattributes getuserattributes basicattribute basicattribute organizationalperson inetorgperson basicattributes basicattributes basicattribute propertyiterator getarguments hasnext getobjectvalue getbasicattribute getname getvalue collect all the value from the table arguments using this create the basic attributes this will create the basic attributes for the user defined test case for modify test return the basic attributes private modification item get user mod attributes modification item mods new modification item get arguments get arguments size basic attribute attr property iterator iter get arguments iterator int count 0 while iter has next argument item argument iter next get object value attr get basic attribute item get name item get value mods count new modification item dir context replace attribute attr count 1 return mods basicattributes testcase basicattributes modificationitem getusermodattributes modificationitem modificationitem getarguments getarguments basicattribute propertyiterator getarguments hasnext getobjectvalue getbasicattribute getname getvalue modificationitem dircontext replace_attribute this will create the basic attributes for the inbuilt test case for modify test return the basic attributes private modification item get modification item modification item mods new modification item 2 replace update attribute attribute mod0 new basic attribute userpassword secret non nls 1 non nls 2 add mobile phone number attribute attribute mod1 new basic attribute mobile 123 456 1234 non nls 1 non nls 2 mods 0 new modification item dir context replace attribute mod0 mods 1 new modification item dir context add attribute mod1 return mods testcase basicattributes modificationitem getmodificationitem modificationitem modificationitem basicattribute basicattribute modificationitem dircontext replace_attribute modificationitem dircontext add_attribute this will create the basic attributes for the in build test case for add test return the basic attributes private basic attributes get basic attributes basic attributes basicattributes new basic attributes basic attribute basicattribute new basic attribute objectclass non nls 1 basicattribute add top non nls 1 basicattribute add person non nls 1 basicattribute add organizational person non nls 1 basicattribute add inet org person non nls 1 basicattributes put basicattribute string s1 user non nls 1 string s3 test non nls 1 string s5 user non nls 1 string s6 test non nls 1 counter 1 basicattributes put new basic attribute givenname s1 non nls 1 basicattributes put new basic attribute sn s3 non nls 1 basicattributes put new basic attribute cn test user counter non nls 1 non nls 2 basicattributes put new basic attribute uid s5 non nls 1 basicattributes put new basic attribute userpassword s6 non nls 1 set property new string property add cn test user counter non nls 1 return basicattributes testcase basicattributes basicattributes getbasicattributes basicattributes basicattributes basicattribute basicattribute organizationalperson inetorgperson basicattribute basicattribute basicattribute testuser basicattribute basicattribute setproperty stringproperty testuser this will create the basic attribute for the given name value pair return the basic attribute private basic attribute get basic attribute string name string value basic attribute attr new basic attribute name value return attr basicattribute basicattribute getbasicattribute basicattribute basicattribute returns a formatted string label describing this sampler return a formatted string label describing this sampler public string get label return ldap this get servername get port this get rootdn getlabel getservername getport getrootdn this will do the add test for the user defined test case as well as inbuilt test case private void add test ldap client ldap sample result res throws naming exception if get property as boolean user defined res sample start ldap create test get user attributes get property as string base entry dn res sample end else res sample start ldap create test get basic attributes get property as string add res sample end ldap delete test get property as string add testcase addtest ldapclient sampleresult namingexception getpropertyasboolean user_defined samplestart createtest getuserattributes getpropertyasstring base_entry_dn sampleend samplestart createtest getbasicattributes getpropertyasstring sampleend deletetest getpropertyasstring this will do the delete test for the user defined test case as well as inbuilt test case private void delete test ldap client ldap sample result res throws naming exception if get property as boolean user defined ldap create test get basic attributes get property as string add set property new string property delete get property as string add res sample start ldap delete test get property as string delete res sample end testcase deletetest ldapclient sampleresult namingexception getpropertyasboolean user_defined createtest getbasicattributes getpropertyasstring setproperty stringproperty getpropertyasstring samplestart deletetest getpropertyasstring sampleend this will do the search test for the user defined test case as well as inbuilt test case private void search test ldap client ldap sample result res throws naming exception if get property as boolean user defined ldap create test get basic attributes get property as string add set property new string property searchbase get property as string add set property new string property searchfilter get property as string add res sample start search found entries ldap search test get property as string searchbase get property as string searchfilter res sample end if get property as boolean user defined ldap delete test get property as string add testcase searchtest ldapclient sampleresult namingexception getpropertyasboolean user_defined createtest getbasicattributes getpropertyasstring setproperty stringproperty getpropertyasstring setproperty stringproperty getpropertyasstring samplestart searchfoundentries searchtest getpropertyasstring getpropertyasstring sampleend getpropertyasboolean user_defined deletetest getpropertyasstring this will do the search test for the user defined test case as well as inbuilt test case private void modify test ldap client ldap sample result res throws naming exception if get property as boolean user defined res sample start ldap modify test get user mod attributes get property as string base entry dn res sample end else ldap create test get basic attributes get property as string add set property new string property modify get property as string add res sample start ldap modify test get modification item get property as string modify res sample end ldap delete test get property as string add testcase modifytest ldapclient sampleresult namingexception getpropertyasboolean user_defined samplestart modifytest getusermodattributes getpropertyasstring base_entry_dn sampleend createtest getbasicattributes getpropertyasstring setproperty stringproperty getpropertyasstring samplestart modifytest getmodificationitem getpropertyasstring sampleend deletetest getpropertyasstring public sample result sample entry e sample result res new sample result boolean is successful false res set sample label get name res set sampler data get property as string test todo improve this ldap client ldap new ldap client try ldap connect get servername get port get rootdn get username get password if get property as string test equals add add test ldap res else if get property as string test equals delete delete test ldap res else if get property as string test equals modify modify test ldap res else if get property as string test equals searchbase search test ldap res todo needs more work if get property as string test equals searchbase search found entries res set response code 201 todo is this a sensible number non nls 1 res set response message ok no results res set response data successful no results get bytes else res set response codeok res set response message ok non nls 1 res set response data successful get bytes res set data type sample result text is successful true catch exception ex log error ldap client ex could time this res sample end if sample end is not called elapsed time will remain zero res set response code 500 todo distinguish errors better non nls 1 res set response message ex to string is successful false finally ldap disconnect set if we were successful or not res set successful is successful return res sampleresult sampleresult sampleresult issuccessful setsamplelabel getname setsamplerdata getpropertyasstring ldapclient ldapclient getservername getport getrootdn getusername getpassword getpropertyasstring addtest getpropertyasstring deletetest getpropertyasstring modifytest getpropertyasstring searchtest getpropertyasstring searchfoundentries setresponsecode setresponsemessage setresponsedata getbytes setresponsecodeok setresponsemessage setresponsedata getbytes setdatatype sampleresult issuccessful sampleend sampleend setresponsecode setresponsemessage tostring issuccessful setsuccessful issuccessful constructor for the java config object public java config set arguments new arguments javaconfig javaconfig setarguments sets the class name attribute of the java config object this is the class name of the link org apache jmeter protocol java sampler java sampler client implementation which will be used to execute the test param classname the new classname value public void set classname string classname set property java sampler classname classname javaconfig javasamplerclient setclassname setproperty javasampler gets the class name attribute of the java config object this is the class name of the link org apache jmeter protocol java sampler java sampler client implementation which will be used to execute the test return the classname value public string get classname return get property as string java sampler classname javaconfig javasamplerclient getclassname getpropertyasstring javasampler adds an argument to the list of arguments for this java config object the link org apache jmeter protocol java sampler java sampler client implementation can access these arguments through the link org apache jmeter protocol java sampler java sampler context param name the name of the argument to be added param value the value of the argument to be added public void add argument string name string value arguments args this get arguments args add argument name value javaconfig javasamplerclient javasamplercontext addargument getarguments addargument removes all of the arguments associated with this java config object public void remove arguments set property new test element property java sampler arguments new arguments javaconfig removearguments setproperty testelementproperty javasampler set all of the arguments for this java config object this will replace any previously added arguments the link org apache jmeter protocol java sampler java sampler client implementation can access these arguments through the link org apache jmeter protocol java sampler java sampler context param args the new arguments public void set arguments arguments args set property new test element property java sampler arguments args javaconfig javasamplerclient javasamplercontext setarguments setproperty testelementproperty javasampler gets the arguments for this java config object the link org apache jmeter protocol java sampler java sampler client implementation can access these arguments through the link org apache jmeter protocol java sampler java sampler context return the arguments public arguments get arguments return arguments get property java sampler arguments get object value javaconfig javasamplerclient javasamplercontext getarguments getproperty javasampler getobjectvalue constructor for an empty http file arg object public http file arg httpfilearg httpfilearg constructor for the http file arg object with given path public http file arg string path this path httpfilearg httpfilearg constructor for the http file arg object with full information public http file arg string path string paramname string mimetype if path null paramname null mimetype null throw new illegal argument exception parameters must not be null set path path set param name paramname set mime type mimetype httpfilearg httpfilearg illegalargumentexception setpath setparamname setmimetype constructor for the http file arg object with full information using existing properties public http file arg j meter property path j meter property paramname j meter property mimetype if path null paramname null mimetype null throw new illegal argument exception parameters must not be null set property filepath path set property mimetype mimetype set property paramname paramname httpfilearg httpfilearg jmeterproperty jmeterproperty jmeterproperty illegalargumentexception setproperty setproperty setproperty private void set property string name j meter property prop j meter property jmp j meter property prop clone jmp set name name set property jmp setproperty jmeterproperty jmeterproperty jmeterproperty setname setproperty copy constructor public http file arg http file arg file this file get path file get param name file get mime type httpfilearg httpfilearg getpath getparamname getmimetype set the http parameter name of the file param new param name the new http parameter name public void set param name string new param name set property new string property paramname new param name newparamname setparamname newparamname setproperty stringproperty newparamname get the http parameter name of the file return the http parameter name public string get param name return get property as string paramname getparamname getpropertyasstring set the mimetype of the file param new mime type the new mimetype public void set mime type string new mime type set property new string property mimetype new mime type newmimetype setmimetype newmimetype setproperty stringproperty newmimetype get the mimetype of the file return the http parameter mimetype public string get mime type return get property as string mimetype getmimetype getpropertyasstring set the path of the file param new path the new path public void set path string new path set property new string property filepath new path newpath setpath newpath setproperty stringproperty newpath get the path of the file return the file s path public string get path return get property as string filepath getpath getpropertyasstring sets the body header for the http file arg object header contains path parameter name and mime type information this is only intended for use by methods which need to store information temporarily whilst creating the http body param new header the new header value public void set header string new header header new header httpfilearg newheader setheader newheader newheader gets the saved body header for the http file arg object public string get header return header httpfilearg getheader returns path param name mime type information of http file arg object return the string demonstration of http file arg object in this format path path param param name mimetype mime type public string to string return path get path param get param name mimetype get mime type httpfilearg httpfilearg tostring getpath getparamname getmimetype check if the entry is not empty return true if path name or mimetype fields are not the empty string public boolean is not empty return get path length 0 get param name length 0 get mime type length 0 todo should we allow mimetype only isnotempty getpath getparamname getmimetype private static final locale default locale locale get default public j meter test string name super name default_locale getdefault jmetertest private test element test item public j meter test string test name test element te super test name save the method name test item te testelement testitem jmetertest testname testelement testname testitem private serializable ser obj public j meter test string test name serializable ser super test name save the method name ser obj ser serobj jmetertest testname testname serobj private j metergui component gui item public j meter test string test name j metergui component gc super test name save the method name gui item gc jmeterguicomponent guiitem jmetertest testname jmeterguicomponent testname guiitem private static volatile boolean class path shown false only show classpath once public j meter test string test name function fi super test name save the method name func item fi classpathshown jmetertest testname testname funcitem public static test suite throws exception the locale used to instantiate the gui objects j meter utils set locale test locale locale set default test locale needs to be done before any gui classes are instantiated test suite suite new test suite j meter test suite add test new j meter test read aliases suite add test new j meter test create title set suite add test new j meter test create tag set suite add test suitegui components suite add test suite serializable elements suite add test suite test elements suite add test suite bean components suite add test new j meter test create function set suite add test suite functions suite add test new j meter test check gui set suite add test new j meter test check function set suite add test new j meter test reset locale revert return suite jmeterutils setlocale test_locale setdefault test_locale testsuite testsuite jmetertest addtest jmetertest readaliases addtest jmetertest createtitleset addtest jmetertest createtagset addtest suiteguicomponents addtest suiteserializableelements addtest suitetestelements addtest suitebeancomponents addtest jmetertest createfunctionset addtest suitefunctions addtest jmetertest checkguiset addtest jmetertest checkfunctionset addtest jmetertest resetlocale restore the original locale public void reset locale j meter utils set locale default locale locale set default default locale resetlocale jmeterutils setlocale default_locale setdefault default_locale public void create title set throws exception gui titles new hash map 90 string compref xdocs usermanual component reference xml sax builder bldr new sax builder document doc doc bldr build compref element root doc get root element element body root get child body list sections body get children section for int i 0 i sections size i list components element sections get i get children component for int j 0 j components size j element comp element components get j string nm comp get attribute value name if nm equals ssl manager not a true gui component gui titles put nm replace boolean false add titles that don t need to be documented gui titles put root boolean false gui titles put example sampler boolean false createtitleset guititles hashmap component_reference saxbuilder saxbuilder getrootelement getchild getchildren getchildren getattributevalue guititles _ guititles guititles public void create tag set throws exception gui tags new hash map 90 string compref xdocs usermanual component reference xml sax builder bldr new sax builder document doc doc bldr build compref element root doc get root element element body root get child body list sections body get children section for int i 0 i sections size i list components element sections get i get children component for int j 0 j components size j element comp element components get j gui tags put comp get attribute value tag boolean false createtagset guitags hashmap component_reference saxbuilder saxbuilder getrootelement getchild getchildren getchildren guitags getattributevalue public void create function set throws exception func titles new hash map 20 string compref xdocs usermanual functions xml sax builder bldr new sax builder document doc doc bldr build compref element root doc get root element element body root get child body element section body get child section list sections section get children subsection for int i 0 i sections size i list components element sections get i get children component for int j 0 j components size j element comp element components get j func titles put comp get attribute value name boolean false createfunctionset functitles hashmap saxbuilder saxbuilder getrootelement getchild getchild getchildren getchildren functitles getattributevalue private int scanprint map map m string t set s m key set int unseen 0 if s size 0 return 0 iterator i s iterator while i has next object key i next if m get key equals boolean true if unseen 0 first time system out println n names remaining in t map unseen system out println key return unseen scanprintmap keyset hasnext nnames public void check gui set throws exception gui titles remove example sampler we don t mind if this is left over gui titles remove sample result save configuration ditto not a sampler assert equals should not have any names left over 0 scanprint map gui titles gui checkguiset guititles guititles sample_result_save_configuration assertequals scanprintmap guititles public void check function set throws exception assert equals should not have any names left over 0 scanprint map func titles function checkfunctionset assertequals scanprintmap functitles private static test suitegui components throws exception test suite suite new test suite gui components iterator iter get objects j metergui component class iterator while iter has next j metergui component item j metergui component iter next if item instanceof j meter tree node system out println info j metergui component skipping all tests item get class get name continue if item instanceof obsolete gui continue test suite ts new test suite item get class get name ts add test new j meter test gui components1 item if item instanceof test beangui system out println info j metergui component skipping some tests item get class get name else ts add test new j meter test gui components2 item ts add test new j meter test rungui title item suite add test ts return suite suiteguicomponents testsuite testsuite guicomponents getobjects jmeterguicomponent hasnext jmeterguicomponent jmeterguicomponent jmetertreenode jmeterguicomponent getclass getname obsoletegui testsuite testsuite getclass getname addtest jmetertest guicomponents1 testbeangui jmeterguicomponent getclass getname addtest jmetertest guicomponents2 addtest jmetertest runguititle addtest private static test suite functions throws exception test suite suite new test suite functions iterator iter get objects function class iterator while iter has next object item iter next if item get class equals compound variable class continue test suite ts new test suite item get class get name ts add test new j meter test run function function item ts add test new j meter test run function2 function item suite add test ts return suite suitefunctions testsuite testsuite getobjects hasnext getclass compoundvariable testsuite testsuite getclass getname addtest jmetertest runfunction addtest jmetertest runfunction2 addtest private static test suite bean components throws exception test suite suite new test suite bean components iterator iter get objects test bean class iterator while iter has next class c iter next get class try j metergui component item new test beangui c j metergui component item j metergui component iter next test suite ts new test suite item get class get name ts add test new j meter test gui components2 item ts add test new j meter test rungui title item suite add test ts catch illegal argument exception e system out println cannot create test for c get name e e print stack trace system out return suite suitebeancomponents testsuite testsuite beancomponents getobjects testbean hasnext getclass jmeterguicomponent testbeangui jmeterguicomponent jmeterguicomponent testsuite testsuite getclass getname addtest jmetertest guicomponents2 addtest jmetertest runguititle addtest illegalargumentexception getname printstacktrace public void rungui title throws exception if gui titles size 0 string title gui item get doc anchor boolean ct gui titles contains key title if ct gui titles put title boolean true so we can detect extra entries string name gui item get class get name if is this a work in progress or an internal gui component title null title length 0 will be for internal components title to upper case java util locale english index of alpha 1 title to upper case java util locale english index of beta 1 title equals example1 skip the example samplers title equals example2 name starts with org apache jmeter examples no not a work in progress string s component reference xml needs title anchor for name if ct log warn s record in log as well assert true s ct runguititle guititles guiitem getdocanchor guititles containskey guititles guiitem getclass getname touppercase indexof touppercase indexof startswith component_reference asserttrue public void run function throws exception if func titles size 0 string title func item get reference key boolean ct func titles contains key title if ct func titles put title boolean true for detecting extra entries if is this a work in progress title index of alpha 1 title index of experimental 1 no not a work in progress string s function xml needs title entry for func item get class get name if ct log warn s record in log as well assert true s ct runfunction functitles funcitem getreferencekey functitles containskey functitles indexof indexof funcitem getclass getname asserttrue public void run function2 throws exception iterator i func item get argument desc iterator while i has next object o i next assert true description must be a string o instanceof string assert false description must not start with refkey string o starts with refkey runfunction2 funcitem getargumentdesc hasnext asserttrue assertfalse startswith public void gui components1 throws exception string name gui item get class get name assert equals name should be same as static label for name gui item get static label gui item get name if name starts with org apache jmeter examples return if name ends with test beangui try string label gui item get label resource assert true label length 0 assert false label should be in resource file for name j meter utils get res string label starts with j meter utils res key pfx catch unsupported operation exception uoe log warn class has not yet implemented get label resource name check element alias gui item guicomponents1 guiitem getclass getname assertequals guiitem getstaticlabel guiitem getname startswith endswith testbeangui guiitem getlabelresource asserttrue assertfalse jmeterutils getresstring startswith jmeterutils res_key_pfx unsupportedoperationexception getlabelresource checkelementalias guiitem public void gui components2 throws exception string name gui item get class get name todo these assertions should be separate tests test element el gui item create test element assert not null name create test element should be non null el assert equals gui class failed on name name el get property as string test element gui class assert equals name failed on name gui item get name el get name assert equals test class failed on name el get class get name el get property as string test element test class test element el2 gui item create test element el set name hey new name el set property not shouldn t be here if gui item instanceof unshared component assert equals shared failed on name el2 get property as string not log debug saving element el get class byte array output stream bos new byte array output stream save service save element el bos byte array input stream bis new byte array input stream bos to byte array bos close el test element save service load element bis bis close assert not null load element failed on name el gui item configure el assert equals configure test failed on name el get name gui item get name gui item modify test element el2 assert equals modify test failed on name hey new name el2 get name guicomponents2 guiitem getclass getname testelement guiitem createtestelement assertnotnull createtestelement assertequals getpropertyasstring testelement gui_class assertequals guiitem getname getname assertequals getclass getname getpropertyasstring testelement test_class testelement guiitem createtestelement setname setproperty guiitem unsharedcomponent assertequals getpropertyasstring getclass bytearrayoutputstream bytearrayoutputstream saveservice saveelement bytearrayinputstream bytearrayinputstream tobytearray testelement saveservice loadelement assertnotnull guiitem assertequals getname guiitem getname guiitem modifytestelement assertequals getname private static test suite serializable elements throws exception test suite suite new test suite serializable elements iterator iter get objects serializable class iterator while iter has next serializable ser obj serializable iter next if ser obj get class get name ends with stub continue test suite ts new test suite ser obj get class get name ts add test new j meter test run serial test ser obj suite add test ts return suite suiteserializableelements testsuite testsuite serializableelements getobjects hasnext serobj serobj getclass getname endswith _stub testsuite testsuite serobj getclass getname addtest jmetertest runserialtest serobj addtest public void run serial test throws exception if ser obj instanceof j component try byte array output stream bytes new byte array output stream object output stream out new object output stream bytes out write object ser obj out close object input stream in new object input stream new byte array input stream bytes to byte array object read object in read object in close assert equals deserializing class ser obj get class get name ser obj get class read object get class catch throwable e fail serialization of ser obj get class get name failed e runserialtest serobj jcomponent bytearrayoutputstream bytearrayoutputstream objectoutputstream objectoutputstream writeobject serobj objectinputstream objectinputstream bytearrayinputstream tobytearray readobject readobject assertequals serobj getclass getname serobj getclass readobject getclass serobj getclass getname private static test suite test elements throws exception test suite suite new test suite test elements iterator iter get objects test element class iterator while iter has next test element item test element iter next test suite ts new test suite item get class get name ts add test new j meter test run test element item suite add test ts return suite suitetestelements testsuite testsuite testelements getobjects testelement hasnext testelement testelement testsuite testsuite getclass getname addtest jmetertest runtestelement addtest public void run test element throws exception check element cloning test item string name test item get class get name assert true name must implement serializable test item instanceof serializable if name starts with org apache jmeter examples return if name equals org apache jmeter control transaction sampler return not a real sampler check element alias test item runtestelement checkelementcloning testitem testitem getclass getname asserttrue testitem startswith transactionsampler checkelementalias testitem public void read aliases throws exception name map save service load properties assert not null save service name map saveservice properties should not be null name map readaliases namemap saveservice loadproperties assertnotnull saveservice namemap namemap private void check element alias object item string name item get class get name boolean contains name map values contains name if contains system out println name substring name last index of 1 name fail save service name map saveservice properties should contain name checkelementalias getclass getname namemap lastindexof saveservice namemap private static collection get objects class extends class throws exception string ex name extends class get name object my this iterator classes class finder find classes that extend j meter utils get search paths new class extends class iterator list objects new linked list string n boolean caught error true throwable caught null try while classes has next n string classes next todo improve this check if n ends with remotej meter engine impl continue don t try to instantiate remote server class c null try c class for name n try try with a parameter less constructor first objects add c new instance catch instantiation exception e caught e system out println e to string try events often have this constructor objects add c get constructor new class object class new instance new object my this catch no such method exception f no luck ignore this class system out println warn ex name no such method exception n catch no class def found error e no luck ignore this class system out println warn ex name no class def found error n catch illegal access exception e caught e system out println warn ex name illegal access exception n we won t test restricted access classes catch headless exception e caught e system out println error creating n e to string catch exception e caught e if e instanceof remote exception not thrown so need to check here system out println warn error creating n e to string else throw new exception error creating n e caught error false finally if caught error system out println last class n system out println objects size objects size system out println last error caught if objects size 0 system out println no classes found that extend ex name check the following system out println search paths are string ss j meter utils get search paths for int i 0 i ss length i system out println ss i if class path shown only dump it once system out println class path is string cp system get property java class path string cpe j orphan utils split cp java io file path separator for int i 0 i cpe length i system out println cpe i class path shown true return objects getobjects extendsclass exname extendsclass getname mythis classfinder findclassesthatextend jmeterutils getsearchpaths extendsclass linkedlist caughterror hasnext endswith remotejmeterengineimpl forname newinstance instantiationexception tostring getconstructor newinstance mythis nosuchmethodexception exname nosuchmethodexception noclassdeffounderror exname noclassdeffounderror illegalaccessexception exname illegalaccessexception headlessexception tostring remoteexception tostring caughterror caughterror exname jmeterutils getsearchpaths classpathshown getproperty jorphanutils pathseparator classpathshown private static void clone testing test element item test element cloned item assert true item cloned item assert equals clone same class testing item get class get name item get class get name cloned item get class get name clonetesting testelement testelement cloneditem asserttrue cloneditem assertequals getclass getname getclass getname cloneditem getclass getname private static void check element cloning test element item test element cloned item test element item clone clone testing item cloned item property iterator iter2 item property iterator while iter2 has next j meter property item2 iter2 next sebb assert equals item2 cloned item get property item2 get name assert equals item2 get string value cloned item get property item2 get name get string value assert true item2 cloned item get property item2 get name checkelementcloning testelement testelement cloneditem testelement clonetesting cloneditem propertyiterator propertyiterator hasnext jmeterproperty assertequals cloneditem getproperty getname assertequals getstringvalue cloneditem getproperty getname getstringvalue asserttrue cloneditem getproperty getname no arg constructor public random execute the function see function execute sample result sampler public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception long min long parse long minimum execute trim long max long parse long maximum execute trim long rand min long math random max min 1 string rand string long to string rand if var name null j meter variables vars get variables final string var trim var name execute trim if vars null var trim length 0 vars will be null on test plan vars put var trim rand string return rand string sampleresult sampleresult previousresult currentsampler invalidvariableexception parselong parselong randstring tostring varname jmetervariables getvariables vartrim varname vartrim testplan vartrim randstring randstring set the parameters for the function see function set parameters collection public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters 2 3 object values parameters to array minimum compound variable values 0 maximum compound variable values 1 if values length 2 var name compound variable values 2 else var name null setparameters setparameters invalidvariableexception checkparametercount toarray compoundvariable compoundvariable varname compoundvariable varname get the invocation key for this function see function get reference key public string get reference key return key getreferencekey getreferencekey get the description of this function see function get argument desc public list get argument desc return desc getargumentdesc getargumentdesc private final j panel lookup new j panel public jms subscriber gui init jpanel jpanel jmssubscribergui public string get label resource return jms subscriber title non nls 1 getlabelresource jms_subscriber_title see org apache jmeter gui j metergui component create test element public test element create test element subscriber sampler sampler new subscriber sampler this configure test element sampler sampler set usejndi properties string value of use properties is selected sampler setjndi intial context factory jndiicf get text sampler set provider url url field get text sampler set connection factory jndi conn fac get text sampler set topic jms topic get text sampler set username jms user get text sampler set password jms pwd get text sampler set use auth use auth is selected sampler set iterations iterations get text sampler set read response string value of read response is selected sampler set client choice client choice get text return sampler jmeterguicomponent createtestelement testelement createtestelement subscribersampler subscribersampler configuretestelement setusejndiproperties valueof useproperties isselected setjndiintialcontextfactory gettext setproviderurl urlfield gettext setconnectionfactory jndiconnfac gettext settopic jmstopic gettext setusername jmsuser gettext setpassword jmspwd gettext setuseauth useauth isselected setiterations gettext setreadresponse valueof readresponse isselected setclientchoice clientchoice gettext modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element s subscriber sampler sampler subscriber sampler s this configure test element sampler sampler set usejndi properties string value of use properties is selected sampler setjndi intial context factory jndiicf get text sampler set provider url url field get text sampler set connection factory jndi conn fac get text sampler set topic jms topic get text sampler set username jms user get text sampler set password jms pwd get text sampler set use auth use auth is selected sampler set iterations iterations get text sampler set read response string value of read response is selected sampler set client choice client choice get text testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement subscribersampler subscribersampler configuretestelement setusejndiproperties valueof useproperties isselected setjndiintialcontextfactory gettext setproviderurl urlfield gettext setconnectionfactory jndiconnfac gettext settopic jmstopic gettext setusername jmsuser gettext setpassword jmspwd gettext setuseauth useauth isselected setiterations gettext setreadresponse valueof readresponse isselected setclientchoice clientchoice gettext init adds jndiicf to the main panel the class reuses logic from soap sampler since it is common private void init this set layout new vertical layout 5 vertical layout left vertical layout top main panel j panel main panel new j panel border margin new empty border 10 10 5 10 main panel set border margin main panel set layout new vertical layout 5 vertical layout left title j label panel title label new j label get static label font cur font panel title label get font int cur font size cur font get size cur font size 4 panel title label set font new font cur font get font name cur font get style cur font size main panel add panel title label name main panel add get name panel button for browsing webservice wsdl lookup set layout new vertical layout 6 vertical layout left main panel add lookup lookup add use properties use properties add change listener this lookup add jndiicf lookup add url field lookup add jndi conn fac j panel common params new j panel common params set layout new vertical layout 6 vertical layout left main panel add common params common params add jms topic common params add use auth common params add jms user common params add jms pwd common params add iterations common params add read response common params add client choice we have to add the gui to the change listener this add main panel mainpanel soapsampler setlayout verticallayout verticallayout verticallayout jpanel mainpanel jpanel emptyborder mainpanel setborder mainpanel setlayout verticallayout verticallayout jlabel paneltitlelabel jlabel getstaticlabel curfont paneltitlelabel getfont curfontsize curfont getsize curfontsize paneltitlelabel setfont curfont getfontname curfont getstyle curfontsize mainpanel paneltitlelabel mainpanel getnamepanel setlayout verticallayout verticallayout mainpanel useproperties useproperties addchangelistener urlfield jndiconnfac jpanel commonparams jpanel commonparams setlayout verticallayout verticallayout mainpanel commonparams commonparams jmstopic commonparams useauth commonparams jmsuser commonparams jmspwd commonparams commonparams readresponse commonparams clientchoice mainpanel the implementation loads the url and the soap action for the request public void configure test element el super configure el subscriber sampler sampler subscriber sampler el use properties set selected sampler get usejndi properties as boolean jndiicf set text sampler getjndi initial context factory url field set text sampler get provider url jndi conn fac set text sampler get connection factory jms topic set text sampler get topic jms user set text sampler get username jms pwd set text sampler get password iterations set text sampler get iterations use auth set selected sampler is use auth read response set selected sampler get read response as boolean client choice set text sampler get client choice testelement subscribersampler subscribersampler useproperties setselected getusejndipropertiesasboolean settext getjndiinitialcontextfactory urlfield settext getproviderurl jndiconnfac settext getconnectionfactory jmstopic settext gettopic jmsuser settext getusername jmspwd settext getpassword settext getiterations useauth setselected isuseauth readresponse setselected getreadresponseasboolean clientchoice settext getclientchoice public void clear gui super clear gui use properties set selected false non nls 1 jndiicf set text non nls 1 url field set text non nls 1 jndi conn fac set text non nls 1 jms topic set text non nls 1 jms user set text non nls 1 jms pwd set text non nls 1 iterations set text non nls 1 use auth set selected false read response set selected true client choice set text receive rsc cleargui cleargui useproperties setselected settext urlfield settext jndiconnfac settext jmstopic settext jmsuser settext jmspwd settext settext useauth setselected readresponse setselected clientchoice settext receive_rsc method from action listener param event that occurred public void action performed action event event if event get source use properties actionlistener actionperformed actionevent getsource useproperties when the state of a widget changes it will notify the gui the method then enables or disables certain parameters public void state changed change event event if event get source use properties if use properties is selected this jndiicf set enabled false this url field set enabled false else this jndiicf set enabled true this url field set enabled true statechanged changeevent getsource useproperties useproperties isselected setenabled urlfield setenabled setenabled urlfield setenabled public class sharedtc log parser extends tc log parser implements test cloneable public sharedtc log parser super sharedtclogparser tclogparser testcloneable sharedtclogparser public sharedtc log parser string source super source sharedtclogparser public object clone sharedtc log parser parser new sharedtc log parser parser filename filename parser filter filter return parser sharedtclogparser sharedtclogparser public int parse test element el int parse count file server file server file server get file server file server reserve file filename try return parse file server el parse count catch exception exception log error problem creating samples exception return 1 indicate that an error occured testelement parsecount fileserver fileserver fileserver getfileserver fileserver reservefile fileserver parsecount the method is responsible for reading each line and breaking out of the while loop if a set number of lines is given param breader protected int parse file server breader test element el int parse count int actual count 0 string line null try read one line at a time using buffered reader line breader read line filename while line null if line length 0 actual count this parse line line el we check the count to see if we have exceeded the number of lines to parse there s no way to know where to stop in the file therefore we use break to escape the while loop when we ve reached the count if parse count 1 actual count parse count break line breader read line filename if line null breader close file filename this reader new buffered reader new file reader this source parse this reader el catch io exception ioe log error error reading log file ioe return actual count fileserver testelement parsecount actualcount bufferedreader readline actualcount parseline parsecount actualcount parsecount readline closefile bufferedreader filereader ioexception actualcount public void close try file server get file server close file filename catch io exception e do nothing fileserver getfileserver closefile ioexception public tcp client impl super set eol byte eol int if use eol byte log info using eol byte eol byte tcpclientimpl seteolbyte eolint useeolbyte eolbyte eolbyte public void write output stream os string s try os write s get bytes os flush catch io exception e log warn write error e log debug wrote s return outputstream getbytes ioexception public void write output stream os input stream is byte buff new byte 512 try while is read buff 0 os write buff os flush catch io exception e log warn write error e outputstream inputstream ioexception reads data until the defined eol byte is reached if there is no eol byte defined then reads until the end of the stream is reached public string read input stream is byte buffer new byte 4096 byte array output stream w new byte array output stream int x 0 try while x is read buffer 1 w write buffer 0 x if use eol byte buffer x 1 eol byte break catch socket timeout exception e drop out to handle buffer catch interruptedio exception e drop out to handle buffer catch io exception e log warn read error e return do we need to close byte array or flush it log debug read w size n w to string return w to string inputstream bytearrayoutputstream bytearrayoutputstream useeolbyte eolbyte sockettimeoutexception interruptedioexception ioexception tostring tostring create a new arguments object with no arguments public ldap arguments set property new collection property arguments new array list ldaparguments setproperty collectionproperty arraylist get the arguments return the arguments public collection property get arguments return collection property get property arguments collectionproperty getarguments collectionproperty getproperty clear the arguments public void clear super clear set property new collection property arguments new array list setproperty collectionproperty arraylist set the list of arguments any existing arguments will be lost param arguments the new arguments public void set arguments list arguments set property new collection property arguments arguments setarguments setproperty collectionproperty get the arguments as a map each argument name is used as the key and its value as the value return a new map with string keys and values containing the arguments public map get arguments as map property iterator iter get arguments iterator map arg map new hash map while iter has next ldap argument arg ldap argument iter next get object value arg map put arg get name arg get value return arg map getargumentsasmap propertyiterator getarguments argmap hashmap hasnext ldapargument ldapargument getobjectvalue argmap getname getvalue argmap add a new argument with the given name and value param name the name of the argument param value the value of the argument public void add argument string name string value string opcode add argument new ldap argument name value opcode null addargument addargument ldapargument add a new argument param arg the new argument public void add argument ldap argument arg test element property new arg new test element property arg get name arg if is running version this set temporary new arg get arguments add item new arg addargument ldapargument testelementproperty newarg testelementproperty getname isrunningversion settemporary newarg getarguments additem newarg add a new argument with the given name value and metadata param name the name of the argument param value the value of the argument param metadata the metadata for the argument public void add argument string name string value string opcode string metadata add argument new ldap argument name value opcode metadata addargument addargument ldapargument get a property iterator of the arguments return an iteration of the arguments public property iterator iterator return get arguments iterator propertyiterator propertyiterator getarguments create a string representation of the arguments return the string representation of the arguments public string to string string buffer str new string buffer property iterator iter get arguments iterator while iter has next ldap argument arg ldap argument iter next get object value final string meta data arg get meta data str append arg get name if meta data null str append non nls else str append meta data str append arg get value if iter has next str append non nls return str to string tostring stringbuffer stringbuffer propertyiterator getarguments hasnext ldapargument ldapargument getobjectvalue metadata getmetadata getname metadata metadata getvalue hasnext tostring remove the specified argument from the list param row the index of the argument to remove public void remove argument int row if row get arguments size get arguments remove row removeargument getarguments getarguments remove the specified argument from the list param arg the argument to remove public void remove argument ldap argument arg property iterator iter get arguments iterator while iter has next ldap argument item ldap argument iter next get object value if arg equals item iter remove removeargument ldapargument propertyiterator getarguments hasnext ldapargument ldapargument getobjectvalue remove the argument with the specified name param arg name the name of the argument to remove public void remove argument string arg name property iterator iter get arguments iterator while iter has next ldap argument arg ldap argument iter next get object value if arg get name equals arg name iter remove argname removeargument argname propertyiterator getarguments hasnext ldapargument ldapargument getobjectvalue getname argname remove all arguments from the list public void remove all arguments get arguments clear removeallarguments getarguments add a new empty argument to the list the new argument will have the empty string as its name and value and null metadata public void add empty argument add argument new ldap argument null addemptyargument addargument ldapargument get the number of arguments in the list return the number of arguments public int get argument count return get arguments size getargumentcount getarguments get a single argument param row the index of the argument to return return the argument at the specified index or null if no argument exists at that index public ldap argument get argument int row ldap argument argument null if row get arguments size argument ldap argument get arguments get row get object value return argument ldapargument getargument ldapargument getarguments ldapargument getarguments getobjectvalue returns the converter version used to check for possible incompatibilities public static string get version return revision 674365 non nls 1 getversion see com thoughtworks xstream converters converter can convert java lang class public boolean can convert class arg0 return arg0 equals boolean property class canconvert canconvert booleanproperty public void marshal object obj hierarchical stream writer writer marshalling context arg2 boolean property prop boolean property obj writer add attribute att name conversion help encode prop get name writer set value prop get string value hierarchicalstreamwriter marshallingcontext booleanproperty booleanproperty addattribute att_name conversionhelp getname setvalue getstringvalue public object unmarshal hierarchical stream reader reader unmarshalling context arg1 boolean property prop new boolean property conversion help decode reader get attribute att name boolean value of reader get value boolean value return prop hierarchicalstreamreader unmarshallingcontext booleanproperty booleanproperty conversionhelp getattribute att_name valueof getvalue booleanvalue see command get action names public set get action names return commands getactionnames getactionnames see command do action action event public void do action action event e gui package gui pack gui package get instance j meter tree node current nodes gui pack get tree listener get selected nodes copy set copied nodes current nodes for int i 0 i current nodes length i gui pack get tree model remove node from parent current nodes i gui pack get main frame repaint doaction actionevent doaction actionevent guipackage guipack guipackage getinstance jmetertreenode currentnodes guipack gettreelistener getselectednodes setcopiednodes currentnodes currentnodes guipack gettreemodel removenodefromparent currentnodes guipack getmainframe public html parse error super htmlparseerror param message public html parse error string message super message htmlparseerror param cause public html parse error throwable cause jdk1 4 super cause saved cause cause htmlparseerror savedcause param message param cause public html parse error string message throwable cause jdk1 4 super message cause super message saved cause cause htmlparseerror savedcause local verstion of get cause for jdk1 3 support public throwable get cause return saved cause getcause getcause savedcause public standard report engine super standardreportengine see java lang runnable run public void run see org apache jmeter report engine report engine configure org apache jorphan collections hash tree public void configure hash tree test plan reportengine hashtree hashtree testplan see org apache jmeter report engine report engine run report public void run report throws j meter engine exception reportengine runreport runreport jmeterengineexception see org apache jmeter report engine report engine stop report public void stop report reportengine stopreport stopreport see org apache jmeter report engine report engine reset public void reset reportengine see org apache jmeter report engine report engine exit public void exit reportengine public void set up jmctx j meter context service get context assertion new size assertion assertion set thread context jmctx vars new j meter variables jmctx set variables vars sample0 new sample result sample1 new sample result sample1 set response data data1 get bytes setup jmetercontextservice getcontext sizeassertion setthreadcontext jmetervariables setvariables sampleresult sampleresult setresponsedata getbytes public void test size assertion equals throws exception assertion set comp oper size assertion equal assertion set allowed size 0 result assertion get result sample1 assert failed result assertion get result sample0 assert passed assertion set allowed size data1 len result assertion get result sample1 assert passed result assertion get result sample0 assert failed testsizeassertionequals setcompoper sizeassertion setallowedsize getresult assertfailed getresult assertpassed setallowedsize data1len getresult assertpassed getresult assertfailed public void test size assertion not equals throws exception assertion set comp oper size assertion notequal assertion set allowed size 0 result assertion get result sample1 assert passed result assertion get result sample0 assert failed assertion set allowed size data1 len result assertion get result sample1 assert failed result assertion get result sample0 assert passed testsizeassertionnotequals setcompoper sizeassertion setallowedsize getresult assertpassed getresult assertfailed setallowedsize data1len getresult assertfailed getresult assertpassed public void test size assertion greater than throws exception assertion set comp oper size assertion greaterthan assertion set allowed size 0 result assertion get result sample1 assert passed result assertion get result sample0 assert failed assertion set allowed size data1 len result assertion get result sample1 assert failed result assertion get result sample0 assert failed testsizeassertiongreaterthan setcompoper sizeassertion setallowedsize getresult assertpassed getresult assertfailed setallowedsize data1len getresult assertfailed getresult assertfailed public void test size assertion greater than equal throws exception assertion set comp oper size assertion greaterthanequal assertion set allowed size 0 result assertion get result sample1 assert passed result assertion get result sample0 assert passed assertion set allowed size data1 len result assertion get result sample1 assert passed result assertion get result sample0 assert failed testsizeassertiongreaterthanequal setcompoper sizeassertion setallowedsize getresult assertpassed getresult assertpassed setallowedsize data1len getresult assertpassed getresult assertfailed public void test size assertion less than throws exception assertion set comp oper size assertion lessthan assertion set allowed size 0 result assertion get result sample1 assert failed result assertion get result sample0 assert failed assertion set allowed size data1 len 1 result assertion get result sample1 assert passed result assertion get result sample0 assert passed testsizeassertionlessthan setcompoper sizeassertion setallowedsize getresult assertfailed getresult assertfailed setallowedsize data1len getresult assertpassed getresult assertpassed public void test size assertion less than equal throws exception assertion set comp oper size assertion lessthanequal assertion set allowed size 0 result assertion get result sample1 assert failed result assertion get result sample0 assert passed assertion set allowed size data1 len 1 result assertion get result sample1 assert passed result assertion get result sample0 assert passed testsizeassertionlessthanequal setcompoper sizeassertion setallowedsize getresult assertfailed getresult assertpassed setallowedsize data1len getresult assertpassed getresult assertpassed private void assert passed throws exception if null result get failure message system out println result get failure message debug assert null failure message should be null result get failure message assert false result is error assert false result is failure assertpassed getfailuremessage getfailuremessage assertnull getfailuremessage assertfalse iserror assertfalse isfailure private void assert failed throws exception assert not null failure nessage should not be null result get failure message system out println result get failure message assert false should not be response was null response was null equals result get failure message assert false result is error assert true result is failure assertfailed assertnotnull getfailuremessage getfailuremessage assertfalse getfailuremessage assertfalse iserror asserttrue isfailure protected volatile http client saved client private static boolean is non proxy string host return non proxy host full contains host is partial match host httpclient savedclient isnonproxy nonproxyhostfull ispartialmatch private static boolean is partial match string host for int i 0 i non proxy host suffix size i if host ends with string non proxy host suffix get i return true return false ispartialmatch nonproxyhostsuffixsize endswith nonproxyhostsuffix constructor for the http sampler2 object consider using http sampler factory new instance instead public http sampler2 httpsampler2 httpsamplerfactory newinstance httpsampler2 private string send post data post method post throws io exception buffer to hold the post body except file content string buffer posted body new string buffer 1000 http file arg files gethttp files check if we should do a multipart form data or an application x www form urlencoded post request if get use multipart for post if a content encoding is specified we use that as the encoding of any parameter values string content encoding get content encoding if content encoding null content encoding length 0 content encoding null we don t know how many entries will be skipped array list partlist new array list create the parts add any parameters property iterator args get arguments iterator while args has next http argument arg http argument args next get object value string parameter name arg get name if arg is skippable parameter name continue partlist add new string part arg get name arg get value content encoding add any files for int i 0 i files length i http file arg file files i file input file new file file get path we do not know the char set of the file to be uploaded so we set it to null viewable file part file part new viewable file part file get param name input file file get mime type null file part set char set null we do not know what the char set of the file is partlist add file part set the multipart for the post int part no partlist size part parts part partlist to array new part part no multipart request entity multi part new multipart request entity parts post get params post set request entity multi part set the content type string multi part content type multi part get content type post set request header header content type multi part content type if the multipart is repeatable we can send it first to our own stream without the actual file content so we can return it if multi part is repeatable for all the file multiparts we must tell it to not include the actual file content for int i 0 i part no i if parts i instanceof viewable file part viewable file part parts i set hide file data true send multipart without file content bos write the request to our own stream byte array output stream bos new byte array output stream multi part write request bos bos flush we get the posted bytes using the encoding used to create it posted body append new string bos to byte array content encoding null us ascii non nls 1 this is the default used by http client content encoding bos close for all the file multiparts we must revert the hiding of the actual file content for int i 0 i part no i if parts i instanceof viewable file part viewable file part parts i set hide file data false else posted body append multipart was not repeatable cannot view what was sent non nls 1 else check if the header manager had a content type header this allows the user to specify his own content type for a post request header content type header post get request header header content type boolean has content type header content type header null content type header get value null content type header get value length 0 if there are no arguments we can send a file as the body of the request todo needs a multiple file upload scenerio if has arguments get send file as post body if get send file as post body returned true it s sure that file is not null http file arg file files 0 if has content type header allow the mimetype of the file to control the content type if file get mime type null file get mime type length 0 post set request header header content type file get mime type else post set request header header content type application x www form urlencoded file request entity file request entity new file request entity new file file get path null post set request entity file request entity we just add placeholder text for file content posted body append actual file content not shown here else in a post request which is not multipart we only support parameters no file upload is allowed if a content encoding is specified we set it as http parameter so that the post body will be encoded in the specified content encoding string content encoding get content encoding boolean have content encoding false if content encoding null content encoding trim length 0 post get params set content charset content encoding have content encoding true else if content encoding null content encoding trim length 0 content encoding null if none of the arguments have a name specified we just send all the values as the post body if get send parameter values as post body allow the mimetype of the file to control the content type this is not obvious in gui if you are not uploading any files but just sending the content of nameless parameters todo needs a multiple file upload scenerio if has content type header http file arg file files length 0 files 0 null if file null file get mime type null file get mime type length 0 post set request header header content type file get mime type else todo is this the correct default post set request header header content type application x www form urlencoded just append all the parameter values and use that as the post body string buffer post body new string buffer property iterator args get arguments iterator while args has next http argument arg http argument args next get object value string value if have content encoding value arg get encoded value content encoding else value arg get encoded value post body append value string request entity request entity new string request entity post body to string post get request header header content type get value content encoding post set request entity request entity else it is a normal post request with parameter names and values set the content type if has content type header post set request header header content type application x www form urlencoded add the parameters property iterator args get arguments iterator while args has next http argument arg http argument args next get object value the http client always urlencodes both name and value so if the argument is already encoded we have to decode it before adding it to the post request string parameter name arg get name if arg is skippable parameter name continue string parameter value arg get value if arg is always encoded the value is already encoded by the user must decode the value now so that when the httpclient encodes it we end up with the same value as the user had entered string url content encoding content encoding if url content encoding null url content encodin sendpostdata postmethod ioexception stringbuffer postedbody stringbuffer httpfilearg gethttpfiles getusemultipartforpost contentencoding getcontentencoding contentencoding contentencoding contentencoding arraylist arraylist propertyiterator getarguments hasnext httpargument httpargument getobjectvalue parametername getname isskippable parametername stringpart getname getvalue contentencoding httpfilearg inputfile getpath viewablefilepart filepart viewablefilepart getparamname inputfile getmimetype filepart setcharset filepart partno toarray partno multipartrequestentity multipart multipartrequestentity getparams setrequestentity multipart multipartcontenttype multipart getcontenttype setrequestheader header_content_type multipartcontenttype multipart isrepeatable partno viewablefilepart viewablefilepart sethidefiledata sendmultipartwithoutfilecontent bytearrayoutputstream bytearrayoutputstream multipart writerequest postedbody tobytearray contentencoding httpclient contentencoding partno viewablefilepart viewablefilepart sethidefiledata postedbody contenttypeheader getrequestheader header_content_type hascontenttypeheader contenttypeheader contenttypeheader getvalue contenttypeheader getvalue hasarguments getsendfileaspostbody getsendfileaspostbody httpfilearg hascontenttypeheader getmimetype getmimetype setrequestheader header_content_type getmimetype setrequestheader header_content_type application_x_www_form_urlencoded filerequestentity filerequestentity filerequestentity getpath setrequestentity filerequestentity postedbody contentencoding getcontentencoding havecontentencoding contentencoding contentencoding getparams setcontentcharset contentencoding havecontentencoding contentencoding contentencoding contentencoding getsendparametervaluesaspostbody hascontenttypeheader httpfilearg getmimetype getmimetype setrequestheader header_content_type getmimetype setrequestheader header_content_type application_x_www_form_urlencoded stringbuffer postbody stringbuffer propertyiterator getarguments hasnext httpargument httpargument getobjectvalue havecontentencoding getencodedvalue contentencoding getencodedvalue postbody stringrequestentity requestentity stringrequestentity postbody tostring getrequestheader header_content_type getvalue contentencoding setrequestentity requestentity hascontenttypeheader setrequestheader header_content_type application_x_www_form_urlencoded propertyiterator getarguments hasnext httpargument httpargument getobjectvalue httpclient parametername getname isskippable parametername parametervalue getvalue isalwaysencoded urlcontentencoding contentencoding urlcontentencoding urlcontentencodin returns an code http connection code fully ready to attempt connection this means it sets the request method get or post headers cookies and authorization for the url request p the request infos are saved into the sample result if one is provided param u code url code of the url request param http method get put head etc param res sample result to save request infos to return code http connection code ready for connect exception io exception if an i o exception occurs protected http client setup connection url u http method base http method http sample result res throws io exception string url str u to string org apache commons httpclient uri uri new org apache commons httpclient uri url str false string schema uri get scheme if schema null schema length 0 schema protocol http if protocol https equals ignore case schema ssl manager get instance ensure the manager is initialised we don t currently need to do anything further as this sets the default https protocol protocol protocol protocol get protocol schema string host uri get host int port uri get port we use the host configuration as the key to retrieve the http client so need to ensure that any items used in its equals hashcode methods are not changed after use i e host port protocol local address proxy host configuration hc new host configuration hc set host host port protocol all needed to ensure re usablility set up the local address if one exists if local address null hc set local address local address boolean use proxy proxy defined is non proxy host if use proxy if log is debug enabled log debug setting proxy proxy host proxy port hc set proxy proxy host proxy port map map map http clients get http client http client http client map get hc if http client null http client new http client new simple http connection manager if log is debug enabled log debug created new http client system identity hash code http client http client set host configuration hc map put hc http client these items don t change so only need to be done once if use proxy if proxy user length 0 http client get state set proxy credentials new auth scope proxy host proxy port null auth scope any scheme new nt credentials proxy user proxy pass local host proxy domain else if log is debug enabled log debug reusing the http client system identity hash code http client int rto get response timeout if rto 0 http method get params set so timeout rto int cto get connect timeout if cto 0 http client get http connection manager get params set connection timeout cto allow http client to handle the redirects http method set follow redirects get auto redirects a well behaved browser is supposed to send connection close with the last request to an http server instead most browsers leave it to the server to close the connection after their timeout period leave it to the j meter user to decide if get use keep alive http method set request header header connection keep alive else http method set request header header connection connection close set connection headers http method u get header manager get cache manager string cookies set connection cookie http method u get cookie manager set connection authorization http client u get auth manager if res null res seturl u res set cookies cookies return http client httpconnection httpmethod httpconnection ioexception httpclient setupconnection httpmethodbase httpmethod httpsampleresult ioexception urlstr tostring urlstr getscheme protocol_http protocol_https equalsignorecase sslmanager getinstance getprotocol gethost getport hostconfiguration httpclient localaddress hostconfiguration hostconfiguration sethost localaddress setlocaladdress localaddress useproxy proxy_defined isnonproxy useproxy isdebugenabled proxy_host proxy_port setproxy proxy_host proxy_port httpclients httpclient httpclient httpclient httpclient httpclient httpclient simplehttpconnectionmanager isdebugenabled httpclient identityhashcode httpclient httpclient sethostconfiguration httpclient useproxy proxy_user httpclient getstate setproxycredentials authscope proxy_host proxy_port authscope any_scheme ntcredentials proxy_user proxy_pass localhost proxy_domain isdebugenabled httpclient identityhashcode httpclient getresponsetimeout httpmethod getparams setsotimeout getconnecttimeout httpclient gethttpconnectionmanager getparams setconnectiontimeout httpclient httpmethod setfollowredirects getautoredirects jmeter getusekeepalive httpmethod setrequestheader header_connection keep_alive httpmethod setrequestheader header_connection connection_close setconnectionheaders httpmethod getheadermanager getcachemanager setconnectioncookie httpmethod getcookiemanager setconnectionauthorization httpclient getauthmanager setcookies httpclient set any default request headers to include param http method the http method used for the request protected void set default request headers http method http method method left empty here but allows subclasses to override httpmethod httpmethod setdefaultrequestheaders httpmethod httpmethod gets the response headers param method connection from which the headers are read return string containing the headers one per line protected string get response headers http method method string buffer header buf new string buffer org apache commons httpclient header rh method get response headers header buf append method get status line header 0 is not the status line header buf append n non nls 1 for int i 0 i rh length i string key rh i get name header buf append key header buf append non nls 1 header buf append rh i get value header buf append n non nls 1 return header buf to string responseheaders getresponseheaders httpmethod stringbuffer headerbuf stringbuffer getresponseheaders headerbuf getstatusline headerbuf getname headerbuf headerbuf headerbuf getvalue headerbuf headerbuf tostring extracts all the required cookies for that particular url request and sets them in the code http method code passed in param method code http method code for the request param u code url code of the request param cookie manager the code cookie manager code containing all the cookies return a string containing the cookie details for the response may be null private string set connection cookie http method method url u cookie manager cookie manager string cookie header null if cookie manager null cookie header cookie manager get cookie header forurl u if cookie header null method set request header header cookie cookie header return cookie header httpmethod httpmethod cookiemanager cookiemanager setconnectioncookie httpmethod cookiemanager cookiemanager cookieheader cookiemanager cookieheader cookiemanager getcookieheaderforurl cookieheader setrequestheader header_cookie cookieheader cookieheader extracts all the required non cookie headers for that particular url request and sets them in the code http method code passed in param method code http method code which represents the request param u code url code of the url request param header manager the code header manager code containing all the cookies for this code url config code param cache manager the cache manager may be null private void set connection headers http method method url u header manager header manager cache manager cache manager set all the headers from the header manager if header manager null collection property headers header manager get headers if headers null property iterator i headers iterator while i has next org apache jmeter protocol http control header header org apache jmeter protocol http control header i next get object value string n header get name don t allow override of content length this helps with soap sampler hack too todo what other headers are not allowed if header content length equals ignore case n string v header get value method add request header n v if cache manager null cache manager set headers u method httpmethod httpmethod headermanager headermanager urlconfig cachemanager cachemanager setconnectionheaders httpmethod headermanager headermanager cachemanager cachemanager headermanager headermanager collectionproperty headermanager getheaders propertyiterator hasnext getobjectvalue getname soapsampler header_content_length equalsignorecase getvalue addrequestheader cachemanager cachemanager setheaders get all the request headers for the code http method code param method code http method code which represents the request return the headers as a string protected string get connection headers http method method get all the request headers string buffer hdrs new string buffer 100 header request headers method get request headers for int i 0 i request headers length i exclude the cookie header since cookie is reported separately in the sample if header cookie equals ignore case request headers i get name hdrs append request headers i get name hdrs append non nls 1 hdrs append request headers i get value hdrs append n non nls 1 return hdrs to string httpmethod httpmethod getconnectionheaders httpmethod stringbuffer stringbuffer requestheaders getrequestheaders requestheaders header_cookie equalsignorecase requestheaders getname requestheaders getname requestheaders getvalue tostring extracts all the required authorization for that particular url request and sets it in the code http method code passed in param client the http client object param u code url code of the url request param auth manager the code auth manager code containing all the authorisations for this code url config code private void set connection authorization http client client url u auth manager auth manager http params params client get params if auth manager null authorization auth auth manager get auth forurl u if auth null string username auth get user string realm auth get realm string domain auth get domain if log is debug enabled log debug username d username d domain r realm client get state set credentials new auth scope u get host u get port realm length 0 null realm is not the same as no realm auth scope any scheme nt includes other types of credentials new nt credentials username auth get pass local host domain we have credentials should we set pre emptive authentication if can set pre emptive log debug setting pre emptive authentication params set boolean parameter http authentication preemptive true else client get state clear credentials if can set pre emptive params set boolean parameter http authentication preemptive false else client get state clear credentials httpmethod httpclient authmanager authmanager urlconfig setconnectionauthorization httpclient authmanager authmanager httpparams getparams authmanager authmanager getauthforurl getuser getrealm getdomain isdebugenabled getstate setcredentials authscope gethost getport authscope any_scheme ntcredentials getpass localhost cansetpreemptive setbooleanparameter http_authentication_preemptive getstate clearcredentials cansetpreemptive setbooleanparameter http_authentication_preemptive getstate clearcredentials samples the url passed in and stores the result in code http sample result code following redirects and downloading page resources as appropriate p when getting a redirect target redirects are not followed and resources are not downloaded the caller will take care of this param url url to sample param method http method get post param are following redirect whether we re getting a redirect target param frame depth depth of this target in the frame structure used only to prevent infinite recursion return results of the sampling protected http sample result sample url url string method boolean are following redirect int frame depth string url str url to string log debug start sample url str log debug method method http method base http method null http sample result res new http sample result res set monitor is monitor res set sample label url str may be replaced later res sethttp method method res sample start count the retries as well in the time http client client null input stream instream null try may generate illegal argument exception if method equals post http method new post method url str else if method equals put http method new put method url str else if method equals head http method new head method url str else if method equals trace http method new trace method url str else if method equals options http method new options method url str else if method equals delete http method new delete method url str else if method equals get http method new get method url str else log error unexpected method converted to get method http method new get method url str set any default request headers set default request headers http method setup connection client setup connection url http method res handle the various methods if method equals post string post body send post data post method http method res set query string post body else if method equals put string put body send put data put method http method res set query string put body saved client client int status code client execute method http method needs to be done after execute to pick up all the headers res set request headers get connection headers http method request sent now get the response instream http method get response body as stream if instream null will be null for head header response header http method get response header header content encoding if response header null encoding gzip equals response header get value instream new gzip input stream instream res set response data read response res instream int http method get response content length res sample end done with the sampling proper now collect the results into the http sample result res set sample label http method geturi to string pick up actual path after redirects res set response code integer to string status code res set successful is success code status code res set response message http method get status text string ct null org apache commons httpclient header h http method get response header header content type if h null can be missing e g on redirect ct h get value res set content type ct e g text html charset iso 8859 1 res set encoding and type ct res set response headers get response headers http method if res is redirect final header header location http method get response header header location if header location null http protocol violation but avoids npe throw new illegal argument exception missing location header res set redirect location header location get value if we redirected automatically the url may have changed if get auto redirects res seturl new url http method geturi to string store any cookies received in the cookie manager save connection cookies http method res geturl get cookie manager save cache information final cache manager cache manager get cache manager if cache manager null cache manager save details http method res follow redirects and download page resources if appropriate res result processing are following redirect frame depth res log debug end sample http method release connection return res catch illegal argument exception e e g some kinds of invalid url res sample end http sample result err error result e res err set sample label error url to string return err catch io exception e res sample end http sample result err error result e res err set sample label error url to string return err finally saved client null j orphan utils close quietly instream if http method null http method release connection httpsampleresult arefollowingredirect framedepth httpsampleresult arefollowingredirect framedepth urlstr tostring urlstr httpmethodbase httpmethod httpsampleresult httpsampleresult setmonitor ismonitor setsamplelabel urlstr sethttpmethod samplestart httpclient inputstream illegalargumentexception httpmethod postmethod urlstr httpmethod putmethod urlstr httpmethod headmethod urlstr httpmethod tracemethod urlstr httpmethod optionsmethod urlstr httpmethod deletemethod urlstr httpmethod getmethod urlstr httpmethod getmethod urlstr setdefaultrequestheaders httpmethod setupconnection httpmethod postbody sendpostdata postmethod httpmethod setquerystring postbody putbody sendputdata putmethod httpmethod setquerystring putbody savedclient statuscode executemethod httpmethod setrequestheaders getconnectionheaders httpmethod httpmethod getresponsebodyasstream responseheader httpmethod getresponseheader header_content_encoding responseheader encoding_gzip responseheader getvalue gzipinputstream setresponsedata readresponse httpmethod getresponsecontentlength sampleend httpsampleresult setsamplelabel httpmethod tostring setresponsecode tostring statuscode setsuccessful issuccesscode statuscode setresponsemessage httpmethod getstatustext httpmethod getresponseheader header_content_type getvalue setcontenttype setencodingandtype setresponseheaders getresponseheaders httpmethod isredirect headerlocation httpmethod getresponseheader header_location headerlocation illegalargumentexception setredirectlocation headerlocation getvalue getautoredirects httpmethod tostring saveconnectioncookies httpmethod getcookiemanager cachemanager cachemanager getcachemanager cachemanager cachemanager savedetails httpmethod resultprocessing arefollowingredirect framedepth httpmethod releaseconnection illegalargumentexception sampleend httpsampleresult errorresult setsamplelabel tostring ioexception sampleend httpsampleresult errorresult setsamplelabel tostring savedclient jorphanutils closequietly httpmethod httpmethod releaseconnection set up the put data private string send put data put method put throws io exception buffer to hold the put body except file content string buffer put body new string buffer 1000 boolean has put body false check if the header manager had a content type header this allows the user to specify his own content type for a post request header content type header put get request header header content type boolean has content type header content type header null content type header get value null content type header get value length 0 http file arg files gethttp files if there are no arguments we can send a file as the body of the request if has arguments get send file as post body has put body true if get send file as post body returned true it s sure that file is not null file request entity file request entity new file request entity new file files 0 get path null put set request entity file request entity we just add placeholder text for file content put body append actual file content not shown here if none of the arguments have a name specified we just send all the values as the put body else if get send parameter values as post body has put body true if a content encoding is specified we set it as http parameter so that the post body will be encoded in the specified content encoding final string content encoding get content encoding boolean have content encoding false if content encoding null content encoding trim length 0 put get params set content charset content encoding have content encoding true just append all the parameter values and use that as the post body string buffer put body content new string buffer property iterator args get arguments iterator while args has next http argument arg http argument args next get object value string value null if have content encoding value arg get encoded value content encoding else value arg get encoded value put body content append value string content type value null if has content type header content type value put get request header header content type get value string request entity request entity new string request entity put body content to string content type value put get request char set put set request entity request entity check if we have any content to send for body if has put body if the request entity is repeatable we can send it first to our own stream so we can return it if put get request entity is repeatable byte array output stream bos new byte array output stream put get request entity write request bos bos flush we get the posted bytes using the charset that was used to create them put body append new string bos to byte array put get request char set bos close else put body append request entity was not repeatable cannot view what was sent if has content type header allow the mimetype of the file to control the content type this is not obvious in gui if you are not uploading any files but just sending the content of nameless parameters todo needs a multiple file upload scenerio http file arg file files length 0 files 0 null if file null file get mime type null file get mime type length 0 put set request header header content type file get mime type set the content length put set request header header content length long to string put get request entity get content length return put body to string return null sendputdata putmethod ioexception stringbuffer putbody stringbuffer hasputbody contenttypeheader getrequestheader header_content_type hascontenttypeheader contenttypeheader contenttypeheader getvalue contenttypeheader getvalue httpfilearg gethttpfiles hasarguments getsendfileaspostbody hasputbody getsendfileaspostbody filerequestentity filerequestentity filerequestentity getpath setrequestentity filerequestentity putbody getsendparametervaluesaspostbody hasputbody contentencoding getcontentencoding havecontentencoding contentencoding contentencoding getparams setcontentcharset contentencoding havecontentencoding stringbuffer putbodycontent stringbuffer propertyiterator getarguments hasnext httpargument httpargument getobjectvalue havecontentencoding getencodedvalue contentencoding getencodedvalue putbodycontent contenttypevalue hascontenttypeheader contenttypevalue getrequestheader header_content_type getvalue stringrequestentity requestentity stringrequestentity putbodycontent tostring contenttypevalue getrequestcharset setrequestentity requestentity hasputbody getrequestentity isrepeatable bytearrayoutputstream bytearrayoutputstream getrequestentity writerequest putbody tobytearray getrequestcharset putbody requestentity hascontenttypeheader httpfilearg getmimetype getmimetype setrequestheader header_content_type getmimetype setrequestheader header_content_length tostring getrequestentity getcontentlength putbody tostring private boolean hide file data public viewable file part string name file file string content type string charset throws file not found exception super name file content type charset this hide file data false hidefiledata viewablefilepart contenttype filenotfoundexception contenttype hidefiledata public void set hide file data boolean hide file data this hide file data hide file data sethidefiledata hidefiledata hidefiledata hidefiledata protected void send data output stream out throws io exception check if we should send only placeholder text for the file content or the real file content if hide file data out write actual file content not shown here get bytes encoding does not really matter here else super send data out senddata outputstream ioexception hidefiledata getbytes senddata from the code http method code store all the set cookie key pair values in the cookie manager of the code url config code param method code http method code which represents the request param u code url code of the url request param cookie manager the code cookie manager code containing all the cookies protected void save connection cookies http method method url u cookie manager cookie manager if cookie manager null header hdr method get response headers header set cookie for int i 0 i hdr length i cookie manager add cookie from header hdr i get value u httpmethod cookiemanager urlconfig httpmethod cookiemanager cookiemanager saveconnectioncookies httpmethod cookiemanager cookiemanager cookiemanager getresponseheaders header_set_cookie cookiemanager addcookiefromheader getvalue public void thread started log debug thread started does not need to be synchronised as all access is from same thread http clients set new hash map threadstarted httpclients hashmap public void thread finished log debug thread finished does not need to be synchronised as all access is from same thread map map map http clients get if map null for iterator it map entry set iterator it has next map entry entry map entry it next http client cl http client entry get value can cause npe in http client 3 1 simple http connection manager cl get http connection manager shutdown closes the connection revert to original method cl get http connection manager close idle connections 1000 closes the connection map clear threadfinished httpclients entryset hasnext httpclient httpclient getvalue httpclient simplehttpconnectionmanager gethttpconnectionmanager gethttpconnectionmanager closeidleconnections inherit doc public boolean interrupt http client client saved client if client null saved client null todo not sure this is the best method final http connection manager http connection manager client get http connection manager if http connection manager instanceof simple http connection manager should be true simple http connection manager http connection manager shutdown return client null inheritdoc httpclient savedclient savedclient httpconnectionmanager httpconnectionmanager gethttpconnectionmanager httpconnectionmanager simplehttpconnectionmanager simplehttpconnectionmanager httpconnectionmanager public final static string password config test element password public config test element configtestelement configtestelement public void add test element test element parm1 if parm1 instanceof config test element merge in parm1 addtestelement testelement configtestelement mergein see org apache jmeter config config element add config element org apache jmeter config config element public void add config element config element config merge in test element config configelement addconfigelement configelement addconfigelement configelement mergein testelement see org apache jmeter config config element expects modification public boolean expects modification return false configelement expectsmodification expectsmodification public stat graph visualizer super model new object table model columns sampling stat calculator class new functor new functor get label non nls 1 new functor get count non nls 1 new functor get mean as number non nls 1 new functor get median non nls 1 new functor get percent point non nls 1 new object new float 900 new functor get min non nls 1 new functor get max non nls 1 new functor get error percentage non nls 1 new functor get rate non nls 1 new functor getkb per second non nls 1 new functor null null null null null null null null null null new class string class long class long class long class long class long class long class string class string class string class clear data init statgraphvisualizer objecttablemodel samplingstatcalculator getlabel getcount getmeanasnumber getmedian getpercentpoint getmin getmax geterrorpercentage getrate getkbpersecond cleardata public static boolean test functors stat graph visualizer instance new stat graph visualizer return instance model check functors null instance get class testfunctors statgraphvisualizer statgraphvisualizer checkfunctors getclass public string get label resource return aggregate graph title non nls 1 getlabelresource aggregate_graph_title public void add sample result res sampling stat calculator row null final string sample label res get sample label synchronized table rows row sampling stat calculator table rows get sample label if row null row new sampling stat calculator sample label table rows put row get label row model insert row row model get row count 1 row add sample res sampling stat calculator table rows get total row label add sample res model fire table data changed sampleresult samplingstatcalculator samplelabel getsamplelabel tablerows samplingstatcalculator tablerows samplelabel samplingstatcalculator samplelabel tablerows getlabel insertrow getrowcount addsample samplingstatcalculator tablerows total_row_label addsample firetabledatachanged clears this visualizer and its model and forces a repaint of the table public void clear data model clear data table rows clear table rows put total row label new sampling stat calculator total row label model add row table rows get total row label cleardata cleardata tablerows tablerows total_row_label samplingstatcalculator total_row_label addrow tablerows total_row_label main visualizer setup private void init this set layout new border layout main panel j panel main panel new j panel border margin new empty border 10 10 5 10 border margin2 new empty border 10 10 5 10 main panel set border margin main panel set layout new box layout main panel box layout y axis main panel add make title panel myj table new j table model myj table set preferred scrollable viewport size new dimension 500 80 renderer utils apply renderers myj table renderers my scroll pane new j scroll pane myj table graph new vertical panel graph set border margin2 j label graph label new j label j meter utils get res string aggregate graph non nls 1 graph panel new axis graph graph panel set preferred size new dimension default width default height horizontal panel for the buttons horizontal panel buttonpanel new horizontal panel buttonpanel add columns buttonpanel add display button buttonpanel add save graph buttonpanel add save table buttonpanel add save headers graph add graph label graph add graph title graph add max lengthx axis label graph add graph width graph add graph height graph add buttonpanel graph add graph panel display button add action listener this save graph add action listener this save table add action listener this graph scroll new j scroll pane graph graph scroll set autoscrolls true spane new j split pane j split pane vertical split spane set left component my scroll pane spane set right component graph scroll spane set resize weight 2 spane set continuous layout true this add main panel border layout north this add spane border layout center setlayout borderlayout jpanel mainpanel jpanel emptyborder emptyborder mainpanel setborder mainpanel setlayout boxlayout mainpanel boxlayout y_axis mainpanel maketitlepanel myjtable jtable myjtable setpreferredscrollableviewportsize rendererutils applyrenderers myjtable myscrollpane jscrollpane myjtable verticalpanel setborder jlabel graphlabel jlabel jmeterutils getresstring aggregate_graph graphpanel axisgraph graphpanel setpreferredsize defaultwidth defaultheight horizontalpanel horizontalpanel displaybutton savegraph savetable saveheaders graphlabel graphtitle maxlengthxaxislabel graphwidth graphheight graphpanel displaybutton addactionlistener savegraph addactionlistener savetable addactionlistener graphscroll jscrollpane graphscroll setautoscrolls jsplitpane jsplitpane vertical_split setleftcomponent myscrollpane setrightcomponent graphscroll setresizeweight setcontinuouslayout mainpanel borderlayout borderlayout public void make graph string wstr graph width get text string hstr graph height get text string lstr max lengthx axis label get text if wstr length 0 wstr 450 non nls 1 if hstr length 0 hstr 250 non nls 1 if lstr length 0 lstr 20 non nls 1 int width integer parse int wstr int height integer parse int hstr int max length integer parse int lstr graph panel set data this get data graph panel set height height graph panel set width width graph panel set title graph title get text graph panel set max length max length graph panel setx axis labels get axis labels graph panel setx axis title columns get text graph panel sety axis labels this y axis label graph panel sety axis title this y axis title graph panel set preferred size new dimension width height graph set size new dimension graph get width height 120 spane repaint makegraph graphwidth gettext graphheight gettext maxlengthxaxislabel gettext parseint parseint maxlength parseint graphpanel setdata getdata graphpanel setheight graphpanel setwidth graphpanel settitle graphtitle gettext graphpanel setmaxlength maxlength graphpanel setxaxislabels getaxislabels graphpanel setxaxistitle gettext graphpanel setyaxislabels yaxislabel graphpanel setyaxistitle yaxistitle graphpanel setpreferredsize setsize getwidth public double get data if model get row count 1 int count model get row count 1 int col model find column columns get text double data new double 1 count for int idx 0 idx count idx data 0 idx number model get value at idx col double value return data return new double 250 45 36 66 145 80 55 getdata getrowcount getrowcount findcolumn gettext getvalueat doublevalue public string get axis labels if model get row count 1 int count model get row count 1 string labels new string count for int idx 0 idx count idx labels idx string model get value at idx 0 return labels return new string samples jsp samples manager manager status hello world getaxislabels getrowcount getrowcount getvalueat we use this method to get the data since we are using object table model so the calling get data vector doesn t work as expected return the data from the model public vector get all table data vector data new vector if model get row count 0 for int rw 0 rw model get row count rw int cols model get column count vector column new vector data add column for int idx 0 idx cols idx object val model get value at rw idx column add val return data objecttablemodel getdatavector getalltabledata getrowcount getrowcount getcolumncount getvalueat public void action performed action event event if event get source display button make graph else if event get source save graph save graph to file true try action router get instance get action action names save graphics save graphics class get name do action new action event this 1 action names save graphics catch exception e log error e get message else if event get source save table j file chooser chooser file dialoger prompt to save file statistics csv non nls 1 if chooser null return file writer writer null try writer new file writer chooser get selected file vector data this get all table data csv save service savecsv stats data writer save headers is selected columns null catch file not found exception e log warn e get message catch io exception e log warn e get message finally j orphan utils close quietly writer actionperformed actionevent getsource displaybutton makegraph getsource savegraph savegraphtofile actionrouter getinstance getaction actionnames save_graphics savegraphics getname doaction actionevent actionnames save_graphics getmessage getsource savetable jfilechooser filedialoger prompttosavefile filewriter filewriter getselectedfile getalltabledata csvsaveservice savecsvstats saveheaders isselected filenotfoundexception getmessage ioexception getmessage jorphanutils closequietly public j component get printable component if save graph to file true save graph to file false graph panel set bounds graph panel get location x graph panel get location y graph panel width graph panel height return graph panel return this jcomponent getprintablecomponent savegraphtofile savegraphtofile graphpanel setbounds graphpanel getlocation graphpanel getlocation graphpanel graphpanel graphpanel private object values public variable public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception string variable name compound variable values 0 execute string variable value get variables get variable name return variable value null variable name variable value sampleresult previousresult currentsampler invalidvariableexception variablename compoundvariable variablevalue getvariables variablename variablevalue variablename variablevalue public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters min parameter count max parameter count values parameters to array setparameters invalidvariableexception checkparametercount min_parameter_count max_parameter_count toarray public string get reference key return key getreferencekey public list get argument desc return desc getargumentdesc private j text field md5 hex input public md5 hex assertiongui init jtextfield md5hexinput md5hexassertiongui private void init set layout new border layout 0 10 set border make border add make title panel border layout north j panel main panel new j panel new border layout user input horizontal panel md5 hex panel new horizontal panel md5 hex panel set border border factory create titled border border factory create etched border j meter utils get res string md5hex assertion md5hex test non nls 1 md5 hex panel add new j label j meter utils get res string md5hex assertion label non nls 1 md5 hex input new j text field 25 md5 hex input add focus listener this md5 hex panel add md5 hex input main panel add md5 hex panel border layout north add main panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout jpanel mainpanel jpanel borderlayout user_input horizontalpanel md5hexpanel horizontalpanel md5hexpanel setborder borderfactory createtitledborder borderfactory createetchedborder jmeterutils getresstring md5hex_assertion_md5hex_test md5hexpanel jlabel jmeterutils getresstring md5hex_assertion_label md5hexinput jtextfield md5hexinput addfocuslistener md5hexpanel md5hexinput mainpanel md5hexpanel borderlayout mainpanel borderlayout public void configure test element el super configure el md5 hex assertion assertion md5 hex assertion el this md5 hex input set text string value of assertion get allowedmd5 hex testelement md5hexassertion md5hexassertion md5hexinput settext valueof getallowedmd5hex public string get label resource return md5hex assertion title non nls 1 getlabelresource md5hex_assertion_title public test element create test element md5 hex assertion el new md5 hex assertion modify test element el return el testelement createtestelement md5hexassertion md5hexassertion modifytestelement public void modify test element test element element configure test element element string md5 hex string this md5 hex input get text initialize to empty string this will fail the assertion if md5 hex string null md5 hex string length 0 md5 hex string md5 hex assertion element set allowedmd5 hex md5 hex string modifytestelement testelement configuretestelement md5hexstring md5hexinput gettext md5hexstring md5hexstring md5hexstring md5hexassertion setallowedmd5hex md5hexstring implements j metergui component clear gui public void clear gui super clear gui md5 hex input set text non nls 1 jmeterguicomponent cleargui cleargui cleargui md5hexinput settext public void process string buffer sb new string buffer 100 j meter context thread context get thread context property iterator i thread context get current sampler property iterator while i has next j meter property prop i next sb append prop get name sb append sb append prop get string value sb append n sample result sr new sample result sr set response data sb to string get bytes sr set data type text sr set sample label get name sr set successful true sr set sampler data sampler property values thread context get previous result add sub result sr stringbuffer stringbuffer jmetercontext threadcontext getthreadcontext propertyiterator threadcontext getcurrentsampler propertyiterator hasnext jmeterproperty getname getstringvalue sampleresult sampleresult setresponsedata tostring getbytes setdatatype setsamplelabel getname setsuccessful setsamplerdata samplerpropertyvalues threadcontext getpreviousresult addsubresult public thread info impl super threadinfoimpl public int get max spare threads return this max spare threads getmaxsparethreads maxsparethreads public void set max spare threads int value this max spare threads value setmaxsparethreads maxsparethreads public int get min spare threads return this min spare threads getminsparethreads minsparethreads public void set min spare threads int value this min spare threads value setminsparethreads minsparethreads public int get max threads return this max threads getmaxthreads maxthreads public void set max threads int value this max threads value setmaxthreads maxthreads public int get current threads busy return this current threads busy getcurrentthreadsbusy currentthreadsbusy public void set current threads busy int value this current threads busy value setcurrentthreadsbusy currentthreadsbusy public int get current thread count return this current thread count getcurrentthreadcount currentthreadcount public void set current thread count int value this current thread count value setcurrentthreadcount currentthreadcount deprecated only for use by unit tests public multipart url config this null multiparturlconfig called by http request hdr public multipart url config string boundary args new arguments files new http file args this boundary boundary httprequesthdr multiparturlconfig httpfileargs public string get boundary return boundary getboundary public arguments get arguments return args getarguments public void add argument string name string value arguments my args this get arguments my args add argument new http argument name value addargument myargs getarguments myargs addargument httpargument public void add argument string name string value string metadata arguments my args this get arguments my args add argument new http argument name value metadata addargument myargs getarguments myargs addargument httpargument public http file args gethttp file args return files httpfileargs gethttpfileargs add a value that is not url encoded and make sure it appears in the gui that it will not be encoded when the request is sent param name param value private void add non encoded argument string name string value arguments my args get arguments the value is not encoded http argument arg new http argument name value false let the gui show that it will not be encoded arg set always encoded false my args add argument arg addnonencodedargument myargs getarguments httpargument httpargument setalwaysencoded myargs addargument this method allows a proxy server to send over the raw text from a browser s output stream to be parsed and stored correctly into the url config object public void parse arguments string query string string parts j orphan utils split query string get boundary non nls 1 for int i 0 i parts length i string content disposition get header value content disposition parts i non nls 1 string content type get header value content type parts i non nls 1 check if it is form data if content disposition null content disposition index of form data 1 non nls 1 get the form field name final string name prefix name non nls 1 int index content disposition index of name prefix name prefix length string name content disposition substring index content disposition index of index non nls 1 check if it is a file being uploaded final string filename prefix filename non nls 1 if content disposition index of filename prefix 1 get the filename index content disposition index of filename prefix filename prefix length string path content disposition substring index content disposition index of index non nls 1 if path null path length 0 set the values retrieved for the file upload files addhttp file arg path name content type else find the first empty line of the multipart it signals end of headers for multipart int index empty lf cr lf line pos parts i index of n r n non nls 1 int index empty lf lf line pos parts i index of n n non nls 1 string value null if index empty lf cr lf line pos 1 value parts i substring index empty lf cr lf line pos trim else if index empty lf lf line pos 1 value parts i substring index empty lf lf line pos trim this add non encoded argument name value urlconfig parsearguments querystring jorphanutils querystring getboundary contentdisposition getheadervalue contenttype getheadervalue contentdisposition contentdisposition indexof nameprefix contentdisposition indexof nameprefix nameprefix contentdisposition contentdisposition indexof filenameprefix contentdisposition indexof filenameprefix contentdisposition indexof filenameprefix filenameprefix contentdisposition contentdisposition indexof addhttpfilearg contenttype indexemptylfcrlflinepos indexof indexemptylflflinepos indexof indexemptylfcrlflinepos indexemptylfcrlflinepos indexemptylflflinepos indexemptylflflinepos addnonencodedargument private string get header value string header name string multi part string regular expression header name s s non nls 1 perl5 matcher local matcher j meter utils get matcher pattern pattern j meter utils get pattern regular expression perl5 compiler read only mask perl5 compiler case insensitive mask perl5 compiler multiline mask if local matcher contains multi part pattern return local matcher get match group 1 trim else return null getheadervalue headername multipart regularexpression headername perl5matcher localmatcher jmeterutils getmatcher jmeterutils getpattern regularexpression perl5compiler read_only_mask perl5compiler case_insensitive_mask perl5compiler multiline_mask localmatcher multipart localmatcher getmatch public class test if controller extends j meter test case public test if controller string name super name testifcontroller jmetertestcase testifcontroller public void test processing throws exception generic controller controller new generic controller controller add test element new if controller false false controller add test element new if controller a equals a controller add test element new if controller 2 100 todo enable some proper tests generic controller sub 1 new generic controller sub 1 add test element new if controller 3 3 controller add test element sub 1 controller add test element new if controller false true generic controller controller new generic controller generic controller sub 1 new generic controller sub 1 add test element new if controller 10 100 sub 1 add test element new if controller true false controller add test element sub 1 controller add test element new if controller false false if controller sub 2 new if controller sub 2 set condition 10 10000 generic controller sub 3 new generic controller sub 2 add test element new if controller a equals a sub 3 add test element new if controller 2 100 sub 3 add test element new if controller false true sub 2 add test element sub 3 sub 2 add test element new if controller 2 3 controller add test element sub 2 if controller controller new if controller 12 12 controller initialize test element sampler null while sampler controller next null logger debug gonna assert true sampler get class get name property is sampler get name testprocessing genericcontroller genericcontroller addtestelement ifcontroller addtestelement ifcontroller addtestelement ifcontroller genericcontroller sub_1 genericcontroller sub_1 addtestelement ifcontroller addtestelement sub_1 addtestelement ifcontroller genericcontroller genericcontroller genericcontroller sub_1 genericcontroller sub_1 addtestelement ifcontroller sub_1 addtestelement ifcontroller addtestelement sub_1 addtestelement ifcontroller ifcontroller sub_2 ifcontroller sub_2 setcondition genericcontroller sub_3 genericcontroller sub_2 addtestelement ifcontroller sub_3 addtestelement ifcontroller sub_3 addtestelement ifcontroller sub_2 addtestelement sub_3 sub_2 addtestelement ifcontroller addtestelement sub_2 ifcontroller ifcontroller testelement asserttrue getclass getname getname private replace string with functions transformer public package test string arg0 super arg0 replacestringwithfunctions packagetest public void set up jmctx j meter context service get context variables new hash map variables put my regex variables put server jakarta apache org result new sample result result set response data html hello world html costs 3 47 5 67 get bytes transformer new replace string with functions new compound variable variables jmctx set variables new j meter variables jmctx set sampling started true jmctx set previous result result jmctx get variables put server jakarta apache org jmctx get variables put my regex setup jmetercontextservice getcontext hashmap my_regex sampleresult setresponsedata getbytes replacestringwithfunctions compoundvariable setvariables jmetervariables setsamplingstarted setpreviousresult getvariables getvariables my_regex public void test function parse1 throws exception string property prop new string property date javascript new date get date 100 to string substr javascript 1 1 d ay 2 heute j meter property new prop transformer transform value prop new prop set running version true assert equals org apache jmeter testelement property function property new prop get class get name new prop recover running version null assert true integer parse int new prop get string value 1 assert equals 2 jmctx get variables get object d ay testfunctionparse1 stringproperty stringproperty __javascript getdate tostring __javascript jmeterproperty newprop transformvalue newprop setrunningversion assertequals functionproperty newprop getclass getname newprop recoverrunningversion asserttrue parseint newprop getstringvalue assertequals getvariables getobject public void test parse example1 throws exception string property prop new string property html regexfunction html html 1 j meter property new prop transformer transform value prop new prop set running version true assert equals org apache jmeter testelement property function property new prop get class get name assert equals hello world new prop get string value testparseexample1 stringproperty stringproperty __regexfunction jmeterproperty newprop transformvalue newprop setrunningversion assertequals functionproperty newprop getclass getname assertequals newprop getstringvalue public void test parse example2 throws exception string property prop new string property html it should say regexfunction html html 1 j meter property new prop transformer transform value prop new prop set running version true assert equals org apache jmeter testelement property function property new prop get class get name assert equals it should say hello world new prop get string value testparseexample2 stringproperty stringproperty __regexfunction jmeterproperty newprop transformvalue newprop setrunningversion assertequals functionproperty newprop getclass getname assertequals newprop getstringvalue public void test parse example3 throws exception string property prop new string property html regexfunction html html 1 regexfunction html o o html 1 3 j meter property new prop transformer transform value prop new prop set running version true assert equals org apache jmeter testelement property function property new prop get class get name assert equals hello worldhellorld new prop get string value testparseexample3 stringproperty stringproperty __regexfunction __regexfunction jmeterproperty newprop transformvalue newprop setrunningversion assertequals functionproperty newprop getclass getname assertequals newprop getstringvalue public void test parse example4 throws exception string property prop new string property html non existing function j meter property new prop transformer transform value prop new prop set running version true assert equals org apache jmeter testelement property function property new prop get class get name assert equals non existing function new prop get string value testparseexample4 stringproperty stringproperty jmeterproperty newprop transformvalue newprop setrunningversion assertequals functionproperty newprop getclass getname assertequals newprop getstringvalue public void test parse example6 throws exception string property prop new string property html server j meter property new prop transformer transform value prop new prop set running version true assert equals org apache jmeter testelement property function property new prop get class get name assert equals jakarta apache org new prop get string value testparseexample6 stringproperty stringproperty jmeterproperty newprop transformvalue newprop setrunningversion assertequals functionproperty newprop getclass getname assertequals newprop getstringvalue public void test parse example5 throws exception string property prop new string property html j meter property new prop transformer transform value prop new prop set running version true assert equals org apache jmeter testelement property string property new prop get class get name assert equals new prop get string value testparseexample5 stringproperty stringproperty jmeterproperty newprop transformvalue newprop setrunningversion assertequals stringproperty newprop getclass getname assertequals newprop getstringvalue public void test parse example7 throws exception string property prop new string property html regexfunction a z 1 j meter property new prop transformer transform value prop new prop set running version true assert equals org apache jmeter testelement property function property new prop get class get name assert equals html new prop get string value testparseexample7 stringproperty stringproperty __regexfunction jmeterproperty newprop transformvalue newprop setrunningversion assertequals functionproperty newprop getclass getname assertequals newprop getstringvalue public void test parse example8 throws exception string property prop new string property html regexfunction d d 1 j meter property new prop transformer transform value prop new prop set running version true assert equals org apache jmeter testelement property function property new prop get class get name assert equals 3 47 new prop get string value testparseexample8 stringproperty stringproperty __regexfunction jmeterproperty newprop transformvalue newprop setrunningversion assertequals functionproperty newprop getclass getname assertequals newprop getstringvalue public void test parse example9 throws exception string property prop new string property html regexfunction d d 1 j meter property new prop transformer transform value prop new prop set running version true assert equals org apache jmeter testelement property function property new prop get class get name assert equals 3 47 new prop get string value testparseexample9 stringproperty stringproperty __regexfunction jmeterproperty newprop transformvalue newprop setrunningversion assertequals functionproperty newprop getclass getname assertequals newprop getstringvalue public void test parse example10 throws exception string property prop new string property html regexfunction d d d d 1 j meter property new prop transformer transform value prop new prop set running version true assert equals org apache jmeter testelement property function property new prop get class get name assert equals 3 47 5 67 new prop get string value testparseexample10 stringproperty stringproperty __regexfunction jmeterproperty newprop transformvalue newprop setrunningversion assertequals functionproperty newprop getclass getname assertequals newprop getstringvalue escaped dollar commma and backslash with no variable reference public void test parse example11 throws exception string property prop new string property html a x jakarta apache org j meter property new prop transformer transform value prop new prop set running version true assert equals org apache jmeter testelement property string property new prop get class get name assert equals a x jakarta apache org new prop get string value testparseexample11 stringproperty stringproperty jmeterproperty newprop transformvalue newprop setrunningversion assertequals stringproperty newprop getclass getname assertequals newprop getstringvalue escaped dollar commma and backslash with variable reference public void test parse example12 throws exception string property prop new string property html a x server b cd j meter property new prop transformer transform value prop new prop set running version true n b backslashes are removed before dollar comma and backslash assert equals a x jakarta apache org b cd new prop get string value testparseexample12 stringproperty stringproperty jmeterproperty newprop transformvalue newprop setrunningversion assertequals newprop getstringvalue escaped dollar commma and backslash with missing variable reference public void test parse example13 throws exception string property prop new string property html a x missing b cd j meter property new prop transformer transform value prop new prop set running version true n b backslashes are removed before dollar comma and backslash assert equals a x missing b cd new prop get string value testparseexample13 stringproperty stringproperty jmeterproperty newprop transformvalue newprop setrunningversion assertequals newprop getstringvalue escaped dollar commma and backslash with missing function reference public void test parse example14 throws exception string property prop new string property html a x missing a b cd j meter property new prop transformer transform value prop new prop set running version true n b backslashes are removed before dollar comma and backslash assert equals a x missing a b cd new prop get string value testparseexample14 stringproperty stringproperty __missing jmeterproperty newprop transformvalue newprop setrunningversion assertequals __missing newprop getstringvalue public void test nested example1 throws exception string property prop new string property html regexfunction html my regex html 1 regexfunction html o o html 1 3 j meter property new prop transformer transform value prop new prop set running version true assert equals org apache jmeter testelement property function property new prop get class get name assert equals hello worldhellorld new prop get string value testnestedexample1 stringproperty stringproperty __regexfunction my_regex __regexfunction jmeterproperty newprop transformvalue newprop setrunningversion assertequals functionproperty newprop getclass getname assertequals newprop getstringvalue public void test nested example2 throws exception string property prop new string property html regexfunction html my regex html 1 j meter property new prop transformer transform value prop new prop set running version true assert equals org apache jmeter testelement property function property new prop get class get name assert equals hello world new prop get string value testnestedexample2 stringproperty stringproperty __regexfunction my_regex jmeterproperty newprop transformvalue newprop setrunningversion assertequals functionproperty newprop getclass getname assertequals newprop getstringvalue create a new test plan gui public report gui init testplangui reportgui need to update this to make the context popupmenu correct return a j popup menu appropriate for the component public j popup menu create popup menu j popup menu pop new j popup menu j menu add menu new j menu j meter utils get res string add add menu add report menu factory make menu item new report page gui get static label report page gui class get name add add menu add report menu factory make menu item new html report writer gui get static label html report writer gui class get name add add menu add report menu factory make menu report menu factory config elements add pop add add menu report menu factory add file menu pop report menu factory add edit menu pop true return pop jpopupmenu jpopupmenu createpopupmenu jpopupmenu jpopupmenu jmenu addmenu jmenu jmeterutils getresstring addmenu reportmenufactory makemenuitem reportpagegui getstaticlabel reportpagegui getname addmenu reportmenufactory makemenuitem htmlreportwritergui getstaticlabel htmlreportwritergui getname addmenu reportmenufactory makemenu reportmenufactory config_elements addmenu reportmenufactory addfilemenu reportmenufactory addeditmenu implements j metergui component create test element public test element create test element report plan tp new report plan modify test element tp return tp jmeterguicomponent createtestelement testelement createtestelement reportplan reportplan modifytestelement implements j metergui component modify test element test element public void modify test element test element plan super configure test element plan if plan instanceof report plan report plan rp report plan plan rp set user defined variables arguments args panel create test element rp set property report plan comments comment panel get text rp set basedir base dir get filename jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement reportplan reportplan reportplan setuserdefinedvariables argspanel createtestelement setproperty reportplan commentpanel gettext setbasedir basedir getfilename public string get label resource return report plan getlabelresource report_plan this is the list of menu categories this gui component will be available under this implementation returns null since the test plan appears at the top level of the tree and cannot be added elsewhere return a collection of strings where each element is one of the constants defined in menu factory public collection get menu categories return null testplan menufactory getmenucategories a newly created component can be initialized with the contents of a test element object by calling this method the component is responsible for querying the test element object for the relevant information to display in its gui param el the test element to configure public void configure test element el super configure el if el get property report plan user defined variables null args panel configure arguments el get property report plan user defined variables get object value comment panel set text el get property as string report plan comments base dir set filename el get property as string report plan basedir testelement testelement getproperty reportplan user_defined_variables argspanel getproperty reportplan user_defined_variables getobjectvalue commentpanel settext getpropertyasstring reportplan basedir setfilename getpropertyasstring reportplan create a panel allowing the user to define variables for the test return a panel for user defined variables private j panel create variable panel args panel new arguments panel j meter utils get res string user defined variables color white return args panel jpanel createvariablepanel argspanel argumentspanel jmeterutils getresstring user_defined_variables argspanel private container create comment panel j panel panel new j panel panel set background color white panel set layout new border layout 10 10 container title make title panel comment panel new j text field comment panel set background color white j label label new j label j meter utils get res string testplan comments label set background color white label set label for comment panel title add label title add comment panel panel add title border layout north panel add base dir border layout center return panel createcommentpanel jpanel jpanel setbackground setlayout borderlayout maketitlepanel commentpanel jtextfield commentpanel setbackground jlabel jlabel jmeterutils getresstring testplan_comments setbackground setlabelfor commentpanel commentpanel borderlayout basedir borderlayout initialize the components and layout of this component private void init called from ctor so must not be overridable set layout new border layout 10 10 set border make border set background color white add create comment panel border layout north add create variable panel border layout center setlayout borderlayout setborder makeborder setbackground createcommentpanel borderlayout createvariablepanel borderlayout private static final logger log logging manager get logger for class private message admin loggingmanager getloggerforclass messageadmin public static synchronized message admin get admin return singleton messageadmin getadmin param request public void put request string id message request if log is debug enabled log debug req id id table put id new place holder request putrequest isdebugenabled req_id placeholder public void put reply string id message reply place holder holder place holder table get id if log is debug enabled log debug rpl id id for holder holder if holder null holder set reply reply object obj holder get request synchronized obj obj notify putreply placeholder placeholder isdebugenabled rpl_id setreply getrequest get the reply message param id the id of the message return the received message or code null code public message get string id place holder holder place holder table remove id if log is debug enabled log debug get id id for holder if holder has reply log info message with id not found return message holder get reply placeholder placeholder isdebugenabled get_id hasreply getreply private object reply place holder object original this request original placeholder void set reply object reply this reply reply setreply public object get reply return reply getreply public object get request return request getrequest boolean has reply return reply null hasreply public string to string return request request reply reply tostring iterator iter public property iterator impl collection value iter value iterator propertyiteratorimpl public property iterator impl propertyiteratorimpl public void set collection collection value iter value iterator setcollection public boolean has next return iter has next hasnext hasnext public j meter property next return j meter property iter next jmeterproperty jmeterproperty see org apache jmeter testelement property property iterator remove public void remove iter remove propertyiterator test data string f boolean exf boolean inf boolean exp boolean inp file f exclfile exf inclfile inf exclpatt exp inclpatt inp testdata new test data test index htm true false false true public void test construct new log filter testdata testconstruct logfilter private log filter testf public void set up testf new log filter logfilter setup logfilter public void test replace extension testf set replace extension html jsp testf is filtered teststr null set the required variables assert equals teststrout testf filter teststr testreplaceextension setreplaceextension isfiltered assertequals public void test exclude files testf exclude files incl for int idx 0 idx testdata length idx test data td testdata idx string the file td file boolean expect td exclfile testf is filtered the file null string line testf filter the file if line null assert true expect to accept the file expect else assert false expect to reject the file expect testexcludefiles excludefiles testdata thefile isfiltered thefile thefile asserttrue thefile assertfalse thefile public void test include files testf include files incl for int idx 0 idx testdata length idx test data td testdata idx string the file td file boolean expect td inclfile testf is filtered the file null string line testf filter the file if line null assert true expect to accept the file expect else assert false expect to reject the file expect testincludefiles includefiles testdata thefile isfiltered thefile thefile asserttrue thefile assertfalse thefile public void test exclude pattern testf exclude pattern patterns for int idx 0 idx testdata length idx test data td testdata idx string the file td file boolean expect td exclpatt assert equals expect testf is filtered the file null string line testf filter the file if line null assert true expect to accept the file expect else assert false expect to reject the file expect testexcludepattern excludepattern testdata thefile assertequals isfiltered thefile thefile asserttrue thefile assertfalse thefile public void test include pattern testf include pattern patterns for int idx 0 idx testdata length idx test data td testdata idx string the file td file boolean expect td inclpatt assert equals expect testf is filtered the file null string line testf filter the file if line null assert true expect to accept the file expect else assert false expect to reject the file expect testincludepattern includepattern testdata thefile assertequals isfiltered thefile thefile asserttrue thefile assertfalse thefile returns the result of the assertion here it checks wether the sample took to long to be considered successful if so an assertion result containing a failure message will be returned otherwise the returned assertion result will reflect the success of the sample public assertion result get result sample result response assertion result result new assertion result get name result set failure false long duration get allowed duration if duration 0 long response time response get time has the sample lasted too long if response time duration result set failure true object arguments new long response time new long duration string message message format format j meter utils get res string duration assertion failure non nls 1 arguments result set failure message message return result assertionresult failuremessage assertionresult assertionresult getresult sampleresult assertionresult assertionresult getname setfailure getallowedduration responsetime gettime responsetime setfailure responsetime messageformat jmeterutils getresstring duration_assertion_failure setfailuremessage returns the duration to be asserted a duration of 0 indicates this assertion is to be ignored private long get allowed duration return get property as long duration key getallowedduration getpropertyaslong duration_key private object values public un escape html unescapehtml public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception string escaped string compound variable values 0 execute return string escape utils unescape html escaped string sampleresult previousresult currentsampler invalidvariableexception escapedstring compoundvariable stringescapeutils unescapehtml escapedstring public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters 1 values parameters to array setparameters invalidvariableexception checkparametercount toarray public string get reference key return key getreferencekey public list get argument desc return desc getargumentdesc public focus requester component comp this comp comp try swing utilities invoke later this catch exception e log error e non nls 1 focusrequester swingutilities invokelater public void run comp request focus requestfocus constructor for the save object public save gets the action names attribute of the save object return the action names value public set get action names return commands actionnames actionnames getactionnames public void do action action event e throws illegal user action exception hash tree sub tree null if commands contains e get action command throw new illegal user action exception invalid user command e get action command if e get action command equals action names save as j meter tree node nodes gui package get instance get tree listener get selected nodes if nodes length 1 j meter utils report error to user j meter utils get res string save as error non nls 1 j meter utils get res string save as non nls 1 return sub tree gui package get instance get current sub tree else sub tree gui package get instance get tree model get test plan string update file gui package get instance get test plan file if action names save equals e get action command update file null j file chooser chooser file dialoger prompt to save file gui package get instance get tree listener get current node get name jmx file extension if chooser null return update file chooser get selected file get absolute path make sure the file ends with proper extension if filename utils get extension update file equals update file update file jmx file extension check if the user is trying to save to an existing file file f new file update file if f exists int response j option pane show confirm dialog gui package get instance get main frame j meter utils get res string save overwrite existing file non nls 1 j meter utils get res string save non nls 1 j option pane yes no option j option pane question message if response j option pane closed option response j option pane no option return do not save user does not want to overwrite if e get action command equals action names save as gui package get instance set test plan file update file todo doesn t putting this here mark the tree as saved even though a failure may occur later action router get instance do action now new action event sub tree e getid action names sub tree saved try convert sub tree sub tree catch exception err file output stream ostream null try ostream new file output stream update file if save service is save test plan format20 old save service save sub tree sub tree ostream else save service save tree sub tree ostream catch throwable ex gui package get instance set test plan file null log error ex throw new illegal user action exception couldn t save test plan to file update file finally j orphan utils close quietly ostream gui package get instance update current gui doaction actionevent illegaluseractionexception hashtree subtree getactioncommand illegaluseractionexception getactioncommand getactioncommand actionnames save_as jmetertreenode guipackage getinstance gettreelistener getselectednodes jmeterutils reporterrortouser jmeterutils getresstring save_as_error jmeterutils getresstring save_as subtree guipackage getinstance getcurrentsubtree subtree guipackage getinstance gettreemodel gettestplan updatefile guipackage getinstance gettestplanfile actionnames getactioncommand updatefile jfilechooser filedialoger prompttosavefile guipackage getinstance gettreelistener getcurrentnode getname jmx_file_extension updatefile getselectedfile getabsolutepath filenameutils getextension updatefile updatefile updatefile jmx_file_extension updatefile joptionpane showconfirmdialog guipackage getinstance getmainframe jmeterutils getresstring save_overwrite_existing_file jmeterutils getresstring joptionpane yes_no_option joptionpane question_message joptionpane closed_option joptionpane no_option getactioncommand actionnames save_as guipackage getinstance settestplanfile updatefile actionrouter getinstance doactionnow actionevent subtree actionnames sub_tree_saved convertsubtree subtree fileoutputstream fileoutputstream updatefile saveservice issavetestplanformat20 oldsaveservice savesubtree subtree saveservice savetree subtree guipackage getinstance settestplanfile illegaluseractionexception updatefile jorphanutils closequietly guipackage getinstance updatecurrentgui package protected to all for separate test code void convert sub tree hash tree tree iterator iter new linked list tree list iterator while iter has next j meter tree node item j meter tree node iter next convert sub tree tree get tree item test element test element item get test element tree replace item test element convertsubtree hashtree linkedlist hasnext jmetertreenode jmetertreenode convertsubtree gettree testelement testelement gettestelement testelement private static final file server fs file server get file server public test file server super fileserver fileserver getfileserver testfileserver public test file server string arg0 super arg0 testfileserver public void tear down throws io exception fs close files fs reset base teardown ioexception closefiles resetbase public void testopen throws exception try fs read line test fail expected io exception catch io exception ignored try fs write test fail expected io exception catch io exception ignored assert false should not have any files open fs files open fs close file xxx unrecognised files are ignored assert false should not have any files open fs files open string infile testfiles test csv fs reserve file infile does not open file assert false should not have any files open fs files open assert equals a1 b1 c1 d1 fs read line infile assert true should have some files open fs files open assert not null fs read line infile assert not null fs read line infile assert not null fs read line infile assert equals a1 b1 c1 d1 fs read line infile re read 1st line assert not null fs read line infile try fs write infile should not be able to write to it fail expected io exception catch io exception ignored fs close file infile does not remove the entry assert false should not have any files open fs files open assert equals a1 b1 c1 d1 fs read line infile re read 1st line assert true should have some files open fs files open fs close files removes all entries assert false should not have any files open fs files open try fs read line infile fail expected io exception catch io exception ignored string base fs get base dir infile base testfiles test csv fs reserve file infile does not open file assert false should not have any files open fs files open assert equals a1 b1 c1 d1 fs read line infile try fs set basedir x fail expected io exception catch io exception ignored fs close file infile fs set basedir y fs close files fs set basedir j meter utils get property user dir readline ioexception ioexception ioexception ioexception assertfalse filesopen closefile assertfalse filesopen reservefile assertfalse filesopen assertequals readline asserttrue filesopen assertnotnull readline assertnotnull readline assertnotnull readline assertequals readline assertnotnull readline ioexception ioexception closefile assertfalse filesopen assertequals readline asserttrue filesopen closefiles assertfalse filesopen readline ioexception ioexception getbasedir reservefile assertfalse filesopen assertequals readline setbasedir ioexception ioexception closefile setbasedir closefiles setbasedir jmeterutils getproperty constructor for the graph object public graph this set preferred size new dimension width 100 setpreferredsize constructor for the graph object public graph sampling stat calculator model this set model model samplingstatcalculator setmodel sets the model attribute of the graph object private void set model object model this model sampling stat calculator model repaint setmodel samplingstatcalculator gets the preferred scrollable viewport size attribute of the graph object return the preferred scrollable viewport size value public dimension get preferred scrollable viewport size return this get preferred size return new dimension width 400 preferredscrollableviewportsize preferredscrollableviewportsize getpreferredscrollableviewportsize getpreferredsize gets the scrollable unit increment attribute of the graph object return the scrollable unit increment value public int get scrollable unit increment rectangle visible rect int orientation int direction return 5 scrollableunitincrement scrollableunitincrement getscrollableunitincrement visiblerect gets the scrollable block increment attribute of the graph object return the scrollable block increment value public int get scrollable block increment rectangle visible rect int orientation int direction return int visible rect width 9 scrollableblockincrement scrollableblockincrement getscrollableblockincrement visiblerect visiblerect gets the scrollable tracks viewport width attribute of the graph object return the scrollable tracks viewport width value public boolean get scrollable tracks viewport width return false scrollabletracksviewportwidth scrollabletracksviewportwidth getscrollabletracksviewportwidth gets the scrollable tracks viewport height attribute of the graph object return the scrollable tracks viewport height value public boolean get scrollable tracks viewport height return true scrollabletracksviewportheight scrollabletracksviewportheight getscrollabletracksviewportheight clears this graph public void clear data graph max 1 throughput max 1 cleardata graphmax throughputmax public void enable data boolean value this want data value enabledata wantdata public void enable average boolean value this want average value enableaverage wantaverage public void enable median boolean value this want median value enablemedian wantmedian public void enable deviation boolean value this want deviation value enabledeviation wantdeviation public void enable throughput boolean value this want throughput value enablethroughput wantthroughput public void update gui final sample one sample long h model get percent point float 0 90 long value boolean repaint false if one sample get count 20 0 one sample get count 20 h graph max 1 2 graph max h 1 2 if h 1 graph max h else graph max 1 repaint true if model get max throughput throughput max throughput max model get max throughput 1 3 repaint true if repaint repaint return final int x pos model get count swing utilities invoke later new runnable public void run graphics g get graphics if g null draw sample x pos one sample g updategui onesample getpercentpoint longvalue onesample getcount onesample getcount graphmax graphmax graphmax graphmax getmaxthroughput throughputmax throughputmax getmaxthroughput xpos getcount swingutilities invokelater getgraphics drawsample xpos onesample swing utilities invoke later new runnable public void run graphics g get graphics if g null draw sample x pos one sample g swingutilities invokelater getgraphics drawsample xpos onesample public void paint component graphics g super paint component g list samples model get samples synchronized samples iterator e samples iterator for int i 0 e has next i sample s sample e next draw sample i s g paintcomponent paintcomponent getsamples hasnext drawsample private void draw sample int x sample one sample graphics g int width get width int height get height log debug drawing a sample at x if want data int data int one sample get data height graph max if one sample is success g set color color black else g set color j meter color yellow g draw line x width height data x width height data 1 log debug drawing coords x width height data if want average int average int one sample get average height graph max g set color color blue g draw line x width height average x width height average 1 if want median int median int one sample get median height graph max g set color j meter color purple g draw line x width height median x width height median 1 if want deviation int deviation int one sample get deviation height graph max g set color color red g draw line x width height deviation x width height deviation 1 if want throughput int throughput int one sample get throughput height throughput max g set color j meter color dark green g draw line x width height throughput x width height throughput 1 drawsample onesample getwidth getheight wantdata onesample getdata graphmax onesample issuccess setcolor setcolor jmetercolor drawline wantaverage onesample getaverage graphmax setcolor drawline wantmedian onesample getmedian graphmax setcolor jmetercolor drawline wantdeviation onesample getdeviation graphmax setcolor drawline wantthroughput onesample getthroughput throughputmax setcolor jmetercolor dark_green drawline return returns the graph max public long get graph max return graph max graphmax getgraphmax graphmax private static void set timeout method method url connection conn int timeout if method null log warn connect read timeout is not supported on this jvm return try method invoke conn new integer new integer timeout catch illegal argument exception e1 log warn failed to set timeout e1 catch illegal access exception e1 log warn failed to set timeout e1 catch invocation target exception e1 log warn failed to set timeout e1 settimeout urlconnection illegalargumentexception illegalaccessexception invocationtargetexception constructor for the http sampler object consider using http sampler factory new instance instead public http sampler httpsampler httpsamplerfactory newinstance httpsampler set request headers in preparation to opening a connection param conn code url connection code to set headers on exception io exception if an i o exception occurs protected void set post headers url connection conn throws io exception post or put writer new post writer post or put writer set headers conn this urlconnection ioexception setpostheaders urlconnection ioexception postorputwriter postwriter postorputwriter setheaders private void set put headers url connection conn throws io exception post or put writer new put writer post or put writer set headers conn this setputheaders urlconnection ioexception postorputwriter putwriter postorputwriter setheaders send post data from code entry code to the open connection this also handles sending data for put requests param connection code url connection code where post data should be sent return a string show what was posted will not contain actual file upload content exception io exception if an i o exception occurs protected string send post data url connection connection throws io exception return post or put writer send post data connection this urlconnection ioexception sendpostdata urlconnection ioexception postorputwriter sendpostdata private string send put data url connection connection throws io exception return post or put writer send post data connection this sendputdata urlconnection ioexception postorputwriter sendpostdata returns an code httpurl connection code fully ready to attempt connection this means it sets the request method get or post headers cookies and authorization for the url request p the request infos are saved into the sample result if one is provided param u code url code of the url request param method get post etc param res sample result to save request infos to return code httpurl connection code ready for connect exception io exception if an i o exception occurs protected httpurl connection setup connection url u string method http sample result res throws io exception ssl manager sslmgr null if protocol https equals ignore case u get protocol try sslmgr ssl manager get instance n b this needs to be done before opening the connection catch exception e log warn problem creating the ssl manager e httpurl connection conn httpurl connection u open connection update follow redirects setting just for this connection conn set instance follow redirects get auto redirects int cto get connect timeout if cto 0 set timeout set connect timeout conn cto int rto get response timeout if rto 0 set timeout set read timeout conn rto if protocol https equals ignore case u get protocol try if null sslmgr sslmgr set context conn n b must be done after opening connection catch exception e log warn problem setting the ssl manager for the connection e a well bahaved browser is supposed to send connection close with the last request to an http server instead most browsers leave it to the server to close the connection after their timeout period leave it to the j meter user to decide if get use keep alive conn set request property header connection keep alive else conn set request property header connection connection close conn set request method method set connection headers conn u get header manager get cache manager string cookies set connection cookie conn u get cookie manager set connection authorization conn u get auth manager if method equals post set post headers conn else if method equals put set put headers conn if res null res seturl u res sethttp method method res set request headers get connection headers conn res set cookies cookies return conn httpurlconnection httpurlconnection ioexception httpurlconnection setupconnection httpsampleresult ioexception sslmanager protocol_https equalsignorecase getprotocol sslmanager getinstance sslmanager httpurlconnection httpurlconnection openconnection setinstancefollowredirects getautoredirects getconnecttimeout settimeout setconnecttimeout getresponsetimeout settimeout setreadtimeout protocol_https equalsignorecase getprotocol setcontext sslmanager jmeter getusekeepalive setrequestproperty header_connection keep_alive setrequestproperty header_connection connection_close setrequestmethod setconnectionheaders getheadermanager getcachemanager setconnectioncookie getcookiemanager setconnectionauthorization getauthmanager setpostheaders setputheaders sethttpmethod setrequestheaders getconnectionheaders setcookies reads the response from the url connection param conn url from which to read response return response content exception io exception if an i o exception occurs protected byte read response httpurl connection conn sample result res throws io exception buffered input stream in final int content length conn get content length if content length 0 j meter utils get prop default httpsampler obey contentlength non nls 1 false log info content length 0 not reading http body res set response headers get response headers conn return null ba works ok even if content encoding is null boolean gzipped encoding gzip equals conn get content encoding try if gzipped in new buffered input stream new gzip input stream conn get input stream else in new buffered input stream conn get input stream catch io exception e if e get cause instanceof file not found exception log error read response e to string throwable cause e get cause if cause null log error cause cause normal input stream is not available input stream error stream conn get error stream if error stream null log info error response code conn get response code server sent no errorpage res set response headers get response headers conn return null ba log info error response code conn get response code if gzipped in new buffered input stream new gzip input stream error stream else in new buffered input stream error stream catch exception e log error read response e to string throwable cause e get cause if cause null log error cause cause in new buffered input stream conn get error stream return read response res in content length ioexception readresponse httpurlconnection sampleresult ioexception bufferedinputstream contentlength getcontentlength contentlength jmeterutils getpropdefault obey_contentlength setresponseheaders getresponseheaders null_ba contentencoding encoding_gzip getcontentencoding bufferedinputstream gzipinputstream getinputstream bufferedinputstream getinputstream ioexception getcause filenotfoundexception readresponse tostring getcause inputstream inputstream errorstream geterrorstream errorstream getresponsecode setresponseheaders getresponseheaders null_ba getresponsecode bufferedinputstream gzipinputstream errorstream bufferedinputstream errorstream readresponse tostring getcause bufferedinputstream geterrorstream readresponse contentlength gets the response headers from the url connection param conn connection from which the headers are read return string containing the headers one per line protected string get response headers httpurl connection conn string buffer header buf new string buffer header buf append conn get header field 0 leave header as is header buf append conn get header field 0 substring 0 8 header buf append header buf append conn get response code header buf append header buf append conn get response message header buf append n non nls 1 string hfk for int i 1 hfk conn get header field key i null i header buf append hfk header buf append non nls 1 header buf append conn get header field i header buf append n non nls 1 return header buf to string responseheaders urlconnection getresponseheaders httpurlconnection stringbuffer headerbuf stringbuffer headerbuf getheaderfield headerbuf getheaderfield headerbuf headerbuf getresponsecode headerbuf headerbuf getresponsemessage headerbuf getheaderfieldkey headerbuf headerbuf headerbuf getheaderfield headerbuf headerbuf tostring extracts all the required cookies for that particular url request and sets them in the code httpurl connection code passed in param conn code http url connection code which represents the url request param u code url code of the url request param cookie manager the code cookie manager code containing all the cookies for this code url config code private string set connection cookie httpurl connection conn url u cookie manager cookie manager string cookie header null if cookie manager null cookie header cookie manager get cookie header forurl u if cookie header null conn set request property header cookie cookie header return cookie header httpurlconnection httpurlconnection cookiemanager cookiemanager urlconfig setconnectioncookie httpurlconnection cookiemanager cookiemanager cookieheader cookiemanager cookieheader cookiemanager getcookieheaderforurl cookieheader setrequestproperty header_cookie cookieheader cookieheader extracts all the required headers for that particular url request and sets them in the code httpurl connection code passed in param conn code http url connection code which represents the url request param u code url code of the url request param header manager the code header manager code containing all the cookies for this code url config code param cache manager the cache manager may be null private void set connection headers httpurl connection conn url u header manager header manager cache manager cache manager add all the headers from the header manager if header manager null collection property headers header manager get headers if headers null property iterator i headers iterator while i has next header header header i next get object value string n header get name string v header get value conn add request property n v if cache manager null cache manager set headers conn u httpurlconnection httpurlconnection headermanager headermanager urlconfig cachemanager cachemanager setconnectionheaders httpurlconnection headermanager headermanager cachemanager cachemanager headermanager headermanager collectionproperty headermanager getheaders propertyiterator hasnext getobjectvalue getname getvalue addrequestproperty cachemanager cachemanager setheaders get all the headers for the code httpurl connection code passed in param conn code http url connection code which represents the url request return the headers as a string private string get connection headers httpurl connection conn get all the request properties which are the headers set on the connection string buffer hdrs new string buffer 100 map request headers conn get request properties set header fields request headers entry set for iterator i header fields iterator i has next map entry entry map entry i next string header key string entry get key exclude the cookie header since cookie is reported separately in the sample if header cookie equals ignore case header key list values list entry get value value is a list of strings for int j 0 j values size j hdrs append header key hdrs append non nls 1 hdrs append string values get j hdrs append n non nls 1 return hdrs to string httpurlconnection httpurlconnection getconnectionheaders httpurlconnection stringbuffer stringbuffer requestheaders getrequestproperties headerfields requestheaders entryset headerfields hasnext headerkey getkey header_cookie equalsignorecase headerkey getvalue headerkey tostring extracts all the required authorization for that particular url request and sets it in the code httpurl connection code passed in param conn code http url connection code which represents the url request param u code url code of the url request param auth manager the code auth manager code containing all the cookies for this code url config code private void set connection authorization httpurl connection conn url u auth manager auth manager if auth manager null authorization auth auth manager get auth forurl u if auth null conn set request property header authorization auth to basic header httpurlconnection httpurlconnection authmanager authmanager urlconfig setconnectionauthorization httpurlconnection authmanager authmanager authmanager authmanager getauthforurl setrequestproperty header_authorization tobasicheader samples the url passed in and stores the result in code http sample result code following redirects and downloading page resources as appropriate p when getting a redirect target redirects are not followed and resources are not downloaded the caller will take care of this param url url to sample param method http method get post param are following redirect whether we re getting a redirect target param frame depth depth of this target in the frame structure used only to prevent infinite recursion return results of the sampling protected http sample result sample url url string method boolean are following redirect int frame depth httpurl connection conn null string url str url to string log debug start sample url str http sample result res new http sample result res set monitor is monitor res set sample label url str res sample start count the retries as well in the time try sampling proper establish the connection and read the response repeatedly try to connect int retry start with 0 so tries at least once and retries at most max conn retries times for retry 0 retry max conn retries retry try conn setup connection url method res attempt the connection saved conn conn conn connect break catch bind exception e if retry max conn retries log error can t connect after retry retries e throw e log debug bind exception try again if conn null conn disconnect this set use keep alive false continue try again catch io exception e log debug connection failed giving up throw e if retry max conn retries this should never happen but throw new bind exception nice we ve got a connection finish sending the request if method equals post string post body send post data conn res set query string post body else if method equals put string put body send put data conn res set query string put body request sent now get the response byte response data read response conn res res sample end done with the sampling proper now collect the results into the http sample result res set response data response data int error level conn get response code string resp msg conn get response message string hdr conn get header field 0 if hdr null hdr null non nls 1 if error level 1 bug 38902 sometimes 1 seems to be returned unnecessarily if resp msg null bug 41902 npe try error level integer parse int resp msg substring 0 3 log warn response code 1 parsed resp msg as error level catch number format exception e log warn response code 1 could not parse resp msg hdr hdr else resp msg hdr for result log warn response code 1 null response message header 0 hdr if error level 1 res set response code null non nls 1 else res set response code integer to string error level res set successful is success code error level if resp msg null has been seen in a redirect resp msg hdr use header if possible if no message found res set response message resp msg string ct conn get content type if ct null res set content type ct e g text html charset iso 8859 1 res set encoding and type ct res set response headers get response headers conn if res is redirect res set redirect location conn get header field header location if we redirected automatically the url may have changed if get auto redirects res seturl conn geturl store any cookies received in the cookie manager save connection cookies conn url get cookie manager save cache information final cache manager cache manager get cache manager if cache manager null cache manager save details conn res res result processing are following redirect frame depth res log debug end sample return res catch io exception e res sample end we don t want to continue using this connection even if keep alive is set if conn null may not exist conn disconnect conn null don t process again return error result e res finally calling disconnect doesn t close the connection immediately but indicates we re through with it the jvm should close it when necessary disconnect conn disconnect unless using keep alive saved conn null httpsampleresult arefollowingredirect framedepth httpsampleresult arefollowingredirect framedepth httpurlconnection urlstr tostring urlstr httpsampleresult httpsampleresult setmonitor ismonitor setsamplelabel urlstr samplestart max_conn_retries max_conn_retries setupconnection savedconn bindexception max_conn_retries setusekeepalive ioexception max_conn_retries bindexception postbody sendpostdata setquerystring postbody putbody sendputdata setquerystring putbody responsedata readresponse sampleend httpsampleresult setresponsedata responsedata errorlevel getresponsecode respmsg getresponsemessage getheaderfield errorlevel respmsg errorlevel parseint respmsg responsecode respmsg errorlevel numberformatexception responsecode respmsg respmsg responsecode responsemessage errorlevel setresponsecode setresponsecode tostring errorlevel setsuccessful issuccesscode errorlevel respmsg respmsg setresponsemessage respmsg getcontenttype setcontenttype setencodingandtype setresponseheaders getresponseheaders isredirect setredirectlocation getheaderfield header_location getautoredirects saveconnectioncookies getcookiemanager cachemanager cachemanager getcachemanager cachemanager cachemanager savedetails resultprocessing arefollowingredirect framedepth ioexception sampleend keepalive errorresult keepalive savedconn protected void disconnect httpurl connection conn if conn null string connection conn get header field header connection string protocol conn get header field 0 if connection null protocol null protocol starts with http 1 1 connection null connection equals ignore case connection close conn disconnect todo perhaps note connection so it can be disconnected at end of test httpurlconnection getheaderfield header_connection getheaderfield startswith http_1_1 equalsignorecase connection_close from the code httpurl connection code store all the set cookie key pair values in the cookie manager of the code url config code param conn code http url connection code which represents the url request param u code url code of the url request param cookie manager the code cookie manager code containing all the cookies for this code url config code private void save connection cookies httpurl connection conn url u cookie manager cookie manager if cookie manager null for int i 1 conn get header field key i null i if conn get header field key i equals ignore case header set cookie cookie manager add cookie from header conn get header field i u httpurlconnection cookiemanager urlconfig httpurlconnection cookiemanager cookiemanager urlconfig saveconnectioncookies httpurlconnection cookiemanager cookiemanager cookiemanager getheaderfieldkey getheaderfieldkey equalsignorecase header_set_cookie cookiemanager addcookiefromheader getheaderfield inherit doc public boolean interrupt httpurl connection conn saved conn if conn null saved conn null conn disconnect return conn null inheritdoc httpurlconnection savedconn savedconn initializes the gui panel for the module controller instance public include controller gui init modulecontroller includecontrollergui public string get label resource return include controller non nls 1 getlabelresource include_controller public void configure test element el super configure el include controller controller include controller el this include panel set filename controller get include path testelement includecontroller includecontroller includepanel setfilename getincludepath public test element create test element include controller mc new include controller configure test element mc return mc testelement createtestelement includecontroller includecontroller configuretestelement public void modify test element test element element configure test element element include controller controller include controller element controller set include path this include panel get filename modifytestelement testelement configuretestelement includecontroller includecontroller setincludepath includepanel getfilename implements j metergui component clear gui public void clear gui super clear gui include panel clear gui jmeterguicomponent cleargui cleargui cleargui includepanel cleargui public j popup menu create popup menu j popup menu menu new j popup menu j menu add menu menu factory make menus new string menu factory config elements menu factory assertions menu factory timers menu factory listeners j meter utils get res string add non nls 1 action names add menu add add menu menu factory add edit menu menu true menu factory add file menu menu return menu jpopupmenu createpopupmenu jpopupmenu jpopupmenu jmenu addmenu menufactory makemenus menufactory config_elements menufactory menufactory menufactory jmeterutils getresstring actionnames addmenu menufactory addeditmenu menufactory addfilemenu private void init set layout new vertical layout 5 vertical layout both vertical layout top set border make border add make title panel add include panel setlayout verticallayout verticallayout verticallayout setborder makeborder maketitlepanel includepanel private long batch send time 1 public statistical sample sender log warn constructor only intended for use in testing batchsendtime statisticalsamplesender constructor param listener that the list of sample events will be sent to statistical sample sender remote sample listener listener this listener listener init log info using batching for this run thresholds num num samples threshold time time threshold statisticalsamplesender remotesamplelistener numsamplesthreshold timethreshold checks for the jmeter properties num sample threshold and time threshold and assigns defaults if not found private void init this num samples threshold j meter utils get prop default num sample threshold default num sample threshold this time threshold j meter utils get prop default time threshold default time threshold num_sample_threshold time_threshold numsamplesthreshold jmeterutils getpropdefault num_sample_threshold default_num_sample_threshold timethreshold jmeterutils getpropdefault time_threshold default_time_threshold checks if any sample events are still present in the sample store and sends them to the listener informs the listener of the testended public void test ended try if sample store size 0 send batch listener test ended catch remote exception err log warn test ended err samplestore testended samplestore sendbatch testended remoteexception testended checks if any sample events are still present in the sample store and sends them to the listener informs the listener of the testended param host the hostname that the test has ended on public void test ended string host try if sample store size 0 send batch listener test ended host catch remote exception err log warn test ended hostname err samplestore testended samplestore sendbatch testended remoteexception testended stores sample events untill either a time or sample threshold is breached both thresholds are reset if one fires if only one threshold is set it becomes the only value checked against when a threhold is breached the list of sample events is sent to a listener where the event are fired locally param e a sample event public void sample occurred sample event e synchronized sample store locate the statistical sample colector string key statistical sample result get key e statistical sample result stat result statistical sample result sample table get key if stat result null stat result new statistical sample result e get result store the new statistical result collector sample table put key stat result add a new wrapper samplevent sample store add new sample event stat result e get thread group stat result add e get result sample count if num samples threshold 1 if sample count num samples threshold try if log is debug enabled log debug firing sample send batch catch remote exception err log warn sample occurred err if time threshold 1 long now system current time millis checking for and creating initial timestamp to cheak against if batch send time 1 this batch send time now time threshold if batch send time now try if log is debug enabled log debug firing time send batch this batch send time now time threshold catch remote exception err log warn sample occurred err sampleoccurred sampleevent samplestore statisticalsampleresult getkey statisticalsampleresult statresult statisticalsampleresult sampletable statresult statresult statisticalsampleresult getresult sampletable statresult samplestore sampleevent statresult getthreadgroup statresult getresult samplecount numsamplesthreshold samplecount numsamplesthreshold isdebugenabled sendbatch remoteexception sampleoccurred timethreshold currenttimemillis batchsendtime batchsendtime timethreshold batchsendtime isdebugenabled sendbatch batchsendtime timethreshold remoteexception sampleoccurred private void send batch throws remote exception if sample store size 0 listener process batch sample store sample store clear sample table clear sample count 0 sendbatch remoteexception samplestore processbatch samplestore samplestore sampletable samplecount convert the given value object to an object of the given type param value param to type return object public static object convert object value class to type if value null value else if to type is assignable from value get class return value else if to type equals float class to type equals float class return new float get float value else if to type equals double class to type equals double class return new double get double value else if to type equals string class return get string value else if to type equals int class to type equals integer class return new integer get int value else if to type equals char class to type equals character class return new character get char value else if to type equals long class to type equals long class return new long get long value else if to type equals boolean class to type equals boolean class return boolean value of get boolean value else if to type equals java util date class return get date value else if to type equals calendar class return get calendar value else if to type equals class class try return class for name value to string catch exception e don t do anything return value totype totype totype isassignablefrom getclass totype totype getfloat totype totype getdouble totype getstring totype totype getint totype totype getchar totype totype getlong totype totype valueof getboolean totype getdate totype getcalendar totype forname tostring converts the given object to a calendar object defaults to the current date if the given object can t be converted param date return calendar public static calendar get calendar object date calendar default value calendar cal new gregorian calendar if date null date instanceof java util date cal set time java util date date return cal else if date null date format formatter date format get date instance date format short java util date d null try d formatter parse date to string catch parse exception e formatter date format get date instance date format medium try d formatter parse string date catch parse exception e1 formatter date format get date instance date format long try d formatter parse string date catch parse exception e2 formatter date format get date instance date format full try d formatter parse string date catch parse exception e3 return default value cal set time d else cal default value return cal getcalendar defaultvalue gregoriancalendar settime dateformat dateformat getdateinstance dateformat tostring parseexception dateformat getdateinstance dateformat parseexception dateformat getdateinstance dateformat parseexception dateformat getdateinstance dateformat parseexception defaultvalue settime defaultvalue public static calendar get calendar object o return get calendar o new gregorian calendar getcalendar getcalendar gregoriancalendar public static date get date object date return get date date calendar get instance get time getdate getdate getinstance gettime public static string url encode object to encode return url encoder encode get string to encode urlencode toencode urlencoder getstring toencode public static date get date object date date default value date val null if date null date instanceof java util date return date date else if date null date format formatter date format get date instance date format short java util date d null try val formatter parse date to string catch parse exception e formatter date format get date instance date format medium try val formatter parse string date catch parse exception e1 formatter date format get date instance date format long try val formatter parse string date catch parse exception e2 formatter date format get date instance date format full try val formatter parse string date catch parse exception e3 return default value else return default value return val getdate defaultvalue dateformat dateformat getdateinstance dateformat tostring parseexception dateformat getdateinstance dateformat parseexception dateformat getdateinstance dateformat parseexception dateformat getdateinstance dateformat parseexception defaultvalue defaultvalue public string format number float num string pattern number format format new decimal format pattern return format format num formatnumber numberformat decimalformat public static float get float object o float default value try if o null return default value if o instanceof number return number o float value return float parse float o to string catch number format exception e return default value getfloat defaultvalue defaultvalue floatvalue parsefloat tostring numberformatexception defaultvalue public static float get float object o return get float o 0 getfloat getfloat public static double get double object o double default value try if o null return default value if o instanceof number return number o double value return double parse double o to string catch number format exception e return default value getdouble defaultvalue defaultvalue doublevalue parsedouble tostring numberformatexception defaultvalue public static double get double object o return get double o 0 getdouble getdouble public static boolean get boolean object o return get boolean o false getboolean getboolean public static boolean get boolean object o boolean default value if o null return default value else if o instanceof boolean return boolean o boolean value return boolean value of o to string boolean value getboolean defaultvalue defaultvalue booleanvalue valueof tostring booleanvalue convert object to integer return default value if object is not convertible or is null param o param default value return int public static int get int object o int default value try if o null return default value if o instanceof number return number o int value return integer parse int o to string catch number format exception e return default value defaultvalue defaultvalue getint defaultvalue defaultvalue intvalue parseint tostring numberformatexception defaultvalue public static char get char object o return get char o getchar getchar public static char get char object o char default value try if o null return default value if o instanceof character return character o char value else if o instanceof byte return char byte o byte value else if o instanceof integer return char integer o int value else string s o to string if s length 0 return o to string char at 0 return default value catch exception e return default value getchar defaultvalue defaultvalue charvalue bytevalue intvalue tostring tostring charat defaultvalue defaultvalue converts object to an integer defaults to 0 if object is not convertible or is null param o return int public static int get int object o return get int o 0 getint getint converts object to a long return default value if object is not convertible or is null param o param default value return long public static long get long object o long default value try if o null return default value if o instanceof number return number o long value return long parse long o to string catch number format exception e return default value defaultvalue defaultvalue getlong defaultvalue defaultvalue longvalue parselong tostring numberformatexception defaultvalue converts object to a long defaults to 0 if object is not convertible or is null param o return long public static long get long object o return get long o 0 getlong getlong public static string format date date date string pattern if date null return simple date format format new simple date format pattern return format format date formatdate simpledateformat simpledateformat public static string format date java sql date date string pattern if date null return simple date format format new simple date format pattern return format format date formatdate simpledateformat simpledateformat public static string format date string date string pattern return format date get calendar date null pattern formatdate formatdate getcalendar public static string format date calendar date string pattern return format calendar date pattern formatdate formatcalendar public static string format calendar calendar date string pattern if date null return simple date format format new simple date format pattern return format format date get time formatcalendar simpledateformat simpledateformat gettime converts object to a string return default value if object is null param o param default value return string public static string get string object o string default value if o null return default value return o to string defaultvalue defaultvalue getstring defaultvalue defaultvalue tostring public static string insert line breaks string v string insertion if v null return string buffer replacement new string buffer string tokenizer tokens new string tokenizer v n true while tokens has more tokens string token tokens next token if token compare to n 0 replacement append insertion else replacement append token return replacement to string insertlinebreaks stringbuffer stringbuffer stringtokenizer stringtokenizer hasmoretokens nexttoken compareto tostring converts object to a string defaults to empty string if object is null param o return string public static string get string object o return get string o getstring getstring public jdbc sampler bean info super jdbc sampler class create property group var name non nls 1 new string data source non nls 1 create property group sql non nls 1 new string query type non nls 1 query non nls 1 query arguments non nls 1 query arguments types non nls 1 variable names non nls 1 property descriptor p property data source non nls 1 p set value not undefined boolean true p set value default p property query arguments non nls 1 p set value not undefined boolean true p set value default p property query arguments types non nls 1 p set value not undefined boolean true p set value default p property variable names non nls 1 p set value not undefined boolean true p set value default p property query type non nls 1 p set value not undefined boolean true p set value default jdbc sampler select p set value not other boolean true p set value tags new string jdbc sampler select jdbc sampler update jdbc sampler callable jdbc sampler prepared select jdbc sampler prepared update jdbc sampler commit jdbc sampler rollback jdbc sampler autocommit false jdbc sampler autocommit true p property query non nls 1 p set value not undefined boolean true p set value default p set property editor class text area editor class jdbcsamplerbeaninfo jdbcsampler createpropertygroup varname datasource createpropertygroup querytype queryarguments queryargumentstypes variablenames propertydescriptor datasource setvalue not_undefined setvalue queryarguments setvalue not_undefined setvalue queryargumentstypes setvalue not_undefined setvalue variablenames setvalue not_undefined setvalue querytype setvalue not_undefined setvalue jdbcsampler setvalue not_other setvalue jdbcsampler jdbcsampler jdbcsampler jdbcsampler prepared_select jdbcsampler prepared_update jdbcsampler jdbcsampler jdbcsampler autocommit_false jdbcsampler autocommit_true setvalue not_undefined setvalue setpropertyeditorclass textareaeditor private ftp config gui ftp default panel public ftp test sampler gui init ftpconfiggui ftpdefaultpanel ftptestsamplergui public void configure test element element super configure element login panel configure element ftp default panel configure element testelement loginpanel ftpdefaultpanel public test element create test element ftp sampler sampler new ftp sampler modify test element sampler return sampler testelement createtestelement ftpsampler ftpsampler modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element sampler sampler clear ftp default panel modify test element sampler login panel modify test element sampler this configure test element sampler testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement ftpdefaultpanel modifytestelement loginpanel modifytestelement configuretestelement implements j metergui component clear gui public void clear gui super clear gui ftp default panel clear gui login panel clear gui jmeterguicomponent cleargui cleargui cleargui ftpdefaultpanel cleargui loginpanel cleargui public string get label resource return ftp testing title non nls 1 getlabelresource ftp_testing_title private void init set layout new border layout 0 5 set border make border add make title panel border layout north vertical panel main panel new vertical panel ftp default panel new ftp config gui false main panel add ftp default panel login panel new login config gui false login panel set border border factory create titled border j meter utils get res string login config non nls 1 main panel add login panel add main panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout verticalpanel mainpanel verticalpanel ftpdefaultpanel ftpconfiggui mainpanel ftpdefaultpanel loginpanel loginconfiggui loginpanel setborder borderfactory createtitledborder jmeterutils getresstring login_config mainpanel loginpanel mainpanel borderlayout private url config gui url config public http defaults gui super init urlconfiggui urlconfig httpdefaultsgui public string get label resource return url config title non nls 1 getlabelresource url_config_title see org apache jmeter gui j metergui component create test element public test element create test element config test element config new config test element modify test element config return config jmeterguicomponent createtestelement testelement createtestelement configtestelement configtestelement modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element config config test element cfg config test element config config test element el config test element url config create test element cfg clear need to clear because the cfg add config element el super configure test element config if image parser is selected config set property new boolean property http sampler base image parser true else config remove property http sampler base image parser testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configtestelement configtestelement configtestelement configtestelement urlconfig createtestelement addconfigelement configuretestelement imageparser isselected setproperty booleanproperty httpsamplerbase image_parser removeproperty httpsamplerbase image_parser implements j metergui component clear gui public void clear gui super clear gui url config clear image parser set selected false jmeterguicomponent cleargui cleargui cleargui urlconfig imageparser setselected public void configure test element el super configure el url config configure el image parser set selected abstract test element el get property as boolean http sampler base image parser testelement urlconfig imageparser setselected abstracttestelement getpropertyasboolean httpsamplerbase image_parser private void init set layout new border layout 0 5 set border make border add make title panel border layout north url config new url config gui false add url config border layout center image parser new j check box j meter utils get res string web testing retrieve images non nls 1 add image parser border layout south setlayout borderlayout setborder makeborder maketitlepanel borderlayout urlconfig urlconfiggui urlconfig borderlayout imageparser jcheckbox jmeterutils getresstring web_testing_retrieve_images imageparser borderlayout public dimension get preferred size return get minimum size getpreferredsize getminimumsize public static string get current name string class name if name map contains key class name string new name name map get property class name log info upgrading class class name to new name return new name return class name getcurrentname classname namemap containskey classname newname namemap getproperty classname classname newname newname classname looks up test element gui class combination if that does not exist in the map then defaults to get current name param test class name test element class name param gui class name associated gui class name return new test class name public static string get current test name string test class name string gui class name string key test class name gui class name if name map contains key key string new name name map get property key log info upgrading key to new name return new name return get current name test class name getcurrentname testclassname guiclassname getcurrenttestname testclassname guiclassname testclassname guiclassname namemap containskey newname namemap getproperty newname newname getcurrentname testclassname public static string get current name string property name string class name string key class name property name if name map contains key key string new name name map get property key log info upgrading property property name to new name return new name return property name getcurrentname propertyname classname classname propertyname namemap containskey newname namemap getproperty propertyname newname newname propertyname public static string get current name string value string property name string class name string key class name property name value if name map contains key key string new value name map get property key log info upgrading value value to new value return new value return value getcurrentname propertyname classname classname propertyname namemap containskey newvalue namemap getproperty newvalue newvalue private constructor to prevent instantiation private name updater nameupdater map variables new hash map public value replacer hashmap valuereplacer public value replacer report plan tp set user defined variables tp get user defined variables valuereplacer reportplan setuserdefinedvariables getuserdefinedvariables public void set user defined variables map variables this variables variables setuserdefinedvariables throws invalid variable exception not thrown currently public void replace values test element el throws invalid variable exception collection new props replace values el property iterator new replace string with functions master function variables set properties el new props invalidvariableexception replacevalues testelement invalidvariableexception newprops replacevalues propertyiterator replacestringwithfunctions masterfunction setproperties newprops throws invalid variable exception not thrown currently public void reverse replace test element el throws invalid variable exception collection new props replace values el property iterator new replace functions with strings master function variables set properties el new props invalidvariableexception reversereplace testelement invalidvariableexception newprops replacevalues propertyiterator replacefunctionswithstrings masterfunction setproperties newprops throws invalid variable exception not thrown currently public void reverse replace test element el boolean regex match throws invalid variable exception collection new props replace values el property iterator new replace functions with strings master function variables regex match set properties el new props invalidvariableexception reversereplace testelement regexmatch invalidvariableexception newprops replacevalues propertyiterator replacefunctionswithstrings masterfunction regexmatch setproperties newprops throws invalid variable exception not thrown currently public void undo reverse replace test element el throws invalid variable exception collection new props replace values el property iterator new undo variable replacement master function variables set properties el new props invalidvariableexception undoreversereplace testelement invalidvariableexception newprops replacevalues propertyiterator undovariablereplacement masterfunction setproperties newprops public void add variable string name string value variables put name value addvariable add all the given variables to this replacer s variables map param vars a map of variable name value pairs string to string public void add variables map vars variables put all vars addvariables putall public abstract class number property extends abstract property public number property super numberproperty abstractproperty numberproperty public number property string name super name numberproperty set the value of the property with a number object protected abstract void set number value number n setnumbervalue protected abstract void set number value number n set the value of the property with a string object protected abstract void set number value string n throws number format exception setnumbervalue setnumbervalue numberformatexception public void set object value object v if v instanceof number set number value number v else try set number value v to string catch runtime exception e setobjectvalue setnumbervalue setnumbervalue tostring runtimeexception see comparable compare to object public int compare to object arg0 if arg0 instanceof j meter property double compare value get double value j meter property arg0 get double value if compare value 0 return 1 else if compare value 0 return 0 else return 1 else return 1 compareto compareto jmeterproperty comparevalue getdoublevalue jmeterproperty getdoublevalue comparevalue comparevalue public class debug post processor bean info extends bean info support public debug post processor bean info super debug post processor class debugpostprocessorbeaninfo beaninfosupport debugpostprocessorbeaninfo debugpostprocessor public report menu bar remote engine start new linked list remote engine stop new linked list remote engine exit new linked list remote hosts j orphan utils split j meter utils get prop default remote hosts if remote hosts length 1 remote hosts 0 equals remote hosts new string 0 this get remote items create menu bar reportmenubar remote_engine_start linkedlist remote_engine_stop linkedlist remote_engine_exit linkedlist remotehosts jorphanutils jmeterutils getpropdefault remote_hosts remotehosts remotehosts remotehosts getremoteitems createmenubar public void set file save enabled boolean enabled file save as set enabled enabled setfilesaveenabled file_save_as setenabled public void set file load enabled boolean enabled if file load null file load set enabled enabled if file merge null file merge set enabled enabled setfileloadenabled file_load file_load setenabled file_merge file_merge setenabled public void set edit enabled boolean enabled if edit menu null edit menu set enabled enabled seteditenabled editmenu editmenu setenabled public void set edit add menu j menu menu if the add menu already exists remove it if edit add null edit menu remove edit add insert the add menu as the first menu item in the edit menu edit add menu edit menu insert edit add 0 seteditaddmenu jmenu edit_add editmenu edit_add edit_add editmenu edit_add public void set edit menu j popup menu menu if menu null edit menu remove all component comps menu get components for int i 0 i comps length i edit menu add comps i edit menu set enabled true else edit menu set enabled false seteditmenu jpopupmenu editmenu removeall getcomponents editmenu editmenu setenabled editmenu setenabled public void set edit add enabled boolean enabled there was a npe being thrown without the null check here jkb if edit add null edit add set enabled enabled if we are enabling the edit add menu item then we also need to enable the edit menu the edit menu may already be enabled but there s no harm it trying to enable it again if enabled set edit enabled true else if we are disabling the edit add menu item and the edit remove menu item is disabled then we also need to disable the edit menu the java look and feel guidelines say to disable a menu if all menu items are disabled if edit remove is enabled edit menu set enabled false seteditaddenabled edit_add edit_add setenabled seteditenabled edit_remove isenabled editmenu setenabled public void set edit remove enabled boolean enabled edit remove set enabled enabled if we are enabling the edit remove menu item then we also need to enable the edit menu the edit menu may already be enabled but there s no harm it trying to enable it again if enabled set edit enabled true else if we are disabling the edit remove menu item and the edit add menu item is disabled then we also need to disable the edit menu the java look and feel guidelines say to disable a menu if all menu items are disabled if edit add is enabled edit menu set enabled false seteditremoveenabled edit_remove setenabled seteditenabled edit_add isenabled editmenu setenabled creates the menu bar for this application i believe in my heart that this should be defined in a file somewhere but that is for later public void create menu bar make file menu make edit menu make run menu make options menu make help menu this add file menu this add edit menu this add run menu this add options menu this add help menu menubar createmenubar makefilemenu makeeditmenu makerunmenu makeoptionsmenu makehelpmenu filemenu editmenu runmenu optionsmenu helpmenu private void make help menu help menu help menu new j menu j meter utils get res string help help menu set mnemonic h j menu item context help new j menu item j meter utils get res string help h context help set action command help context help set accelerator key strokes help context help add action listener report action router get instance help about new j menu item j meter utils get res string about a help about set action command about help about add action listener report action router get instance help menu add context help help menu add help about makehelpmenu helpmenu jmenu jmeterutils getresstring helpmenu setmnemonic jmenuitem contexthelp jmenuitem jmeterutils getresstring contexthelp setactioncommand contexthelp setaccelerator keystrokes contexthelp addactionlistener reportactionrouter getinstance help_about jmenuitem jmeterutils getresstring help_about setactioncommand help_about addactionlistener reportactionrouter getinstance helpmenu contexthelp helpmenu help_about private void make options menu options menu options menu new j menu j meter utils get res string option j menu item function helper new j menu item j meter utils get res string function dialog menu item f function helper add action listener report action router get instance function helper set action command functions function helper set accelerator key strokes functions laf menu new j menu j meter utils get res string appearance ui manager look and feel info lafs ui manager get installed look and feels for int i 0 i lafs length i j menu item laf new j menu item lafs i get name laf add action listener report action router get instance laf set action command laf lafs i get class name laf menu set mnemonic l laf menu add laf options menu set mnemonic o options menu add function helper options menu add laf menu if ssl manager isssl supported ssl manager new j menu item j meter utils get res string ssl manager ssl manager add action listener report action router get instance ssl manager set action command ssl manager ssl manager set mnemonic s ssl manager set accelerator key strokes ssl manager options menu add ssl manager options menu add make language menu makeoptionsmenu optionsmenu jmenu jmeterutils getresstring jmenuitem functionhelper jmenuitem jmeterutils getresstring function_dialog_menu_item functionhelper addactionlistener reportactionrouter getinstance functionhelper setactioncommand functionhelper setaccelerator keystrokes lafmenu jmenu jmeterutils getresstring uimanager lookandfeelinfo uimanager getinstalledlookandfeels jmenuitem jmenuitem getname addactionlistener reportactionrouter getinstance setactioncommand getclassname lafmenu setmnemonic lafmenu optionsmenu setmnemonic optionsmenu functionhelper optionsmenu lafmenu sslmanager issslsupported sslmanager jmenuitem jmeterutils getresstring sslmanager sslmanager addactionlistener reportactionrouter getinstance sslmanager setactioncommand sslmanager sslmanager setmnemonic sslmanager setaccelerator keystrokes ssl_manager optionsmenu sslmanager optionsmenu makelanguagemenu n b changes to language list need to be reflected in resources package test java private j menu make language menu return j meter menu bar make language menu packagetest jmenu makelanguagemenu jmetermenubar makelanguagemenu private void make run menu run menu run menu new j menu j meter utils get res string run run menu set mnemonic r run start new j menu item j meter utils get res string start s run start set accelerator key strokes action start run start add action listener report action router get instance run start set action command action start run stop new j menu item j meter utils get res string stop t run stop set accelerator key strokes action stop run stop set enabled false run stop add action listener report action router get instance run stop set action command action stop run shut new j menu item j meter utils get res string shutdown y run shut set accelerator key strokes action shutdown run shut set enabled false run shut add action listener report action router get instance run shut set action command action shutdown run clear new j menu item j meter utils get res string clear c run clear add action listener report action router get instance run clear set action command action names clear run clearall new j menu item j meter utils get res string clear all a run clearall add action listener report action router get instance run clearall set action command action names clear all run clearall set accelerator key strokes clear all run menu add run start if remote start null run menu add remote start remote start all new j menu item j meter utils get res string remote start all z remote start all set name remote start all remote start all set accelerator key strokes remote start all remote start all add action listener report action router get instance remote start all set action command remote start all run menu add remote start all run menu add run stop run menu add run shut if remote stop null run menu add remote stop remote stop all new j menu item j meter utils get res string remote stop all x remote stop all set accelerator key strokes remote stop all remote stop all add action listener report action router get instance remote stop all set action command remote stop all run menu add remote stop all if remote exit null run menu add remote exit remote exit all new j menu item j meter utils get res string remote exit all remote exit all add action listener report action router get instance remote exit all set action command remote exit all run menu add remote exit all run menu add separator run menu add run clear run menu add run clearall makerunmenu runmenu jmenu jmeterutils getresstring runmenu setmnemonic run_start jmenuitem jmeterutils getresstring run_start setaccelerator keystrokes action_start run_start addactionlistener reportactionrouter getinstance run_start setactioncommand action_start run_stop jmenuitem jmeterutils getresstring run_stop setaccelerator keystrokes action_stop run_stop setenabled run_stop addactionlistener reportactionrouter getinstance run_stop setactioncommand action_stop run_shut jmenuitem jmeterutils getresstring run_shut setaccelerator keystrokes action_shutdown run_shut setenabled run_shut addactionlistener reportactionrouter getinstance run_shut setactioncommand action_shutdown run_clear jmenuitem jmeterutils getresstring run_clear addactionlistener reportactionrouter getinstance run_clear setactioncommand actionnames run_clearall jmenuitem jmeterutils getresstring clear_all run_clearall addactionlistener reportactionrouter getinstance run_clearall setactioncommand actionnames clear_all run_clearall setaccelerator keystrokes clear_all runmenu run_start remote_start runmenu remote_start remote_start_all jmenuitem jmeterutils getresstring remote_start_all remote_start_all setname remote_start_all remote_start_all setaccelerator keystrokes remote_start_all remote_start_all addactionlistener reportactionrouter getinstance remote_start_all setactioncommand remote_start_all runmenu remote_start_all runmenu run_stop runmenu run_shut remote_stop runmenu remote_stop remote_stop_all jmenuitem jmeterutils getresstring remote_stop_all remote_stop_all setaccelerator keystrokes remote_stop_all remote_stop_all addactionlistener reportactionrouter getinstance remote_stop_all setactioncommand remote_stop_all runmenu remote_stop_all remote_exit runmenu remote_exit remote_exit_all jmenuitem jmeterutils getresstring remote_exit_all remote_exit_all addactionlistener reportactionrouter getinstance remote_exit_all setactioncommand remote_exit_all runmenu remote_exit_all runmenu addseparator runmenu run_clear runmenu run_clearall private void make edit menu edit menu edit menu new j menu j meter utils get res string edit from the java look and feel guidelines if all items in a menu are disabled then disable the menu makes sense edit menu set enabled false makeeditmenu editmenu jmenu jmeterutils getresstring editmenu setenabled private void make file menu file menu file menu new j menu j meter utils get res string file file menu set mnemonic f j menu item file save new j menu item j meter utils get res string save s file save set accelerator key strokes save file save set action command save file save add action listener report action router get instance file save set enabled true file save as new j menu item j meter utils get res string save all as a file save as set accelerator key strokes save all as file save as set action command save all as file save as add action listener report action router get instance file save as set enabled true file load new j menu item j meter utils get res string menu open o file load set accelerator key strokes open file load add action listener report action router get instance set default save menu item to disabled since the default node that is selected is root which does not allow items to be inserted file load set enabled false file load set action command open file close new j menu item j meter utils get res string menu close c file close set accelerator key strokes close file close set action command close file close add action listener report action router get instance file exit new j menu item j meter utils get res string exit x file exit set accelerator key strokes exit file exit set action command exit file exit add action listener report action router get instance file merge new j menu item j meter utils get res string menu merge m file merge set accelerator key stroke get key stroke key event vk o key event ctrl mask file merge add action listener report action router get instance set default save menu item to disabled since the default node that is selected is root which does not allow items to be inserted file merge set enabled false file merge set action command merge file menu add file close file menu add file load file menu add file merge file menu add file save file menu add file save as file menu add separator file menu add file exit makefilemenu filemenu jmenu jmeterutils getresstring filemenu setmnemonic jmenuitem file_save jmenuitem jmeterutils getresstring file_save setaccelerator keystrokes file_save setactioncommand file_save addactionlistener reportactionrouter getinstance file_save setenabled file_save_as jmenuitem jmeterutils getresstring save_all_as file_save_as setaccelerator keystrokes save_all_as file_save_as setactioncommand save_all_as file_save_as addactionlistener reportactionrouter getinstance file_save_as setenabled file_load jmenuitem jmeterutils getresstring menu_open file_load setaccelerator keystrokes file_load addactionlistener reportactionrouter getinstance file_load setenabled file_load setactioncommand file_close jmenuitem jmeterutils getresstring menu_close file_close setaccelerator keystrokes file_close setactioncommand file_close addactionlistener reportactionrouter getinstance file_exit jmenuitem jmeterutils getresstring file_exit setaccelerator keystrokes file_exit setactioncommand file_exit addactionlistener reportactionrouter getinstance file_merge jmenuitem jmeterutils getresstring menu_merge file_merge setaccelerator keystroke getkeystroke keyevent vk_o keyevent ctrl_mask file_merge addactionlistener reportactionrouter getinstance file_merge setenabled file_merge setactioncommand filemenu file_close filemenu file_load filemenu file_merge filemenu file_save filemenu file_save_as filemenu addseparator filemenu file_exit public void set running boolean running string host log info set running running host iterator iter remote engine start iterator iterator iter2 remote engine stop iterator iterator iter3 remote engine exit iterator while iter has next iter2 has next iter3 has next j menu item start j menu item iter next j menu item stop j menu item iter2 next j menu item exit j menu item iter3 next if start get text equals host log info found start host start get text start set enabled running if stop get text equals host log info found stop host stop get text stop set enabled running if exit get text equals host log info found exit host exit get text exit set enabled true setrunning setrunning remote_engine_start remote_engine_stop remote_engine_exit hasnext hasnext hasnext jmenuitem jmenuitem jmenuitem jmenuitem jmenuitem jmenuitem gettext gettext setenabled gettext gettext setenabled gettext gettext setenabled public void set enabled boolean enable run start set enabled enable run stop set enabled enable run shut set enabled enable setenabled run_start setenabled run_stop setenabled run_shut setenabled private void get remote items if remote hosts length 0 remote start new j menu j meter utils get res string remote start remote stop new j menu j meter utils get res string remote stop remote exit new j menu j meter utils get res string remote exit for int i 0 i remote hosts length i remote hosts i remote hosts i trim j menu item item new j menu item remote hosts i item set action command remote start item set name remote hosts i item add action listener report action router get instance remote engine start add item remote start add item item new j menu item remote hosts i item set action command remote stop item set name remote hosts i item add action listener report action router get instance item set enabled false remote engine stop add item remote stop add item item new j menu item remote hosts i item set action command remote exit item set name remote hosts i item add action listener report action router get instance item set enabled false remote engine exit add item remote exit add item getremoteitems remotehosts remote_start jmenu jmeterutils getresstring remote_start remote_stop jmenu jmeterutils getresstring remote_stop remote_exit jmenu jmeterutils getresstring remote_exit remotehosts remotehosts remotehosts jmenuitem jmenuitem remotehosts setactioncommand remote_start setname remotehosts addactionlistener reportactionrouter getinstance remote_engine_start remote_start jmenuitem remotehosts setactioncommand remote_stop setname remotehosts addactionlistener reportactionrouter getinstance setenabled remote_engine_stop remote_stop jmenuitem remotehosts setactioncommand remote_exit setname remotehosts addactionlistener reportactionrouter getinstance setenabled remote_engine_exit remote_exit processes a locale change notification changes the texts in all menus to the new language public void locale changed locale change event event update menu element file menu update menu element edit menu update menu element run menu update menu element options menu update menu element help menu localechanged localechangeevent updatemenuelement filemenu updatemenuelement editmenu updatemenuelement runmenu updatemenuelement optionsmenu updatemenuelement helpmenu refreshes all texts in the menu and all submenus to a new locale private void update menu element menu element menu component component menu get component if component get name null if component instanceof j menu j menu component set text j meter utils get res string component get name else j menu item component set text j meter utils get res string component get name menu element subelements menu get sub elements for int i 0 i subelements length i update menu element subelements i updatemenuelement menuelement getcomponent getname jmenu jmenu settext jmeterutils getresstring getname jmenuitem settext jmeterutils getresstring getname menuelement getsubelements updatemenuelement private j text field duration public duration assertion gui init jtextfield durationassertiongui public string get label resource return duration assertion title non nls 1 getlabelresource duration_assertion_title public string get duration attributes title return j meter utils get res string duration assertion duration test non nls 1 getdurationattributestitle jmeterutils getresstring duration_assertion_duration_test public test element create test element duration assertion el new duration assertion modify test element el return el testelement createtestelement durationassertion durationassertion modifytestelement modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element el configure test element el if el instanceof duration assertion duration assertion assertion duration assertion el assertion set property duration assertion duration key duration get text save scope settings assertion testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement durationassertion durationassertion durationassertion setproperty durationassertion duration_key gettext savescopesettings implements j metergui component clear gui public void clear gui super clear gui duration set text non nls 1 jmeterguicomponent cleargui cleargui cleargui settext public void configure test element el super configure el if el instanceof duration assertion duration assertion da duration assertion el duration set text da get property as string duration assertion duration key show scope settings da testelement durationassertion durationassertion durationassertion settext getpropertyasstring durationassertion duration_key showscopesettings private void init set layout new border layout 0 10 set border make border add make title panel border layout north j panel main panel new vertical panel main panel add create scope panel user input vertical panel duration panel new vertical panel duration panel set border border factory create titled border border factory create etched border get duration attributes title j panel label panel new j panel new border layout 5 0 j label duration label new j label j meter utils get res string duration assertion label non nls 1 label panel add duration label border layout west duration new j text field label panel add duration border layout center duration label set label for duration duration panel add label panel main panel add duration panel add main panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout jpanel mainpanel verticalpanel mainpanel createscopepanel user_input verticalpanel durationpanel verticalpanel durationpanel setborder borderfactory createtitledborder borderfactory createetchedborder getdurationattributestitle jpanel labelpanel jpanel borderlayout jlabel durationlabel jlabel jmeterutils getresstring duration_assertion_label labelpanel durationlabel borderlayout jtextfield labelpanel borderlayout durationlabel setlabelfor durationpanel labelpanel mainpanel durationpanel mainpanel borderlayout public class put writer extends post writer constructor for put writer public put writer put request does not use multipart so no need for boundary super null putwriter postwriter putwriter putwriter public void set headers url connection connection http sampler sampler throws io exception get the encoding to use for the request string content encoding sampler get content encoding if content encoding null content encoding length 0 content encoding encoding long content length 0l boolean has put body false check if the header manager had a content type header this allows the user to specify his own content type for a put request string content type header connection get request property http constants header content type boolean has content type header content type header null content type header length 0 http file arg files sampler gethttp files if there are no arguments we can send a file as the body of the request if sampler get arguments null sampler get arguments get argument count 0 sampler get send file as post body if get send file as post body returned true it s sure that file is not null http file arg file files 0 has put body true if has content type header allow the mimetype of the file to control the content type if file get mime type length 0 connection set request property http constants header content type file get mime type create the content length we are going to write file input file new file file get path content length input file length else if sampler get send parameter values as post body has put body true allow the mimetype of the file to control the content type this is not obvious in gui if you are not uploading any files but just sending the content of nameless parameters if has content type header files length 1 files 0 get mime type length 0 connection set request property http constants header content type files 0 get mime type we create the post body content now so we know the size byte array output stream bos new byte array output stream just append all the parameter values and use that as the put body string buffer put body buffer new string buffer property iterator args sampler get arguments iterator while args has next http argument arg http argument args next get object value put body buffer append arg get encoded value content encoding bos write put body buffer to string get bytes content encoding bos flush bos close keep the content will be sent later form data url encoded bos to byte array content length bos to byte array length if has put body set the content length connection set request property http constants header content length long to string content length make the connection ready for sending post data connection set do output true setheaders urlconnection httpsampler ioexception contentencoding getcontentencoding contentencoding contentencoding contentencoding contentlength hasputbody contenttypeheader getrequestproperty httpconstants header_content_type hascontenttypeheader contenttypeheader contenttypeheader httpfilearg gethttpfiles getarguments getarguments getargumentcount getsendfileaspostbody getsendfileaspostbody httpfilearg hasputbody hascontenttypeheader getmimetype setrequestproperty httpconstants header_content_type getmimetype inputfile getpath contentlength inputfile getsendparametervaluesaspostbody hasputbody hascontenttypeheader getmimetype setrequestproperty httpconstants header_content_type getmimetype bytearrayoutputstream bytearrayoutputstream stringbuffer putbodybuffer stringbuffer propertyiterator getarguments hasnext httpargument httpargument getobjectvalue putbodybuffer getencodedvalue contentencoding putbodybuffer tostring getbytes contentencoding formdataurlencoded tobytearray contentlength tobytearray hasputbody setrequestproperty httpconstants header_content_length tostring contentlength setdooutput public class html report writer extends abstract report writer public html report writer super htmlreportwriter abstractreportwriter htmlreportwriter public report summary write report test element element return null reportsummary writereport testelement see org apache jmeter gui action command get action names public set get action names return commands getactionnames getactionnames see org apache jmeter gui action command do action action event public void do action action event e report gui package gui pack report gui package get instance report tree node current nodes gui pack get tree listener get selected nodes report copy set copied nodes current nodes for int i 0 i current nodes length i gui pack get tree model remove node from parent current nodes i gui pack get main frame repaint doaction actionevent doaction actionevent reportguipackage guipack reportguipackage getinstance reporttreenode currentnodes guipack gettreelistener getselectednodes reportcopy setcopiednodes currentnodes currentnodes guipack gettreemodel removenodefromparent currentnodes guipack getmainframe public class testxml buffer extends j meter test case public testxml buffer string arg0 super arg0 testxmlbuffer jmetertestcase testxmlbuffer public void test1 throws exception xml buffer xb new xml buffer xb open tag start assert equals start start n xb to string xmlbuffer xmlbuffer opentag assertequals tostring public void test2 throws exception xml buffer xb new xml buffer xb tag start now assert equals start now start n xb to string xmlbuffer xmlbuffer assertequals tostring public void test3 throws exception xml buffer xb new xml buffer xb open tag abc xb close tag abc assert equals abc abc n xb to string xmlbuffer xmlbuffer opentag closetag assertequals tostring public void test4 throws exception xml buffer xb new xml buffer xb open tag abc try xb close tag abcd fail should have caused illegal argument exception catch illegal argument exception e xmlbuffer xmlbuffer opentag closetag illegalargumentexception illegalargumentexception private volatile ftp client saved client public ftp sampler ftpclient savedclient ftpsampler public string get username return get property as string config test element username getusername getpropertyasstring configtestelement public string get password return get property as string config test element password getpassword getpropertyasstring configtestelement public void set server string new server this set property server new server setserver newserver setproperty newserver public string get server return get property as string server getserver getpropertyasstring public void set port string new port this set property port new port non nls 1 setport newport setproperty newport public string get port return get property as string port non nls 1 getport getpropertyasstring public int get port as int return get property as int port 0 getportasint getpropertyasint public string get remote filename return get property as string remote filename getremotefilename getpropertyasstring remote_filename public string get local filename return get property as string local filename getlocalfilename getpropertyasstring local_filename private string get local file contents return get property as string input data getlocalfilecontents getpropertyasstring input_data public boolean is binary mode return get property as boolean binary mode false isbinarymode getpropertyasboolean binary_mode public boolean is save response return get property as boolean save response false issaveresponse getpropertyasboolean save_response public boolean is upload return get property as boolean upload file false isupload getpropertyasboolean upload_file returns a formatted string label describing this sampler example output ftp ftp nowhere com pub readme txt return a formatted string label describing this sampler public string get label str builder sb new str builder sb set null text null non nls 1 sb append ftp non nls 1 sb append get server string port get port if port length 0 sb append sb append port sb append non nls 1 sb append get remote filename sb append is binary mode binary ascii non nls 1 non nls 2 sb append is upload non nls 1 non nls 2 sb append get local filename return sb to string getlabel strbuilder strbuilder setnulltext getserver getport getremotefilename isbinarymode isupload getlocalfilename tostring public sample result sample entry e sample result res new sample result res set successful false assume failure string remote get remote filename string local get local filename boolean binary transfer is binary mode res set sample label get name final string label get label res set sampler data label try res seturl new url label catch malformedurl exception e1 log warn cannot set url e1 get localized message input stream input null output stream output null res sample start ftp client ftp new ftp client try saved client ftp final int port get port as int if port 0 ftp connect get server port else ftp connect get server res latency end int reply ftp get reply code if ftp reply is positive completion reply if ftp login get username get password if binary transfer ftp set file type ftp binary file type ftp enter local passive mode should probably come from the setup dialog boolean ftpok false if is upload string contents get local file contents if contents length 0 byte bytes contents get bytes todo this assumes local encoding input new byte array input stream bytes res set bytes bytes length else file infile new file local res set bytes int infile length input new file input stream infile ftpok ftp store file remote input else final boolean save response is save response byte array output stream baos null no need to close this output stream target null no need to close this if save response baos new byte array output stream target baos if local length 0 output new file output stream local if target null target output else target new tee output stream output baos if target null target new null output stream input ftp retrieve file stream remote if input null could not access file or other error res set response code integer to string ftp get reply code res set response message ftp get reply string else long bytes io utils copy input target ftpok bytes 0 if save response baos null res set response data baos to byte array if binary transfer res set data type sample result text else res set bytes int bytes if ftpok res set response codeok res set response messageok res set successful true else res set response code integer to string ftp get reply code res set response message ftp get reply string else res set response code integer to string ftp get reply code res set response message ftp get reply string else res set response code 501 todo res set response message could not connect res set response code integer to string ftp get reply code res set response message ftp get reply string catch io exception ex res set response code 000 todo res set response message ex to string finally saved client null if ftp is connected try ftp logout catch io exception ignored try ftp disconnect catch io exception ignored io utils close quietly input io utils close quietly output res sample end return res sampleresult sampleresult sampleresult setsuccessful getremotefilename getlocalfilename binarytransfer isbinarymode setsamplelabel getname getlabel setsamplerdata malformedurlexception getlocalizedmessage inputstream outputstream samplestart ftpclient ftpclient savedclient getportasint getserver getserver latencyend getreplycode ftpreply ispositivecompletion getusername getpassword binarytransfer setfiletype binary_file_type enterlocalpassivemode isupload getlocalfilecontents getbytes bytearrayinputstream setbytes setbytes fileinputstream storefile saveresponse issaveresponse bytearrayoutputstream outputstream saveresponse bytearrayoutputstream fileoutputstream teeoutputstream nulloutputstream retrievefilestream setresponsecode tostring getreplycode setresponsemessage getreplystring ioutils saveresponse setresponsedata tobytearray binarytransfer setdatatype sampleresult setbytes setresponsecodeok setresponsemessageok setsuccessful setresponsecode tostring getreplycode setresponsemessage getreplystring setresponsecode tostring getreplycode setresponsemessage getreplystring setresponsecode setresponsemessage setresponsecode tostring getreplycode setresponsemessage getreplystring ioexception setresponsecode setresponsemessage tostring savedclient isconnected ioexception ioexception ioutils closequietly ioutils closequietly sampleend inherit doc public boolean interrupt ftp client client saved client if client null saved client null try client abort client disconnect catch io exception ignored return client null inheritdoc ftpclient savedclient savedclient ioexception methods implemented from org xml sax content handler public void set document locator locator locator contenthandler setdocumentlocator public void start document throws sax exception startdocument saxexception public void end document throws sax exception enddocument saxexception public void start prefix mapping string prefix string uri throws sax exception startprefixmapping saxexception public void end prefix mapping string prefix throws sax exception endprefixmapping saxexception public void start element string namespaceurl string local name string q name attributes atts throws sax exception contents reset haven t got to reset paramname paramvalue but did it to keep the code looking correct if q name equals parameter paramname paramvalue must create a new object or else end up with a set full of the same map object if q name equals thread name value pair new hash map startelement localname qname saxexception qname qname namevaluepair hashmap public void end element string namespaceuri string local name string q name throws sax exception if q name equals paramname paramname contents to string if q name equals paramvalue paramvalue contents to string if q name equals parameter name value pair put paramname paramvalue if q name equals thread user threads add name value pair endelement localname qname saxexception qname tostring qname tostring qname namevaluepair qname userthreads namevaluepair public void characters char ch int start int length throws sax exception contents write ch start length saxexception public void ignorable whitespace char ch int start int length throws sax exception ignorablewhitespace saxexception public void processing instruction string target string date throws sax exception processinginstruction saxexception public void skipped entity string name throws sax exception skippedentity saxexception results of parsing all user parameter data defined in xml file return all users name value pairs obtained from xml file public list get parsed parameters return user threads getparsedparameters userthreads public class j meter stop thread exception extends runtime exception public j meter stop thread exception super jmeterstopthreadexception runtimeexception jmeterstopthreadexception public j meter stop thread exception string s super s jmeterstopthreadexception new j label j meter utils get res string obsolete test element non nls 1 public obsolete gui init jlabel jmeterutils getresstring obsolete_test_element obsoletegui private void init set layout new border layout 0 10 set border make border add make title panel border layout north add obsolete message border layout west setlayout borderlayout setborder makeborder maketitlepanel borderlayout obsoletemessage borderlayout public string get label resource return obsolete test element non nls 1 getlabelresource obsolete_test_element public test element create test element return new config test element testelement createtestelement configtestelement public void modify test element test element element modifytestelement testelement public j popup menu create popup menu return null jpopupmenu createpopupmenu public collection get menu categories return null getmenucategories private object values public eval var function evalvarfunction public synchronized string execute sample result previous result sampler current sampler throws invalid variable exception string variable name compound variable values 0 execute final j meter variables vars get variables if vars null log error variables have not yet been defined return error see log file string variable value vars get variable name compound variable cv new compound variable variable value return cv execute sampleresult previousresult currentsampler invalidvariableexception variablename compoundvariable jmetervariables getvariables variablevalue variablename compoundvariable compoundvariable variablevalue public synchronized void set parameters collection parameters throws invalid variable exception check parameter count parameters min parameter count max parameter count values parameters to array setparameters invalidvariableexception checkparametercount min_parameter_count max_parameter_count toarray public string get reference key return key getreferencekey public list get argument desc return desc getargumentdesc public http mirror control gui super log debug creating http mirror control gui init httpmirrorcontrolgui httpmirrorcontrolgui public test element create test element mirror controller new http mirror control log debug creating configuring model mirror controller modify test element mirror controller return mirror controller testelement createtestelement mirrorcontroller httpmirrorcontrol mirrorcontroller modifytestelement mirrorcontroller mirrorcontroller modifies a given test element to mirror the data in the gui components see org apache jmeter gui j metergui component modify test element test element public void modify test element test element el configure test element el if el instanceof http mirror control mirror controller http mirror control el mirror controller set port port field get text testelement jmeterguicomponent modifytestelement testelement modifytestelement testelement configuretestelement httpmirrorcontrol mirrorcontroller httpmirrorcontrol mirrorcontroller setport portfield gettext public string get label resource return httpmirror title non nls 1 getlabelresource httpmirror_title public collection get menu categories return arrays as list new string menu factory non test elements getmenucategories aslist menufactory non_test_elements public void configure test element element log debug configuring gui with element super configure element mirror controller http mirror control element port field set text mirror controller get port string repaint testelement mirrorcontroller httpmirrorcontrol portfield settext mirrorcontroller getportstring public void action performed action event action string command action get action command if command equals action stop mirror controller stop http mirror stop set enabled false start set enabled true else if command equals action start modify test element mirror controller mirror controller start http mirror start set enabled false stop set enabled true actionperformed actionevent getactioncommand action_stop mirrorcontroller stophttpmirror setenabled setenabled action_start modifytestelement mirrorcontroller mirrorcontroller starthttpmirror setenabled setenabled private void init set layout new border layout 0 5 set border make border add make title panel border layout north j panel main panel new j panel new border layout box my box box create vertical box my box add create port panel main panel add my box border layout north main panel add create controls border layout center add main panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout jpanel mainpanel jpanel borderlayout mybox createverticalbox mybox createportpanel mainpanel mybox borderlayout mainpanel createcontrols borderlayout mainpanel borderlayout private j panel create controls start new j button j meter utils get res string start non nls 1 start add action listener this start set action command action start start set enabled true stop new j button j meter utils get res string stop non nls 1 stop add action listener this stop set action command action stop stop set enabled false j panel panel new j panel panel add start panel add stop return panel jpanel createcontrols jbutton jmeterutils getresstring addactionlistener setactioncommand action_start setenabled jbutton jmeterutils getresstring addactionlistener setactioncommand action_stop setenabled jpanel jpanel private j panel create port panel port field new j text field http mirror control default port s 8 port field set name http mirror control port j label label new j label j meter utils get res string port non nls 1 label set label for port field horizontal panel panel new horizontal panel panel add label panel add port field panel add box create horizontal strut 10 return panel jpanel createportpanel portfield jtextfield httpmirrorcontrol default_port_s portfield setname httpmirrorcontrol jlabel jlabel jmeterutils getresstring setlabelfor portfield horizontalpanel horizontalpanel portfield createhorizontalstrut public void clear gui super clear gui port field set text http mirror control default port s cleargui cleargui portfield settext httpmirrorcontrol default_port_s public user sequence usersequence load all user and parameter data into the sequence module p ie a set of mapped parameter names and parameter values for each user to be loaded into the sequencer public user sequence list all users this all users all users initalise pointer to first user index of users all users iterator usersequence allusers allusers allusers indexofusers allusers returns the parameter data for the next user in the sequence return a map object of parameter names and matching parameter values for the next user public synchronized map get next user mods use round robin allocation of user details if index of users has next index of users all users iterator map user if index of users has next user map index of users next log debug user sequence get nextuser mods current parameters will be changed to user else no entries in all users therefore create an empty map object user new hash map return user getnextusermods indexofusers hasnext indexofusers allusers indexofusers hasnext indexofusers usersequence getnextusermods hashmap constructor for java test sampler gui public java test sampler gui super init javatestsamplergui javatestsamplergui public string get label resource return java request non nls 1 getlabelresource java_request initialize the gui components and layout private void init set layout new border layout 0 5 set border make border add make title panel border layout north java panel new java config gui false add java panel border layout center setlayout borderlayout setborder makeborder maketitlepanel borderlayout javapanel javaconfiggui javapanel borderlayout implements j meter gui component create test element public test element create test element java sampler sampler new java sampler modify test element sampler return sampler jmeterguicomponent createtestelement testelement createtestelement javasampler javasampler modifytestelement implements j meter gui component modify test element test element public void modify test element test element sampler sampler clear java config config java config java panel create test element configure test element sampler sampler add test element config jmeterguicomponent modifytestelement testelement modifytestelement testelement javaconfig javaconfig javapanel createtestelement configuretestelement addtestelement overrides abstractj meter gui component configure test element public void configure test element el super configure el java panel configure el abstractjmeterguicomponent testelement testelement javapanel constructor for the close object public close gets the action names attribute of the close object return the action names value public set get action names return commands actionnames actionnames getactionnames this method performs the actual command processing param e the generic ui action event public void do action action event e perform action e doaction actionevent performaction helper routine to allow action to be shared by load param e event return true if close was not cancelled static boolean perform action action event e action router get instance do action now new action event e get source e getid action names check dirty gui package gui package gui package get instance if gui package is dirty int response if response j option pane show confirm dialog gui package get instance get main frame j meter utils get res string cancel new to save non nls 1 j meter utils get res string save non nls 1 j option pane yes no cancel option j option pane question message j option pane yes option action router get instance do action now new action event e get source e getid action names save if response j option pane closed option response j option pane cancel option return false don t clear the plan close project e return true performaction actionevent actionrouter getinstance doactionnow actionevent getsource actionnames check_dirty guipackage guipackage guipackage getinstance guipackage isdirty joptionpane showconfirmdialog guipackage getinstance getmainframe jmeterutils getresstring cancel_new_to_save jmeterutils getresstring joptionpane yes_no_cancel_option joptionpane question_message joptionpane yes_option actionrouter getinstance doactionnow actionevent getsource actionnames joptionpane closed_option joptionpane cancel_option closeproject static void close project action event e gui package gui package gui package get instance gui package clear test plan gui package get tree listener getj tree set selection row 1 action router get instance action performed new action event e get source e getid action names add all closeproject actionevent guipackage guipackage guipackage getinstance guipackage cleartestplan guipackage gettreelistener getjtree setselectionrow actionrouter getinstance actionperformed actionevent getsource actionnames add_all combo string editor create the combo box we will use to edit this property model new default combo box model model add element undefined model add element edit combo new j combo box model combo add item listener this combo set editable false combostringeditor defaultcomboboxmodel addelement addelement jcombobox additemlistener seteditable see java beans property editor supports custom editor public boolean supports custom editor return true propertyeditor supportscustomeditor supportscustomeditor see java beans property editor get custom editor public component get custom editor return combo propertyeditor getcustomeditor getcustomeditor see java beans property editor get value public object get value return get as text propertyeditor getvalue getvalue getastext public string get as text object value combo get selected item if value undefined return null return string value getastext getselecteditem see java beans property editor set value public void set value object value set as text string value propertyeditor setvalue setvalue setastext public void set as text string value combo set editable true if value null combo set selected item undefined else combo set selected item value if starting edit combo get selected index 0 combo set editable false setastext seteditable setselecteditem setselecteditem startingedit getselectedindex seteditable public void item state changed item event e if e get state change item event selected if e get item edit starting edit true start editing starting edit false else if starting edit combo get selected index 0 combo set editable false fire property change itemstatechanged itemevent getstatechange itemevent getitem startingedit startediting startingedit startingedit getselectedindex seteditable firepropertychange private void start editing j text component text field j text component combo get editor get editor component combo set editable true text field request focus string text initial edit value if initial edit value null text will revert to last valid value if invalid combo set selected item text int i text index of if i 1 text field set caret position i 2 else text field select all startediting jtextcomponent textfield jtextcomponent geteditor geteditorcomponent seteditable textfield requestfocus initialeditvalue initialeditvalue setselecteditem indexof textfield setcaretposition textfield selectall public string get initial edit value return initial edit value getinitialeditvalue initialeditvalue public boolean get no edit return no edit getnoedit noedit public boolean get no undefined return no undefined getnoundefined noundefined public string get tags return tags gettags param object public void set initial edit value string object initial edit value object setinitialeditvalue initialeditvalue param b public void set no edit boolean b if no edit b return no edit b if no edit model remove element edit else model add element edit setnoedit noedit noedit noedit removeelement addelement param b public void set no undefined boolean b if no undefined b return no undefined b if no undefined model remove element undefined else model insert element at undefined 0 setnoundefined noundefined noundefined noundefined removeelement insertelementat param strings public void set tags string strings if arrays equals tags strings return for int i 0 i tags length i model remove element tags i tags strings null new string 0 strings int b no undefined 0 1 base index for tags for int i 0 i tags length i model insert element at tags i b i settags removeelement noundefined insertelementat private string s unique object string s this s s uniqueobject public string to string return s tostring public compound variable super is dynamic true has function false compoundvariable isdynamic hasfunction public compound variable string parameters this try set parameters parameters catch invalid variable exception e compoundvariable setparameters invalidvariableexception public string execute if is dynamic j meter context context j meter context service get context sample result previous result context get previous result sampler current sampler context get current sampler return execute previous result current sampler return permanent results non nls 1 isdynamic jmetercontext jmetercontextservice getcontext sampleresult previousresult getpreviousresult currentsampler getcurrentsampler previousresult currentsampler permanentresults allows the retrieval of the original string prior to it being compiled return string public string get raw parameters return raw parameters getrawparameters rawparameters public string execute sample result previous result sampler current sampler if compiled components null compiled components size 0 return non nls 1 boolean test dynamic false string buffer results new string buffer iterator iter compiled components iterator while iter has next object item iter next if item instanceof function test dynamic true try results append function item execute previous result current sampler catch invalid variable exception e else if item instanceof simple variable test dynamic true results append simple variable item to string else results append item if test dynamic is dynamic false permanent results results to string return results to string sampleresult previousresult currentsampler compiledcomponents compiledcomponents testdynamic stringbuffer stringbuffer compiledcomponents hasnext testdynamic previousresult currentsampler invalidvariableexception simplevariable testdynamic simplevariable tostring testdynamic isdynamic permanentresults tostring tostring public compound variable get function compound variable func new compound variable func compiled components linked list compiled components clone func raw parameters raw parameters return func compoundvariable getfunction compoundvariable compoundvariable compiledcomponents linkedlist compiledcomponents rawparameters rawparameters public list get argument desc return new linked list getargumentdesc linkedlist public void clear todo should this also clear is dynamic raw parameters permanent results has function false compiled components clear isdynamic rawparameters permanentresults hasfunction compiledcomponents public void set parameters string parameters throws invalid variable exception this raw parameters parameters if parameters null parameters length 0 return compiled components function parser compile string parameters if compiled components size 1 compiled components get 0 instanceof string has function true setparameters invalidvariableexception rawparameters compiledcomponents functionparser compilestring compiledcomponents compiledcomponents hasfunction static object get named function string function name throws invalid variable exception if functions contains key function name try return class functions get function name new instance catch exception e log error e non nls 1 throw new invalid variable exception return new simple variable function name getnamedfunction functionname invalidvariableexception containskey functionname functionname newinstance invalidvariableexception simplevariable functionname public boolean has function return has function hasfunction hasfunction see function get reference key public string get reference key return non nls 1 getreferencekey getreferencekey public void set parameters collection parameters throws invalid variable exception setparameters invalidvariableexception public summary report super model new object table model columns calculator class all rows have this class new functor new functor get label non nls 1 new functor get count non nls 1 new functor get mean as number non nls 1 new functor get min non nls 1 new functor get max non nls 1 new functor get standard deviation non nls 1 new functor get error percentage non nls 1 new functor get rate non nls 1 new functor getkb per second non nls 1 new functor get avg page bytes non nls 1 new functor null null null null null null null null null null new class string class long class long class long class long class string class string class string class string class string class clear data init summaryreport objecttablemodel getlabel getcount getmeanasnumber getmin getmax getstandarddeviation geterrorpercentage getrate getkbpersecond getavgpagebytes cleardata deprecated only for use in testing public static boolean test functors summary report instance new summary report return instance model check functors null instance get class testfunctors summaryreport summaryreport checkfunctors getclass public string get label resource return summary report non nls 1 getlabelresource summary_report public void add sample result res calculator row null final string sample label res get sample label use group name is selected synchronized table rows row calculator table rows get sample label if row null row new calculator sample label table rows put row get label row model insert row row model get row count 1 synch is needed because multiple threads can update the counts synchronized row row add sample res calculator tot calculator table rows get total row label synchronized tot tot add sample res model fire table data changed sampleresult samplelabel getsamplelabel usegroupname isselected tablerows tablerows samplelabel samplelabel tablerows getlabel insertrow getrowcount addsample tablerows total_row_label addsample firetabledatachanged clears this visualizer and its model and forces a repaint of the table public void clear data synchronized table rows model clear data table rows clear table rows put total row label new calculator total row label model add row table rows get total row label cleardata tablerows cleardata tablerows tablerows total_row_label total_row_label addrow tablerows total_row_label main visualizer setup private void init this set layout new border layout main panel j panel main panel new j panel border margin new empty border 10 10 5 10 main panel set border margin main panel set layout new box layout main panel box layout y axis main panel add make title panel myj table new j table model myj table get table header set default renderer new header as property renderer myj table set preferred scrollable viewport size new dimension 500 70 renderer utils apply renderers myj table renderers my scroll pane new j scroll pane myj table this add main panel border layout north this add my scroll pane border layout center save table add action listener this j panel opts new j panel opts add use group name border layout west opts add save table border layout center this add opts border layout south setlayout borderlayout jpanel mainpanel jpanel emptyborder mainpanel setborder mainpanel setlayout boxlayout mainpanel boxlayout y_axis mainpanel maketitlepanel myjtable jtable myjtable gettableheader setdefaultrenderer headeraspropertyrenderer myjtable setpreferredscrollableviewportsize rendererutils applyrenderers myjtable myscrollpane jscrollpane myjtable mainpanel borderlayout myscrollpane borderlayout savetable addactionlistener jpanel jpanel usegroupname borderlayout savetable borderlayout borderlayout public void modify test element test element c super modify test element c c set property use group name use group name is selected false modifytestelement testelement modifytestelement setproperty use_group_name usegroupname isselected public void configure test element el super configure el use group name set selected el get property as boolean use group name false testelement usegroupname setselected getpropertyasboolean use_group_name public void action performed action event ev if ev get source save table j file chooser chooser file dialoger prompt to save file summary csv non nls 1 if chooser null return file writer writer null try writer new file writer chooser get selected file csv save service savecsv stats model writer catch file not found exception e log warn e get message catch io exception e log warn e get message finally j orphan utils close quietly writer actionperformed actionevent getsource savetable jfilechooser filedialoger prompttosavefile filewriter filewriter getselectedfile csvsaveservice savecsvstats filenotfoundexception getmessage ioexception getmessage jorphanutils closequietly param cps characters per second public slow http client socket factory final int cps super cps cps slowhttpclientsocketfactory public socket create socket string host int port inet address client host int client port throws io exception unknown host exception return new slow socket cps host port client host client port createsocket inetaddress clienthost clientport ioexception unknownhostexception slowsocket clienthost clientport public socket create socket string host int port throws io exception unknown host exception return new slow socket cps host port createsocket ioexception unknownhostexception slowsocket public socket create socket string host int port inet address local address int local port http connection params params throws io exception unknown host exception connect timeout exception int timeout params get connection timeout if timeout 0 return new slow socket cps host port local address local port else return new slow socket cps host port local address local port timeout createsocket inetaddress localaddress localport httpconnectionparams ioexception unknownhostexception connecttimeoutexception getconnectiontimeout slowsocket localaddress localport slowsocket localaddress localport public interface page summary extends cloneable long get elapsed time pagesummary getelapsedtime public interface page summary extends cloneable long get elapsed time long get end time stamp pagesummary getelapsedtime getendtimestamp long get elapsed time long get end time stamp string get file name getelapsedtime getendtimestamp getfilename long get end time stamp string get file name string get page title getendtimestamp getfilename getpagetitle string get file name string get page title long get start time stamp getfilename getpagetitle getstarttimestamp string get page title long get start time stamp boolean is successful getpagetitle getstarttimestamp issuccessful long get start time stamp boolean is successful void page started getstarttimestamp issuccessful pagestarted boolean is successful void page started void page ended issuccessful pagestarted pageended void page started void page ended void set file name string file pagestarted pageended setfilename void page ended void set file name string file void set page title string title pageended setfilename setpagetitle void set file name string file void set page title string title void set successful boolean success setfilename setpagetitle setsuccessful public interface report writer report summary write report test element element reportwriter reportsummary writereport testelement public interface report writer report summary write report test element element string get target directory reportwriter reportsummary writereport testelement gettargetdirectory report summary write report test element element string get target directory void set target directory string directory reportsummary writereport testelement gettargetdirectory settargetdirectory public interface report summary extends cloneable add a page summary to the report summary param summary reportsummary void add page summary page summary summary this should be the elapsed time to run all the reports classes implementing it should simply add up the elapsed time for each report page return elapsed time addpagesummary pagesummary long get elapsed time the method should return a list of the pages generated for the report and whether it succeeded or not return page summary array getelapsedtime page summary get pages summaries remove a page summary from the report summary param summary pagesummary getpagessummaries public interface report engine void configure hash tree test plan reportengine hashtree testplan void configure hash tree test plan void run report throws j meter engine exception hashtree testplan runreport jmeterengineexception void run report throws j meter engine exception void stop report runreport jmeterengineexception stopreport void stop report void reset stopreport void reset void exit depending on the implementation the datasouce could be a file or a rdbms it s up to the implementing class to decide param datasource public void set data source string datasource return the datasource for files it should be the absolute path for databases it should be the datasource name created in jmeter setdatasource public string get data source in some cases we may want to return a string that isn t the full datasource string or something different for example we may want to return just the filename and not the absolute path of a jtl file getdatasource absolutepath public string get data source name set the timestamp using the first result from the datasource param stamp getdatasourcename public void set start timestamp long stamp return the timestamp in millisecond format public long get start timestamp setstarttimestamp getstarttimestamp public long get start timestamp set the timestamp using the last result from the datasource param stamp getstarttimestamp public void set end timestamp long stamp return the timestamp in millisecond format public long get end timestamp setendtimestamp getendtimestamp public long get end timestamp return the date object using the start timestamp public date get date getendtimestamp getdate public date get date convienance method for getting the date in mmdd format public string get month day date getdate getmonthdaydate public string get month day date convienant method for getting the date in yyyymmdd format public string get month day year date getmonthdaydate getmonthdayyeardate public string get month day year date classes implementing the method should return the url s in the data set it is up to the class to return strings or url getmonthdayyeardate dataset public set getur ls classes implementing the method should return instance of sampling stat calculator return the set of statistics geturls samplingstatcalculator public set get stats return the sampling stat calculator for a specific url param url getstats samplingstatcalculator public sampling stat calculator get statistics string url convienance method for getting all the sampling stat calculators for a given url param urls samplingstatcalculator getstatistics samplingstatcalculators public list get stats list urls classes implementing the method should load the data from the target location it doesn t necessarily have to be a file it could be from a database getstats public interface report table string get table data list data reporttable gettabledata public interface report chart the method takes a list of the data set items it is up to the chart class to extract the data and use it to render a graphic param data list of data set return the component reportchart dataset dataset public interface tcp client versions of j meter after 2 3 2 invoke this method when the thread starts void setup test tcpclient jmeter setuptest void setup test versions of j meter after 2 3 2 invoke this method when the thread ends void teardown test setuptest jmeter teardowntest param os output stream for socket param is input stream to be written to socket outputstream inputstream param os output stream for socket param s string to write outputstream param is input stream for socket return string read from socket inputstream get the end of line end of message byte return returns the eol byte eolbyte set the end of line end of message byte if the value is out of range of a byte then it is to be ignored param eol int the value to set eolint public interface queue executor sends and receives a message param request the message to send return the received message or code null code throws jms exception in case of an exception from the messaging system queueexecutor jmsexception public interface java sampler client do any initialization required by this client it is generally recommended to do any initialization such as getting parameter values in the setup test method rather than the run test method in order to add as little overhead as possible to the test param context the context to run with this provides access to initialization parameters javasamplerclient setuptest runtest perform a single sample for each iteration this method returns a code sample result code object code sample result code has many fields which can be used at a minimum the test should use code sample result sample start code and code sample result sample end code to set the time that the test required to execute it is also a good idea to set the sample label and the successful flag see org apache jmeter samplers sample result sample start see org apache jmeter samplers sample result sample end see org apache jmeter samplers sample result set successful boolean see org apache jmeter samplers sample result set sample label string param context the context to run with this provides access to initialization parameters return a sample result giving the results of this sample sampleresult sampleresult sampleresult samplestart sampleresult sampleend samplelabel sampleresult samplestart sampleresult sampleend sampleresult setsuccessful sampleresult setsamplelabel sampleresult do any clean up required by this test at the end of a test run param context the context to run with this provides access to initialization parameters provide a list of parameters which this test supports any parameter names and associated values returned by this method will appear in the gui by default so the user doesn t have to remember the exact names the user can add other parameters which are not listed here if this method returns null then no parameters will be listed if the value for some parameter is null then that parameter will be listed in the gui with an empty value return a specification of the parameters used by this test which should be listed in the gui or null if no parameters should be listed public interface generator close the generator public void close the host is the name of the server param host this is the label for the request which is used in the logs and results param label the method is the http request method it s normally post or get param post get post_get set the request parameters param params the path is the web page you want to test param path the default port for http is 80 but not all servers run on that port param port port number set the querystring for the request if the method is get param querystring the source logs is the location where the access log resides param sourcefile the target can be either a java io file or a sampler we make it generic so that later on we can use these classes directly from a http sampler param target httpsampler the method is responsible for calling the necessary methods to generate a valid request if the generator is used to pre process access logs the method wouldn t return anything if the generator is used by a control element it should return the correct sampler class with the required fields set if the generator is converting the logs to a jmx file save should be called the purpose of the reset is so samplers can explicitly call reset to create a new instance of http sampler httpsampler param oldextension param newextension include all files in the array param filenames exclude all files in the array param filenames include any log entry that contains the following regular expression pattern param regexp exclude any log entry that contains the following regular expression pattern param regexp log parser will call this method to see if a particular entry should be filtered or not param path return boolean in case the user wants to replace the file extension log parsers should call this method this is useful for regression test plans if a website is migrating from one platform to another and the file extension changes the filter provides an easy way to do it without spending a lot of time param text return string tell the filter when the parsing has reached the end of the log file and is about to begin again gives the filter a chance to adjust it s values if needed public interface log parser close the any streams or readers public void close logparser the method will parse the given number of lines pass 1 to parse the entire file if the end of the file is reached without parsing a line a 0 is returned if the method is subsequently called again it will restart parsing at the beginning param count return int we allow for filters so that users can simply point to an access log without having to clean it up this makes it significantly easier and reduces the amount of work plus i m lazy so going through a log file to clean it up is a bit tedious one example of this is using the filter to exclude any log entry that has a 505 response code param filter the method is provided to make it easy to dynamically create new classes using class new instance then the access log file is set using this method param source newinstance public interface parser status parse bytes byte bytes parsebytes status parse bytes byte bytes status parse string string content parsebytes parsestring status parse string string content status parse sample result sample result result parsestring parsesampleresult sampleresult public interface jvm memory get memory getmemory memory get memory void set memory memory mem getmemory setmemory public interface workers java util list get worker getworker public interface thread info int get max spare threads threadinfo getmaxsparethreads int get max spare threads void set max spare threads int value getmaxsparethreads setmaxsparethreads void set max spare threads int value int get min spare threads setmaxsparethreads getminsparethreads int get min spare threads void set min spare threads int value getminsparethreads setminsparethreads void set min spare threads int value int get max threads setminsparethreads getmaxthreads int get max threads void set max threads int value getmaxthreads setmaxthreads void set max threads int value int get current threads busy setmaxthreads getcurrentthreadsbusy int get current threads busy void set current threads busy int value getcurrentthreadsbusy setcurrentthreadsbusy void set current threads busy int value int get current thread count setcurrentthreadsbusy getcurrentthreadcount int get current thread count void set current thread count int value getcurrentthreadcount setcurrentthreadcount public interface status jvm get jvm getjvm jvm get jvm void set jvm jvm vm getjvm setjvm void set jvm jvm vm java util list get connector setjvm getconnector java util list get connector void add connector connector conn getconnector addconnector void add connector connector conn void set connector prefix string prefix addconnector setconnectorprefix void set connector prefix string prefix string get connector prefix setconnectorprefix getconnectorprefix public interface memory long get max getmax long get max void set max long value getmax setmax void set max long value long get free setmax getfree long get free void set free long value getfree setfree void set free long value long get total setfree gettotal long get total void set total long value gettotal settotal public interface worker int get request processing time getrequestprocessingtime int get request processing time void set request processing time int value getrequestprocessingtime setrequestprocessingtime void set request processing time int value long get request bytes sent setrequestprocessingtime getrequestbytessent long get request bytes sent void set request bytes sent long value getrequestbytessent setrequestbytessent void set request bytes sent long value java lang string get current query string setrequestbytessent getcurrentquerystring java lang string get current query string void set current query string java lang string value getcurrentquerystring setcurrentquerystring void set current query string java lang string value java lang string get remote addr setcurrentquerystring getremoteaddr java lang string get remote addr void set remote addr java lang string value getremoteaddr setremoteaddr void set remote addr java lang string value java lang string get current uri setremoteaddr getcurrenturi java lang string get current uri void set current uri java lang string value getcurrenturi setcurrenturi void set current uri java lang string value java lang string get stage setcurrenturi getstage java lang string get stage void set stage java lang string value getstage setstage void set stage java lang string value java lang string get virtual host setstage getvirtualhost java lang string get virtual host void set virtual host java lang string value getvirtualhost setvirtualhost void set virtual host java lang string value java lang string get protocol setvirtualhost getprotocol java lang string get protocol void set protocol java lang string value getprotocol setprotocol void set protocol java lang string value long get request bytes received setprotocol getrequestbytesreceived long get request bytes received void set request bytes received long value getrequestbytesreceived setrequestbytesreceived void set request bytes received long value java lang string get method setrequestbytesreceived getmethod java lang string get method void set method java lang string value getmethod setmethod public interface request info long get bytes received requestinfo getbytesreceived long get bytes received void set bytes received long value getbytesreceived setbytesreceived void set bytes received long value long get bytes sent setbytesreceived getbytessent long get bytes sent void set bytes sent long value getbytessent setbytessent void set bytes sent long value long get request count setbytessent getrequestcount long get request count void set request count long value getrequestcount setrequestcount void set request count long value long get error count setrequestcount geterrorcount long get error count void set error count long value geterrorcount seterrorcount void set error count long value int get max time seterrorcount getmaxtime int get max time void set max time int value getmaxtime setmaxtime void set max time int value int get processing time setmaxtime getprocessingtime int get processing time void set processing time int value getprocessingtime setprocessingtime public interface connector thread info get thread info threadinfo getthreadinfo thread info get thread info void set thread info thread info value threadinfo getthreadinfo setthreadinfo threadinfo void set thread info thread info value request info get request info setthreadinfo threadinfo requestinfo getrequestinfo request info get request info void set request info request info value requestinfo getrequestinfo setrequestinfo requestinfo void set request info request info value workers get workers setrequestinfo requestinfo getworkers workers get workers void set workers workers value getworkers setworkers void set workers workers value string get name setworkers getname string get name void set name string value getname setname public interface monitor listener public void add sample monitor model model monitorlistener addsample monitormodel public interface monitor gui listener void update gui monitor model event monitorguilistener updategui monitormodel void update gui monitor model event void update gui updategui monitormodel updategui public interface unit test manager your implementation will be handed the filename that was provided to all tests as a configuration file it can hold whatever properties you need to configure your system prior to the unit tests running param filename unittestmanager alltests the method is similar to get value at int int instead of int the row is an object param node param col return the value at the column getvalueat the method is similar to is cell editable int int instead of int the row is an object param node param col return if cell is editable iscelleditable the method is similar to is cell editable int int instead of int the row is an object param val param node param column iscelleditable public interface j labeled field public string get text jlabeledfield gettext public string get text public void set text string text gettext settext public void set text string text public void set label string p label settext setlabel plabel public void set label string p label public void add change listener change listener p change listener setlabel plabel addchangelistener changelistener pchangelistener public void add change listener change listener p change listener public list get component list addchangelistener changelistener pchangelistener getcomponentlist public interface hash tree traverser the tree traverses itself depth first calling add node for each object it encounters as it goes this is a callback method and should not be called except by a hash tree during traversal param node the node currently encountered param sub tree the hash tree under the node encountered hashtreetraverser addnode hashtree subtree hashtree indicates traversal has moved up a step and the visitor should remove the top node from its stack structure this is a callback method and should not be called except by a hash tree during traversal hashtree process path is called when a leaf is reached if a visitor wishes to generate lists of path elements to each leaf it should keep a stack data structure of nodes passed to it with add node and removing top items for every link subtract node call this is a callback method and should not be called except by a hash tree during traversal addnode subtractnode hashtree public interface parser control called by the parser to determine whether it should stop after last option parsed param last option code the code of last option parsed return return true to halt false to continue parsing parsercontrol lastoptioncode public interface visualizer this method is called by sampling thread to inform the visualizer about the arrival of a new sample this method is used to indicate a visualizer generates statistics return true if visualiser generates statistics public interface printable j component get printable component jcomponent getprintablecomponent public interface image visualizer public java awt image get image imagevisualizer getimage public interface named object public string get name namedobject getname public interface locale change listener public void locale changed locale change event event localechangelistener localechanged localechangeevent public interface timer extends serializable this method is called after a sampling process is done to know how much time the sampling thread has to wait until sampling again return the computed delay value public interface j meter thread monitor public void thread finished j meter thread thread jmeterthreadmonitor threadfinished jmeterthread public interface j meter property extends serializable cloneable comparable returns whether the property is a running version return boolean jmeterproperty the name of the property typically this should match the name that keys the property s location in the test elements map return string set the property name param name make the property a running version or turn it off as the running version a property that is made a running version will preserve the current state in such a way that it is retrievable by a future call to recover running version additionally a property that is a running version will resolve all functions prior to returning it s property value a non running version property will return functions as their uncompiled string representation param running version recoverrunningversion runningversion tell the property to revert to the state at the time set running version true was called setrunningversion take the given property object and merge it s value with the current property object for most property types this will simply be ignored but for collection properties and test element properties more complex behavior is required param prop public void merge in j meter property prop public int get int value mergein jmeterproperty getintvalue public int get int value public long get long value getintvalue getlongvalue public long get long value public double get double value getlongvalue getdoublevalue public double get double value public float get float value getdoublevalue getfloatvalue public float get float value public boolean get boolean value getfloatvalue getbooleanvalue public boolean get boolean value public string get string value getbooleanvalue getstringvalue public string get string value public object get object value getstringvalue getobjectvalue public object get object value public void set object value object value getobjectvalue setobjectvalue public void set object value object value public object clone setobjectvalue public interface property iterator public boolean has next propertyiterator hasnext public boolean has next public j meter property next hasnext jmeterproperty public j meter property next public void remove jmeterproperty notification that a new test element is about to be traversed param el notification that the test element is now done param el notification that a property is starting this could be a test element property or a map property depends on the context param key notification that a property is ending again this could be a test element or a map property dependig on the context param key public interface thread listener called just before the start of the thread see org apache jmeter threads j meter thread thread started threadlistener jmeterthread threadstarted called once for each thread at the end of a test see org apache jmeter threads j meter thread thread finished jmeterthread threadfinished n b comments originally only applied to test plans hence the name which can now not be easily changed public void add test element test element child addtestelement testelement public void add test element test element child public void set property string key string value addtestelement testelement setproperty public void set property string key string value public void set property string key string value string dflt setproperty setproperty public void set property string key string value string dflt public void set property string key boolean value setproperty setproperty public void set property string key boolean value public void set property string key boolean value boolean dflt setproperty setproperty public void set property string key boolean value boolean dflt public void set property string key int value setproperty setproperty public void set property string key int value public void set property string key int value int dflt setproperty setproperty check if enabled property is present and true defaults to true return true if element is enabled public boolean is enabled returns true or false whether the element is the running version public boolean is running version isenabled isrunningversion test whether a given property is only a temporary resident of the test element param property return boolean testelement indicate that the given property should be only a temporary property in the test element param property void testelement public void set temporary j meter property property return a property as a boolean value public boolean get property as boolean string key settemporary jmeterproperty getpropertyasboolean public boolean get property as boolean string key public boolean get property as boolean string key boolean default value getpropertyasboolean getpropertyasboolean defaultvalue public boolean get property as boolean string key boolean default value public long get property as long string key getpropertyasboolean defaultvalue getpropertyaslong public long get property as long string key public int get property as int string key getpropertyaslong getpropertyasint public int get property as int string key public int get property as int string key int default value getpropertyasint getpropertyasint defaultvalue public int get property as int string key int default value public float get property as float string key getpropertyasint defaultvalue getpropertyasfloat public float get property as float string key public double get property as double string key getpropertyasfloat getpropertyasdouble make the test element the running version or make it no longer the running version this tells the test element that it s current state must be retrievable by a call to recover running version it is kind of like making the test element read only but not as strict changes can be made and the element can be modified but the state of the element at the time of the call to set running version must be recoverable recoverrunningversion testelement setrunningversion tells the test element to return to the state it was in when make running version was called makerunningversion public void recover running version clear the test element of all data public void clear recoverrunningversion testelement see also clearable j metergui component public string get property as string string key jmeterguicomponent getpropertyasstring public string get property as string string key public string get property as string string key string default value getpropertyasstring getpropertyasstring defaultvalue sets and overwrites a property in the test element this call will be ignored if the test element is currently a running version testelement testelement given the name of the property returns the appropriate property from j meter if it is null a null property object will be returned jmeter nullproperty get a property iterator for the test elements properties return property iterator testelements propertyiterator public property iterator property iterator public void remove property string key propertyiterator propertyiterator removeproperty lifecycle methods public object clone public object clone convenient way to traverse a test element public void traverse test element traverser traverser testelementtraverser public void traverse test element traverser traverser return returns the thread context public j meter context get thread context testelementtraverser threadcontext jmetercontext getthreadcontext param thread context the thread context to set threadcontext threadcontext public void set thread context j meter context thread context return returns the thread name public string get thread name setthreadcontext jmetercontext threadcontext threadname getthreadname param thread name the thread name to set threadname threadname called by remove to determine if it is safe to remove the element the element can either clean itself up and return true or the element can return false return true if safe to remove the element public boolean can remove public string get name canremove getname public string get name public void set name string name getname setname public void set name string name public string get comment setname getcomment public string get comment public void set comment string comment getcomment setcomment public interface test listener p called just before the start of the test from the main engine thread this is before the test elements are cloned note that not all the test variables will have been set up at this point p p b n b test started and test ended are called from different threads b p see org apache jmeter engine standardj meter engine run testlistener teststarted testended standardjmeterengine p called just before the start of the test from the main engine thread this is before the test elements are cloned note that not all the test variables will have been set up at this point p p b n b test started and test ended are called from different threads b p see org apache jmeter engine standardj meter engine run teststarted testended standardjmeterengine p called once for all threads after the end of a test this will use the same element instances as at the start of the test p p b n b test started and test ended are called from different threads b p see org apache jmeter engine standardj meter engine stop test teststarted testended standardjmeterengine stoptest p called once for all threads after the end of a test this will use the same element instances as at the start of the test p p b n b test started and test ended are called from different threads b p see org apache jmeter engine standardj meter engine stop test teststarted testended standardjmeterengine stoptest each time through a thread group s test script an iteration event is fired for each thread this will be after the test elements have been cloned so in general the instance will not be the same as the ones the start end methods call param event public interface test cloneable extends cloneable public object clone testcloneable public interface remote sample listener extends java rmi remote public void test started throws remote exception remotesamplelistener teststarted remoteexception public void test started throws remote exception public void test started string host throws remote exception teststarted remoteexception teststarted remoteexception public void test started string host throws remote exception public void test ended throws remote exception teststarted remoteexception testended remoteexception public void test ended throws remote exception public void test ended string host throws remote exception testended remoteexception testended remoteexception this method is called remotely and fires a list of samples events recieved locally the function is to reduce network load when using remote testing param samples the list of sample events to be fired locally throws remote exception remoteexception public void process batch list samples throws remote exception a sample has started and stopped public void sample occurred sample event e throws remote exception processbatch remoteexception sampleoccurred sampleevent remoteexception public void sample occurred sample event e throws remote exception a sample has started public void sample started sample event e throws remote exception sampleoccurred sampleevent remoteexception samplestarted sampleevent remoteexception public void sample started sample event e throws remote exception a sample has stopped public void sample stopped sample event e throws remote exception samplestarted sampleevent remoteexception samplestopped sampleevent remoteexception public interface sample listener a sample has started and stopped public void sample occurred sample event e samplelistener sampleoccurred sampleevent public void sample occurred sample event e a sample has started public void sample started sample event e sampleoccurred sampleevent samplestarted sampleevent public void sample started sample event e a sample has stopped public void sample stopped sample event e samplestarted sampleevent samplestopped sampleevent public interface clearable clears the current data of the object public void clear data cleardata interrupt the current operation if possible return code true code if there was an operation to interrupt public interface sampler extends java io serializable test element obtains statistics about the given entry and packages the information into a sample result testelement sampleresult public interface sample sender the test ended public void test ended samplesender testended the test ended param host the host that the test ended on a sample occurred param e a sample event public interface post processor provides the post processor with a sample result object from which to extract values for use in future queries postprocessor postprocessor sampleresult public interface pre processor public void process preprocessor public interface j meter plugin public string get icon mappings jmeterplugin geticonmappings public string get icon mappings public string get resource bundles geticonmappings getresourcebundles public interface named tree node void set name string name namedtreenode setname void set name string name string get name setname getname void set name string name string get name void name changed setname getname namechanged public interface command public void do action action event e throws illegal user action exception doaction actionevent illegaluseractionexception public void do action action event e throws illegal user action exception public set get action names doaction actionevent illegaluseractionexception getactionnames sets the name of the j meter gui component the name of the component is used in the test tree as the name of the tree node param name the name of the component jmeter gets the name of the j meter gui component the name of the component is used in the test tree as the name of the tree node return the name of the component jmeter get the component s label this label is used in drop down lists that give the user the option of choosing one type of component in a list of many it should therefore be a descriptive name for the end user to see it must be unique to the class it is also used by help to find the appropriate location in the documentation normally get label resource should be overridden instead of this method the definition of this method in abstractj meter gui component is intended for general use see get label resource return gui label for the component getlabelresource abstractjmeterguicomponent getlabelresource get the component s resource name which get static label uses to derive the component s label in the local language the resource name is fixed and does not vary with the selected language normally this method should be overriden in preference to overriding get static label however where the resource name is not available or required get static label may be overridden instead return the resource name getstaticlabel getstaticlabel getstaticlabel get the component s document anchor name used by help to find the appropriate location in the documentation return document anchor ref for the component j meter test components are separated into a model and a gui representation the model holds the data and the gui displays it the gui class is responsible for knowing how to create and initialize with data the model class that it knows how to display and this method is called when new test elements are created return the test element object that the gui component represents jmeter gui components are responsible for populating test elements they create with the data currently held in the gui components this method should overwrite whatever data is currently in the test element as it is called after a user has filled out the form elements in the gui with new information param element the test element to modify testelements testelement testelement test gui elements can be disabled in which case they do not become part of the test when run return true if the element should be part of the test run false otherwise set whether this component is enabled param enabled true for enabled false for disabled when a user right clicks on the component in the test tree or selects the edit menu when the component is selected the component will be asked to return a j popup menu that provides all the options available to the user from this component return a j popup menu appropriate for the component jpopupmenu jpopupmenu the gui must be able to extract the data from the test element and update all gui fields to represent those data this method is called to allow j meter to show the user the gui that represents the test element s data param element the test element to configure testelement jmeter testelement this is the list of add menu categories this gui component will be available under for instance if this represents a controller then the menu factory controllers category should be in the returned collection when a user right clicks on a tree element and looks through the add menu which category your gui component shows up in is determined by which categories are returned by this method most gui s belong to only one category but it is possible for a component to exist in multiple categories return a collection of strings where each element is one of the constants defined in menu factory see org apache jmeter gui util menu factory menufactory menufactory menufactory sets the tree node which this component is associated with param node the tree node corresponding to this component clear the gui and return it to initial default values this is necessary because most gui classes are instantiated just once and re used for multiple test element objects and thus they need to be cleared between use public interface function given the previous sample result and the current sampler return a string to use as a replacement value for the function call assume set parameter was previously called this method must be threadsafe multiple threads will be using the same object sampleresult setparameter a collection of the parameters used to configure your function each parameter is a compound function and can be resolved by calling the execute method of the compound function which should be done at execution param parameters throws invalid variable exception compoundfunction compoundfunction invalidvariableexception return the name of your function convention is to prepend to the name ie regexfunction __ __regexfunction return a list of strings briefly describing each parameter your function takes please use j meter utils get res string resource name to grab a resource string otherwise your help text will be difficult to internationalize this list is not optional if you don t wish to write help you must at least return a list containing the correct number of blank strings one for each argument jmeterutils getresstring resource_name interface value transformer transform the given property and return the new version param property return the transformed property valuetransformer set the master function for the value transformer this handles converting strings to functions param master function masterfunction set the variable names and values used to reverse replace functions with strings and undo functions to raw values param vars public interface loop iteration listener public void iteration start loop iteration event iter event loopiterationlistener iterationstart loopiterationevent iterevent public interface j meter engine void configure hash tree test plan jmeterengine hashtree testplan void configure hash tree test plan void run test throws j meter engine exception hashtree testplan runtest jmeterengineexception void run test throws j meter engine exception void stop test runtest jmeterengineexception stoptest void stop test void reset stoptest void reset void set properties properties p setproperties void set properties properties p void exit setproperties public interface remotej meter engine extends remote void configure hash tree test tree string host throws remote exception remotejmeterengine hashtree testtree remoteexception void configure hash tree test tree string host throws remote exception void run test throws remote exception j meter engine exception hashtree testtree remoteexception runtest remoteexception jmeterengineexception void run test throws remote exception j meter engine exception void stop test throws remote exception runtest remoteexception jmeterengineexception stoptest remoteexception void stop test throws remote exception void reset throws remote exception stoptest remoteexception remoteexception void reset throws remote exception void set properties properties p throws remote exception remoteexception setproperties remoteexception void set properties properties p throws remote exception void exit throws remote exception setproperties remoteexception remoteexception public interface controller extends test element delivers the next sampler or null return org apache jmeter samplers sampler or null testelement indicates whether the controller is done delivering samplers for the rest of the test when the top level controller returns true to j meter thread the thread is complete return boolean jmeterthread controllers have to notify listeners of when they begin an iteration through their sub elements public void add iteration listener loop iteration listener listener called to initialize a controller at the beginning of a test iteration public void initialize additerationlistener loopiterationlistener used to replace the test execution tree usually by adding the subelements of the test element that is replacing the replaceable controller see org apache jorphan collections hash tree testelement replaceablecontroller hashtree compute the replacement tree param context add a configuration element to this one this allows config elements to combine and give a quot layered quot effect for example http config elements have properties for domain path method and parameters if element a has everything filled in but null for domain and element b is added which has only domain filled in then after adding b to a a will have the domain from b if a already had a domain then the correct behavior is for a to ignore the addition of element b param config the element to be added to this config element httpconfigelements configelement if your config element expects to be modified in the process of a test run and you want those modifications to carry over from sample to sample as in a cookie manager you want to save all cookies that get set throughout the test then return true for this method your config element will not be cloned for each sample if your config elements are more static in nature return false if in doubt return false return true if the element expects to be modified over the course of a test run boolean expects modification object clone expectsmodification public interface assertion returns the assertion result object encapsulating information about the success or failure of the assertion param response the sample result containing information about the sample duration success etc return the assertion result containing the information about whether the assertion passed or failed assertionresult sampleresult assertionresult public interface graph accum listener public void update gui sample result s graphaccumlistener updategui sampleresult public void update gui sample result s public void update gui updategui sampleresult updategui public interface accum listener public void update gui running sample s accumlistener updategui runningsample public interface model listener informs the visualizer that the model has changed public void update visualizer modellistener updatevisualizer public void update visualizer informs the visualizer that a message should be displayed public void display message string message string boolean is error updatevisualizer displaymessage messagestring iserror public interface graph listener public void update gui sample s graphlistener updategui public void update gui sample s public void update gui updategui updategui