Showing posts with label JAVA 8. Show all posts
Showing posts with label JAVA 8. Show all posts

Tuesday, April 14, 2015

JMETER load testing by code/ JMETER API implementation sample by java code

This tutorial attempts to explain the basic design, functionality and usage of the Jmeter, Jmeter is excellent tool used to perform load testing on the application, By using the jmeter GUI we can create the test samples for the request
according to our requirement and execute the samples with load of number of users.
As jmeter tool is fully developed by using JAVA, We can write the java code to do the same without using the GUI of the jmeter, Its not advisable to implement the java code for the load testing, its just a proof of concept to write the samples by java code using the jmeter libraries.
Jmeter as very good documentation/APIs, After going through the jmeter source code and other reference resources, wrote the following sample code.

Pre-prerequisites:



Prior to understand following code we must have basic knowledge of the how jmeter works.
Initially we need load the jmeter properties which will be used by jmeter classes/libraries in later stage of code
//JMeter Engine
StandardJMeterEngine jmeter = new StandardJMeterEngine();
//JMeter initialization (properties, log levels, locale, etc)
JMeterUtils.setJMeterHome(jmeterHome.getPath());
JMeterUtils.loadJMeterProperties(jmeterProperties.getPath());
JMeterUtils.initLogging();// you can comment this line out to see extra log messages of i.e. DEBUG level
JMeterUtils.initLocale();

1. Create "Test Plan" Object and JOrphan HashTree

//JMeter Test Plan, basically JOrphan HashTree
HashTree testPlanTree = new HashTree();
// Test Plan
TestPlan testPlan = new TestPlan("Create JMeter Script From Java Code");
testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName());
testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.getName());
testPlan.setUserDefinedVariables((Arguments) new ArgumentsPanel().createTestElement());

2. Samplers : Add "Http Sample" Object

Samplers tell JMeter to send requests to a server and wait for a response. They are processed in the order they appear in the tree. Controllers can be used to modify the number of repetitions of a sampler
// First HTTP Sampler - open uttesh.com
HTTPSamplerProxy examplecomSampler = new HTTPSamplerProxy();
examplecomSampler.setDomain("uttesh.com");
examplecomSampler.setPort(80);
examplecomSampler.setPath("/");
examplecomSampler.setMethod("GET");
examplecomSampler.setName("Open uttesh.com");
examplecomSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
examplecomSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());

3.Loop Controller

Loop Controller will execute the samples number times the loop iteration is declared.
// Loop Controller
LoopController loopController = new LoopController();
loopController.setLoops(1);
loopController.setFirst(true);
loopController.setProperty(TestElement.TEST_CLASS, LoopController.class.getName());
loopController.setProperty(TestElement.GUI_CLASS, LoopControlPanel.class.getName());
loopController.initialize();

4.Thread Group

Thread group elements are the beginning points of any test plan. All controllers and samplers must be under a thread group. Other elements, e.g. Listeners, may be placed directly under the test plan, in which case they will apply to all the thread groups. As the name implies, the thread group element controls the number of threads JMeter will use to execute your test.

// Thread Group
ThreadGroup threadGroup = new ThreadGroup();
threadGroup.setName("Sample Thread Group");
threadGroup.setNumThreads(1);
threadGroup.setRampUp(1);
threadGroup.setSamplerController(loopController);
threadGroup.setProperty(TestElement.TEST_CLASS, ThreadGroup.class.getName());
threadGroup.setProperty(TestElement.GUI_CLASS, ThreadGroupGui.class.getName());

5. Add sampler,controller..etc to test plan

// Construct Test Plan from previously initialized elements
testPlanTree.add(testPlan);
HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
threadGroupHashTree.add(examplecomSampler);
// save generated test plan to JMeter's .jmx file format
SaveService.saveTree(testPlanTree, new FileOutputStream("report\\jmeter_api_sample.jmx"));
above code will generate the jmeter script which we wrote from the code.

5. Add Summary and reports

//add Summarizer output to get test progress in stdout like:
// summary =      2 in   1.3s =    1.5/s Avg:   631 Min:   290 Max:   973 Err:     0 (0.00%)
Summariser summer = null;
String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
if (summariserName.length() > 0) {
    summer = new Summariser(summariserName);
}
// Store execution results into a .jtl file, we can save file as csv also
String reportFile = "report\\report.jtl";
String csvFile = "report\\report.csv";
ResultCollector logger = new ResultCollector(summer);
logger.setFilename(reportFile);
ResultCollector csvlogger = new ResultCollector(summer);
csvlogger.setFilename(csvFile);
testPlanTree.add(testPlanTree.getArray()[0], logger);
testPlanTree.add(testPlanTree.getArray()[0], csvlogger);

Finally Execute the test

// Run Test Plan
jmeter.configure(testPlanTree);
jmeter.run();

System.out.println("Test completed. See " + jmeterHome + slash + "report.jtl file for results");
System.out.println("JMeter .jmx script is available at " + jmeterHome + slash + "jmeter_api_sample.jmx");
System.exit(0);

Full Source Code of the POC is available on the GitHub click here
Simple source :

