TestNG – Parallel Execution

TestNG – Parallel Execution ”; Previous Next TestNG allows to run tests parallelly or in separate threads in following ways: Parallel suites: If you are running several suite files (e.g. testng1.xml testng2.xml”), and you want each of these suites to be run in a separate thread. Use the following command line flag to specify the size of a thread pool: java org.testng.TestNG -suitethreadpoolsize 3 testng1.xml testng2.xml testng3.xml Parallel tests, classes and methods: Use parallel attribute on the <suite> tag respectively (for methods,test,classes, instances). <suite name=”My suite” parallel=”methods” thread-count=”5″> <suite name=”My suite” parallel=”tests” thread-count=”5″> <suite name=”My suite” parallel=”classes” thread-count=”5″> <suite name=”My suite” parallel=”instances” thread-count=”5″> Parallel testing is used heavily with Selenium because of the importance of cross-browser testing. With so many browsers in market today with a different version, create a browser matrix and run the tests parallelly. This will save us lot of time and other resources. Advantages and Disadvantages Following are some of the advantages of parallel testing using TestNG: It reduces time Allows multi-threaded tests Following are some of the disadvantages of parallel testing using TestNG Fails on dependent modules – Most of the times the tests are inter-dependent, hence failing chances are more. Program flow sequence – The tester should be well aware of the program flow to create parallel testing modules. Create Test Case Class Let us see an example to run test methods parallelly. Create a java class, say, TestParallel.java in /work/testng/src. import org.testng.annotations.Test; public class TestParallel { @Test public void method1() { System.out.println(“Inside method1()”); //Assert.assertEquals(message, messageUtil.printMessage()); } @Test public void method2() { System.out.println(“Inside method2()”); //Assert.assertEquals(message, messageUtil.printMessage()); } } The preceding test class contains two test methods which will run in separate threads. Create testng.xml Create testng.xml in /work/testng/src to execute test case(s). <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd”> <suite name = “Parallel Testing Suite”> <test name = “Parallel Tests” parallel = “methods”> <classes> <class name = “TestParallel” /> </classes> </test> </suite> Compile the TestParallel class using javac. /work/testng/src$ javac TestParallel.java Now, run testng.xml. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. Inside method1() Inside method2() =============================================== Parallel Testing Suite Total tests run: 2, Passes: 2, Failures: 0, Skips: 0 =============================================== Print Page Previous Next Advertisements ”;

Spring DI – Autowiring

Spring DI – Autowiring ”; Previous Next You have learnt how to declare beans using the <bean> element and inject <bean> using <constructor-arg> and <property> elements in XML configuration file. The Spring container can autowire relationships between collaborating beans without using <constructor-arg> and <property> elements, which helps cut down on the amount of XML configuration you write for a big Spring-based application. Autowiring Modes Following are the autowiring modes, which can be used to instruct the Spring container to use autowiring for dependency injection. You use the autowire attribute of the <bean/> element to specify autowire mode for a bean definition. Sr.No Mode & Description 1 no This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter. 2 byName Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file. 3 byType Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown. 4 constructor Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised. 5 autodetect Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType. You can use byType or constructor autowiring mode to wire arrays and other typed-collections. Limitations with autowiring Autowiring works best when it is used consistently across a project. If autowiring is not used in general, it might be confusing for developers to use it to wire only one or two bean definitions. Though, autowiring can significantly reduce the need to specify properties or constructor arguments but you should consider the limitations and disadvantages of autowiring before using them. Sr.No. Limitations & Description 1 Overriding possibility You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring. 2 Primitive data types You cannot autowire so-called simple properties such as primitives, Strings, and Classes. 3 Confusing nature Autowiring is less exact than explicit wiring, so if possible prefer using explict wiring. Print Page Previous Next Advertisements ”;

Spring MVC – Discussion

Discuss Spring MVC ”; Previous Next Spring MVC Framework is an open source Java platform that provides comprehensive infrastructure support for developing robust Java based Web applications very easily and very rapidly. Spring Framework was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003. This tutorial is written based on the Spring Framework Version 4.1.6 released in March 2015 Print Page Previous Next Advertisements ”;

Spring MVC – Quick Guide

Spring MVC – Quick Guide ”; Previous Next Spring – MVC Framework Overview The Spring Web MVC framework provides a model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The Model encapsulates the application data and in general, they will consist of POJO. The View is responsible for rendering the model data and in general, it generates HTML output that the client”s browser can interpret. The Controller is responsible for processing User Requests and Building Appropriate Model and passes it to the view for rendering. The DispatcherServlet The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. The request processing workflow of the Spring Web MVC DispatcherServlet is shown in the following illustration. Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet − After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller. The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet. The DispatcherServlet will take help from ViewResolver to pick up the defined view for the request. Once view is finalized, The DispatcherServlet passes the model data to the view, which is finally rendered, on the browsers. All the above-mentioned components, i.e. HandlerMapping, Controller and ViewResolver are parts of WebApplicationContext, which is an extension of the plain ApplicationContext with some extra features necessary for web applications. Required Configuration We need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the web.xml file. The following is an example to show declaration and mapping for HelloWeb DispatcherServlet − <web-app id = “WebApp_ID” version = “2.4” xmlns = “http://java.sun.com/xml/ns/j2ee” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”> <display-name>Spring MVC Application</display-name> <servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>*.jsp</url-pattern> </servlet-mapping> </web-app> The web.xml file will be kept in the WebContent/WEB-INF directory of your web application. Upon initialization of the HelloWeb DispatcherServlet, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application”s WebContent/WEB-INF directory. In this case, our file will be HelloWeb-servlet.xml. Next, the <servlet-mapping> tag indicates which URLs will be handled by which DispatcherServlet. Here, all the HTTP requests ending with .jsp will be handled by the HelloWeb DispatcherServlet. If you do not want to go with the default filename as [servlet-name]-servlet.xml and default location as WebContent/WEB-INF, you can customize this file name and location by adding the servlet listener ContextLoaderListener in your web.xml file as follows − <web-app…> <!——– DispatcherServlet definition goes here—–> …. <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/HelloWeb-servlet.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app> Now, let us check the required configuration for HelloWeb-servlet.xml file, placed in your web application”s WebContent/WEB-INF directory. <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:context = “http://www.springframework.org/schema/context” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = ” http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”> <context:component-scan base-package = “com.tutorialspoint” /> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> </beans> Following are some important points about HelloWeb-servlet.xml file − The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope. The <context:component-scan…> tag will be used to activate the Spring MVC annotation scanning capability, which allows to make use of annotations like @Controller and @RequestMapping, etc. The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above-defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp. Let us now understand how to create the actual components i.e., Controller, Model and View. Defining a Controller The DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The @Controller annotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method. @Controller @RequestMapping(“/hello”) public class HelloController{ @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } The @Controller annotation defines the class as a Spring MVC controller. Here, the first usage of @RequestMapping indicates that all handling methods on this controller are relative to the /hello path. The next annotation @RequestMapping (method = RequestMethod.GET) is used to declare the printHello() method as the controller”s default service method to handle HTTP GET request. We can define another method to handle any POST request at the same URL. We can also write the above controller in another form, where we can add additional attributes in the @RequestMapping as follows − @Controller public class HelloController{ @RequestMapping(value = “/hello”, method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } The value attribute indicates the URL to which the handler method is mapped and the method attribute defines the service method to handle the HTTP GET request. Following are some important points to be noted regarding the controller defined above − You will define the required business logic inside a service method. You can call another method inside this method as per the requirement. Based on the business logic defined, you will create a model within this method. You can set different model attributes and these attributes will be accessed by the view to present the result. This example creates a model with its attribute “message”. A defined service method can return a String, which contains the name of the view to be used to render the model. This example returns “hello” as the logical view name. Creating JSP Views Spring MVC supports many types of views for different presentation technologies.

Struts2 – Ajax Tags

Struts 2 – The Ajax Tags ”; Previous Next Struts uses the DOJO framework for the AJAX tag implementation. First of all, to proceed with this example, you need to add struts2-dojo-plugin-2.2.3.jar to your classpath. You can get this file from the lib folder of your struts2 download (C:struts-2.2.3allstruts-2.2.3libstruts2-dojo-plugin-2.2.3.jar) For this exercies, let us modify HelloWorld.jsp as follows − <%@ page contentType = “text/html; charset = UTF-8″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <%@ taglib prefix = “sx” uri = “/struts-dojo-tags”%> <html> <head> <title>Hello World</title> <s:head /> <sx:head /> </head> <body> <s:form> <sx:autocompleter label = “Favourite Colour” list = “{”red”,”green”,”blue”}” /> <br /> <sx:datetimepicker name = “deliverydate” label = “Delivery Date” displayformat = “dd/MM/yyyy” /> <br /> <s:url id = “url” value = “/hello.action” /> <sx:div href=”%{#url}” delay=”2000″> Initial Content </sx:div> <br/> <sx:tabbedpanel id = “tabContainer”> <sx:div label = “Tab 1”>Tab 1</sx:div> <sx:div label = “Tab 2″>Tab 2</sx:div> </sx:tabbedpanel> </s:form> </body> </html> When we run the above example, we get the following output − Let us now go through this example one step at a time. First thing to notice is the addition of a new tag library with the prefix sx. This (struts-dojo-tags) is the tag library specifically created for the ajax integration. Then inside the HTML head we call the sx:head. This initializes the dojo framework and makes it ready for all AJAX invocations within the page. This step is important – your ajax calls will not work without the sx:head being initialized. First we have the autocompleter tag. The autocompleter tag looks pretty much like a select box. It is populated with the values red, green and blue. But the different between a select box and this one is that it auto completes. That is, if you start typing in gr, it will fill it with “green”. Other than that this tag is very much similar to the s:select tag which we covered earlier. Next, we have a date time picker. This tag creates an input field with a button next to it. When the button is pressed, a popup date time picker is displayed. When the user selects a date, the date is filled into the input text in the format that is specified in the tag attribute. In our example, we have specified dd/MM/yyyy as the format for the date. Next we create a url tag to the system.action file which we created in the earlier exercises. It doesn”t have to be the system.action – it could be any action file that you created earlier. Then we have a div with the hyperlink set to the url and delay set to 2 seconds. What happens when you run this is, the “Initial Content” will be displayed for 2 seconds, then the div”s content will be replaced with the contents from the hello.action execution. Finally we have a simple tab panel with two tabs. The tabs are divs themseleves with the labels Tab 1 and Tab2. It should be worth noting that the AJAX tag integration in Struts is still a work in progress and the maturity of this integration is slowly increasing with every release. Print Page Previous Next Advertisements ”;

Example – Formatted TextFields

Swing Examples – Formatted TextFields ”; Previous Next Learn how to play with Formatted TextFields in Swing UI programming. Here are most commonly used examples − How to create a masked Text field in Swing? How to use JFormattedTextField in Swing? How to use Percentage format in a Text Box in Swing? How to use Currency format in a Text Box in Swing? How to use Date Format in a Text Box in Swing? Print Page Previous Next Advertisements ”;

Example – Dialogs

Swing Examples – Dialogs ”; Previous Next Learn how to play with Dialogs in Swing UI programming. Here are most commonly used examples − How to show a simple message alert with Ok button in Swing? How to show a warning message dialog in Swing? How to show an error message dialog in Swing? How to show an message dialog with no icon in Swing? How to show an message dialog with custom icon in Swing? How to show a confirm dialog with Yes, No and Cancel option in Swing? How to show a confirm dialog with Yes, No option in Swing? How to show a confirm dialog with Custom texts on Buttons in Swing? How to get user”s input from a list in a input dialog in Swing? How to get user”s input from a text box in a input dialog in Swing? How to create a modal dialog in Swing? How to create a non-modal dialog in Swing? Print Page Previous Next Advertisements ”;

Example – File Choosers

Swing Examples – File Choosers ”; Previous Next Learn how to play with File Choosers in Swing UI programming. Here are most commonly used examples − How to show a open file dialog in Swing? How to show a open file dialog to select multiple files in Swing? How to show a file chooser to select only images in Swing? How to show a file chooser to select directory only in Swing? How to show a file chooser to select both file and directory in Swing? How to show a save file dialog in Swing? Print Page Previous Next Advertisements ”;

Spring SpEL – Logical Operators

Spring SpEL – Logical Operators ”; Previous Next SpEL expression supports logical operators like AND, OR and NOT. Following example shows the various use cases. Example Let”s update the project created in Spring SpEL – Create Project chapter. We”re adding/updating following files − MainApp.java − Main application to run and test. Here is the content of MainApp.java file − package com.tutorialspoint; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import org.springframework.expression.EvaluationContext; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; public class MainApp { public static void main(String[] args) throws ParseException { ExpressionParser parser = new SpelExpressionParser(); // evaluates to true boolean result = parser.parseExpression(“true and true”).getValue(Boolean.class); System.out.println(result); // evaluates to true result = parser.parseExpression(“true or false”).getValue(Boolean.class); System.out.println(result); // evaluates to false result = parser.parseExpression(“!true”).getValue(Boolean.class); System.out.println(result); } } Output true true false Print Page Previous Next Advertisements ”;

TestNG – Executing Tests

TestNG – Executing Tests ”; Previous Next The test cases are executed using TestNG class. This class is the main entry point for running tests in the TestNG framework. Users can create their own TestNG object and invoke it in many different ways such as − On an existing testng.xml. On a synthetic testng.xml, created entirely from Java. By directly setting the test classes. You can also define which groups to include or exclude, assign parameters, etc. The command line parameters are − -d outputdir: specify the output directory. -testclass class_name: specifies one or several class names. -testjar jar_name: specifies the jar containing the tests. -sourcedir src1;src2: ; separated list of source directories (used only when javadoc annotations are used). -target -groups -testrunfactory -listener We will create the TestNG object an existing testng.xml in our example below. Create a Class Create a java class to be tested, say, MessageUtil.java in /work/testng/src. /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message) { this.message = message; } // prints the message public String printMessage() { System.out.println(message); return message; } } Create Test Case Class Create a java test class, say, SampleTest.java. Add a test method testPrintMessage() to your test class. Add an Annotation @Test to method testPrintMessage(). Implement the test condition and check the condition using assertEquals API of TestNG. Create a java class file called SampleTest.java in /work/testng/src. import org.testng.Assert; import org.testng.annotations.Test; public class SampleTest { String message = “Hello World”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { Assert.assertEquals(message, messageUtil.printMessage()); } } Create testng.xml Next, let”s create testng.xml file in /work/testng/src, to execute test case(s). This file captures your entire testing in XML. This file makes it easy to describe all your test suites and their parameters in one file, which you can check in your code repository or e-mail to coworkers. It also makes it easy to extract subsets of your tests or split several runtime configurations (e.g., testngdatabase.xml would run only tests that exercise your database). <?xml version = “1.0” encoding = “UTF-8”?> <suite name = “Sample test Suite”> <test name = “Sample test”> <classes> <class name = “SampleTest” /> </classes> </test> </suite> Compile the test case using javac. /work/testng/src$ javac MessageUtil.java SampleTest.java Now, run the testng.xml, which will run the test case defined in <test> tag. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. Hello World =============================================== Sample test Suite Total tests run: 1, Failures: 0, Skips: 0 =============================================== Print Page Previous Next Advertisements ”;