Generate JMX sample file by code and opened in jmeter UI.

Summary Report generated by code after test execution

Thursday, February 26, 2015

Java get system environment variable details

Get System environment variable details.

import java.util.Map;

/**
 *
 * @author Uttesh Kumar T.H.
 */
public class FindJdk {

    public static void main(String[] args) {
        Map<String, String> env = System.getenv();
        for (String envName : env.keySet()) {
            System.out.format("%s=%s%n",envName,env.get(envName));
        }
    }
}


Monday, February 23, 2015

JAVA8 Lambda part1


Lambda expressions are a new and important feature included in Java SE 8. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection. In addition, new concurrency features improve performance.

Lambda Expression Syntax
(Arguments)      (Arrow Token)  (Body)
(int x,int y)        ->    x+y

Arguments:
argument list is like normal method level parameters list, it can be no argument also. i.e.

() -> 121


it will return 121 value and no argument list.

Body:
body can be statement block or logical block with return statement.

more samples :

(String s) -> { System.out.println(s); }


block form just print the string.

a lambda could be represented as a comma-separated list of parameters, the –> symbol and the body. For example:

Arrays.asList( "Item1", "Item2", "Item3" ).forEach( e -> System.out.println( e ) );


Please notice the type of argument e is being inferred by the compiler. Alternatively, you may explicitly provide the type of the parameter.

Arrays.asList("Item1", "Item2", "Item3").forEach((String e) -> System.out.println(e));


If expression/processing in complex then add the brackets i.e.

Arrays.asList("Item1", "Item2", "Item3").forEach(e -> {
            System.out.print(e);
        });

String separator = ",";
Arrays.asList( "Item1", "Item2", "Item3" ).forEach( {
    ( String e ) -> System.out.print( e + separator ) });

lambda expression will return the value as well. i.e.

Arrays.asList( "Item1", "Item2", "Item3" ).sort( ( e1, e2 ) -> e1.compareTo( e2 ) );

 Arrays.asList( "Item1", "Item2", "Item3" ).sort( ( e1, e2 ) -> {
    int result = e1.compareTo( e2 );
    return result;
} );

Functional Interfaces:

a Functional Interface is an interface with just one abstract method declared in it.

java.lang.Runnable is an example of a Functional Interface. There is only one method void run() declared in Runnable interface. We use Anonymous inner classes to instantiate objects of functional interface. With Lambda expressions.

// Anonymous Runnable
     Runnable r = new Runnable(){
       
       @Override
       public void run(){
         System.out.println("Hello world old!");
      }

    };

// Lambda Runnable
     Runnable r = () -> System.out.println("Hello world new!");

Comparator Lambda expression



traditional compator sort
</hr>
Collections.sort(list, new Comparator<Person>() {
            public int compare(Person p1, Person p2) {
                return p1.getName().compareTo(p2.getName());
            }
        });

Lambda sort 
</hr>
Collections.sort(list, (Person p1, Person p2) -> p1.getName().compareTo(p2.getName()));
full sample





references
http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html


Thursday, February 19, 2015

Exciting Features In Java 8 That Will Change How We Code?

5 features that we feel an absolute must for you to know about.

1.Lambda expressions.
2.Parallel operations.
3.Java + JavaScript :)
4.New date / time APIs.
5.Concurrent accumulators

1.Lambda expressions

Lambda expressions have taken the programming world by storm in the last few years. Most modern languages have adopted them as a fundamental part of functional programming. JVM based languages such as Scala, Groovy and Clojure have integrated them as key part of the language. And now, Java 8 is joining in on the fun.

2.Parallel operations.

Java introduced a key concept into the language of internal iteration. Essentially as developers we’re used to use loop operations as one of the most basic programming idioms, right up there with if and else.
This enable operations carried out on long arrays such as sorting, filtering and mapping to be carried out in parallel by the framework.

ConcurrentMap> byGender = roster.parallelStream().collect(Collectors.groupingByConcurrent(Person::getGender))

here roster this a collection and by using the parallelStream() we are getting the person object by the gender and populating the map with gender as key and resulted collection as value.

3.Java + JavaScript :)

Java 8 is introducing a completely new JVM JavaScript engine – Nashorn. This means that the next time you’re looking to integrate JS into your backend, instead of setting up a node.js instance, you can simply use the JVM to execute the code. The added bonus here is the ability to have seamless interoperability between your Java and JavaScript code in-process, without having to use various IPC/RPC methods to bridge the gap.

4.New date / time APIs.

Java 8 implemented its own new date / time API from scratch. The good news is that unlike Calendar.getInstance(), the new APIs were designed with simplicity in mind, and clear operations to operate on manipulated values in both human readable and machine time formats.


5.Concurrent accumulators

One of the most common scenarios in concurrent programming is updating of numeric counters accessed by multiple threads. There have been many idioms to do this over the years, starting from synchronized blocks,read/write locks to AtomicInteger(s).

With Java 8 this problem is solved at the framework level with new concurrent accumulator classes that enable you to very efficiently increase / decrease the value of a counter in a thread safe manner.