TestNG – Plug with Eclipse ”; Previous Next To set up TestNG with Eclipse, follow the steps given below − Step 1: Download TestNG Archive Download the latest version of TestNG jar file from http://www.testng.org OS Archive name Windows testng-7.4.jar Linux testng-7.4.jar Mac testng-7.4.jar We assume you have copied the above JAR file in /work/testng folder. Step 2: Set Eclipse environment Open eclipse → right click on the project and go to property → Build Path → Configure Build Path and add the testng-7.4.jar in the libraries using Add External Jar button. We assume that your Eclipse has inbuilt TestNG plug-in; if it is not available, then please get the latest version using the update site. In your Eclipse IDE, select Help / Eclipse Marketplace. Search for Testng. You will get the TestNG in the list. Click on Install as shown below: Now, your Eclipse is ready for the development of TestNG test cases. Step 3: Verify TestNG Installation in Eclipse Create a project TestNGProject in Eclipse at any location. Create a class MessageUtil to test in the project. /* * 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 a test class TestNGExample in the project. import org.testng.Assert; import org.testng.annotations.Test; public class TestNGExample { String message = “Hello World”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { Assert.assertEquals(message,messageUtil.printMessage()); } } The project structure should be as follows − Finally, verify the output of the program by right-clicking on the program and running as TestNG. Verify the result. Print Page Previous Next Advertisements ”;
Category: Java
Spring MVC – Hello World Example ”; Previous Next The following example shows how to write a simple web based Hello World application using the Spring MVC Framework. To start with, let us have a working Eclipse IDE in place and follow the subsequent steps to develop a Dynamic Web Application using the Spring Web Framework. Step Description 1 Create a Dynamic Web Project with a name HelloWeb and create a package com.tutorialspoint under the src folder in the created project. 2 Drag and drop the following Spring and other libraries into the folder WebContent/WEB-INF/lib.. 3 Create a Java class HelloController under the com.tutorialspoint package. 4 Create Spring configuration files web.xml and HelloWeb-servlet.xml under the WebContent/WEB-INF folder. 5 Create a sub-folder with a name jsp under the WebContent/WEB-INFfolder. Create a view file hello.jsp under this sub-folder. 6 The final step is to create the content of the source and configuration files and export the application as explained below. HelloController.java package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.ui.ModelMap; @Controller @RequestMapping(“/hello”) public class HelloController{ @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } web.xml <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>/</url-pattern> </servlet-mapping> </web-app> HelloWeb-servlet.xml <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> hello.jsp <%@ page contentType = “text/html; charset = UTF-8″ %> <html> <head> <title>Hello World</title> </head> <body> <h2>${message}</h2> </body> </html> Following is the list of Spring and other libraries to be included in the web application. We can just drag these files and drop them in – WebContent/WEB-INF/lib folder. servlet-api-x.y.z.jar commons-logging-x.y.z.jar spring-aop-x.y.z.jar spring-beans-x.y.z.jar spring-context-x.y.z.jar spring-core-x.y.z.jar spring-expression-x.y.z.jar spring-webmvc-x.y.z.jar spring-web-x.y.z.jar Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat”s webapps folder. Now start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Now, try to access the URL − http://localhost:8080/HelloWeb/hello. If everything is fine with the Spring Web Application, we will see the following screen. You should note that in the given URL, HelloWeb is the application name and hello is the virtual subfolder, which we have mentioned in our controller using @RequestMapping(“/hello”). You can use direct root while mapping your URL using @RequestMapping(“/”), in this case you can access the same page using short URL http://localhost:8080/HelloWeb/, but it is advised to have different functionalities under different folders. Print Page Previous Next Advertisements ”;
Spring ORM – Update Project
Spring ORM – Update Project ”; Previous Next Let”s add the following classes in the project in the relevant packages. Employee class to be persisted in database. Employee.java package com.tutorialspoint.jpa.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = “Employees”) public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = “NAME”) private String name; @Column(name = “SALARY”) private double salary; @Column(name = “DESIGNATION”) private String designation; public Employee( ) { } public Employee(String name, double salary, String designation) { this.name = name; this.salary = salary; this.designation = designation; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } } Employee DAO class to do operations on database. EmployeeDao.java package com.tutorialspoint.jpa.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.springframework.stereotype.Repository; import com.tutorialspoint.jpa.entity.Employee; @Repository public class EmployeeDao { @PersistenceContext private EntityManager em; public void add(Employee employee) { em.persist(employee); } public List<Employee> listEmployees() { CriteriaQuery<Employee> criteriaQuery = em.getCriteriaBuilder().createQuery(Employee.class); @SuppressWarnings(“unused”) Root<Employee> root = criteriaQuery.from(Employee.class); return em.createQuery(criteriaQuery).getResultList(); } } Employee Service class to use Employee DAO class. EmployeeService.java package com.tutorialspoint.jpa.service; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.tutorialspoint.jpa.dao.EmployeeDao; import com.tutorialspoint.jpa.entity.Employee; @Service public class EmployeeService { @Autowired private EmployeeDao employeeDao; @Transactional public void add(Employee employee) { employeeDao.add(employee); } @Transactional() public List<Employee> listEmployees() { return employeeDao.listEmployees(); } } Application Configuration to be used by Spring framework. AppConfig.java package com.tutorialspoint.jpa; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScans; import org.springframework.context.annotation.Configuration; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalEntityManagerFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @ComponentScans(value = { @ComponentScan(“com.tutorialspoint.jpa.dao”), @ComponentScan(“com.tutorialspoint.jpa.service”) }) public class AppConfig { @Bean public LocalEntityManagerFactoryBean geEntityManagerFactoryBean() { LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean(); factoryBean.setPersistenceUnitName(“Hibernate_JPA”); return factoryBean; } @Bean public JpaTransactionManager geJpaTransactionManager() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(geEntityManagerFactoryBean().getObject()); return transactionManager; } } Main Application to run and test the functionalities. MainApp.java package com.tutorialspoint.jpa; import java.sql.SQLException; import java.util.List; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.tutorialspoint.jpa.entity.Employee; import com.tutorialspoint.jpa.service.EmployeeService; public class MainApp { public static void main(String[] args) throws SQLException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); EmployeeService employeeService = context.getBean(EmployeeService.class); employeeService.add(new Employee(“Julie”, 10000, “Technical Manager”)); employeeService.add(new Employee(“Robert”, 20000, “Senior Manager”)); employeeService.add(new Employee(“Anil”, 5000, “Software Engineer”)); // Get Persons List<Employee> employees = employeeService.listEmployees(); for (Employee employee : employees) { System.out.println(“Id : “+employee.getId()); System.out.println(“Name : “+employee.getName()); System.out.println(“Salary = “+employee.getSalary()); System.out.println(“Designation = “+employee.getDesignation()); System.out.println(); } context.close(); } } Print Page Previous Next Advertisements ”;
Spring MVC – Static Pages
Spring MVC – Static Pages Example ”; Previous Next The following example shows how to write a simple web based application using Spring MVC Framework, which can access static pages along with dynamic pages with the help of a <mvc:resources> tag. To begin with, let us have a working Eclipse IDE in place and adhere to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework. Step Description 1 Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create a Java class WebController under the com.tutorialspoint package. 3 Create a static file final.htm under jsp sub-folder. 4 Update the Spring configuration file HelloWeb-servlet.xml under the WebContent/WEB-INF folder as shown below. 5 The final step is to create the content of the source and configuration files and export the application, which is explained below. WebController.java package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class WebController { @RequestMapping(value = “/index”, method = RequestMethod.GET) public String index() { return “index”; } @RequestMapping(value = “/staticPage”, method = RequestMethod.GET) public String redirect() { return “redirect:/pages/final.htm”; } } HelloWeb-servlet.xml <?xml version = “1.0” encoding = “UTF-8”?> <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:xsi = ” http://www.w3.org/2001/XMLSchema-instance” xmlns:context = “http://www.springframework.org/schema/context” xmlns:mvc = “http://www.springframework.org/schema/mvc” xsi:schemaLocation = “http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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 id = “viewResolver” class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> <mvc:resources mapping = “/pages/**” location = “/WEB-INF/pages/” /> <mvc:annotation-driven/> </beans> Here, the <mvc:resources…./> tag is being used to map static pages. The mapping attribute must be an Ant pattern that specifies the URL pattern of an http requests. The location attribute must specify one or more valid resource directory locations having static pages including images, stylesheets, JavaScript, and other static content. Multiple resource locations may be specified using a comma-separated list of values. Following is the content of Spring view file WEB-INF/jsp/index.jsp. This will be a landing page; this page will send a request to access the staticPage service method, which will redirect this request to a static page available in WEB-INF/pages folder. index.jsp <%@taglib uri = “http://www.springframework.org/tags/form” prefix = “form”%> <html> <head> <title>Spring Landing Page</title> </head> <body> <h2>Spring Landing Pag</h2> <p>Click below button to get a simple HTML page</p> <form:form method = “GET” action = “/HelloWeb/staticPage”> <table> <tr> <td> <input type = “submit” value = “Get HTML Page”/> </td> </tr> </table> </form:form> </body> </html> final.htm <html> <head> <title>Spring Static Page</title> </head> <body> <h2>A simple HTML page</h2> </body> </html> Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat”s webapps folder. Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Now try to access the URL – http://localhost:8080/HelloWeb/index. If everything is fine with the Spring Web Application, we will see the following screen. Click on “Get HTML Page” button to access a static page mentioned in the staticPage service method. If everything is fine with your Spring Web Application, we will see the following screen. Print Page Previous Next Advertisements ”;
Spring MVC – Overview
Spring – MVC Framework Overview ”; Previous Next 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. These include – JSPs, HTML,
Spring Security – Discussion
Discuss Spring Security ”; Previous Next In this tutorial, we will learn about Spring Security Frameworks. We will start with the basics and go through the configuration of various frameworks to work with Spring Security. We will also do some handson coding to perform CRUD operation using Spring Security Frameworks. Print Page Previous Next Advertisements ”;
TestNG – Parameterized Test
TestNG – Parameterized Test ”; Previous Next Another interesting feature available in TestNG is parametric testing. In most cases, you”ll come across a scenario where the business logic requires a hugely varying number of tests. Parameterized tests allow developers to run the same test over and over again using different values. TestNG lets you pass parameters directly to your test methods in two different ways − With testng.xml With Data Providers Passing Parameters with testng.xml With this technique, you define the simple parameters in the testng.xml file and then reference those parameters in the source files. Let us have an example to demonstrate how to use this technique to pass parameters. Create Test Case Class Create a java test class, say, ParameterizedTest1.java. Add test method parameterTest() to your test class. This method takes a string as input parameter. Add the annotation @Parameters(“myName”) to this method. The parameter would be passed a value from testng.xml, which we will see in the next step. Create a java class file named ParameterizedTest1.java in /work/testng/src. import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class ParameterizedTest1 { @Test @Parameters(“myName”) public void parameterTest(String myName) { System.out.println(“Parameterized value is : ” + myName); } } 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 = “Suite1”> <test name = “test1”> <parameter name = “myName” value=”manisha”/> <classes> <class name = “ParameterizedTest1″ /> </classes> </test> </suite> We can also define the parameters at the <suite> level. Suppose we have defined myName at both <suite> and <test> levels. In such cases, regular scoping rules apply. It means that any class inside <test> tag will see the value of parameter defined in <test>, while the classes in the rest of the testng.xml file will see the value defined in <suite>. Compile the test case class using javac. /work/testng/src$ javac ParameterizedTest1.java Now, run testng.xml, which will run the parameterTest method. TestNG will try to find a parameter named myName first in the <test> tag, and then, if it can’t find it, it searches in the <suit> tag that encloses it. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. Parameterized value is : manisha =============================================== Suite1 Total tests run: 1, Failures: 0, Skips: 0 =============================================== TestNG will automatically try to convert the value specified in testng.xml to the type of your parameter. Here are the types supported − String int/Integer boolean/Boolean byte/Byte char/Character double/Double float/Float long/Long short/Short Passing Parameters with Dataproviders When you need to pass complex parameters or parameters that need to be created from Java (complex objects, objects read from a property file or a database, etc.), parameters can be passed using Dataproviders. A Data Provider is a method annotated with @DataProvider. This annotation has only one string attribute: its name. If the name is not supplied, the data provider’s name automatically defaults to the method’s name. A data provider returns an array of objects. The following examples demonstrate how to use data providers. The first example is about @DataProvider using Vector, String, or Integer as parameter, and the second example is about @DataProvider using object as parameter. Example 1 Here, the @DataProvider passes Integer and Boolean as parameter. Create Java class Create a java class called PrimeNumberChecker.java. This class checks if the number is prime. Create this class in /work/testng/src. public class PrimeNumberChecker { public Boolean validate(final Integer primeNumber) { for (int i = 2; i < (primeNumber / 2); i++) { if (primeNumber % i == 0) { return false; } } return true; } } Create Test Case Class Create a java test class, say, ParamTestWithDataProvider1.java in /work/testng/src. Define the method primeNumbers(), which is defined as a Data provider using the annotation. This method returns an array of objects. Add the test method testPrimeNumberChecker() to your test class. This method takes an Integer and Boolean as input parameters. This method validates if the parameter passed is a prime number. Add the annotation @Test(dataProvider = “test1”) to this method. The attribute dataProvider is mapped to “test1”. Following are the contents of ParamTestWithDataProvider1.java. import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ParamTestWithDataProvider1 { private PrimeNumberChecker primeNumberChecker; @BeforeMethod public void initialize() { primeNumberChecker = new PrimeNumberChecker(); } @DataProvider(name = “test1”) public static Object[][] primeNumbers() { return new Object[][] {{2, true}, {6, false}, {19, true}, {22, false}, {23, true}}; } // This test will run 4 times since we have 5 parameters defined @Test(dataProvider = “test1″) public void testPrimeNumberChecker(Integer inputNumber, Boolean expectedResult) { System.out.println(inputNumber + ” ” + expectedResult); Assert.assertEquals(expectedResult, primeNumberChecker.validate(inputNumber)); } } Create testng.xml Create a testng.xml /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 = “Suite1”> <test name = “test1”> <classes> <class name = “ParamTestWithDataProvider1″ /> </classes> </test> </suite> Compile the Test case class using javac. /work/testng/src$ javac ParamTestWithDataProvider1.java PrimeNumberChecker.java Now, run testng.xml. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. 2 true 6 false 19 true 22 false 23 true =============================================== Suite1 Total tests run: 5, Failures: 0, Skips: 0 =============================================== Example 2 Here, the @DataProvider passes Object as parameter. Create Java class Create a java class Bean.java, which is a simple object with get/set methods, in /work/testng/src. public class Bean { private String val; private int i; public Bean(String val, int i) { this.val = val; this.i = i; } public String getVal() { return val; } public void setVal(String val) { this.val = val; } public int getI() { return i; } public void setI(int i) { this.i = i; } } Create Test Case Class Create a java test class, say, ParamTestWithDataProvider2.java. Define the method primeNumbers(), which is defined as a data provider using annotation. This method returns an array of object. Add the test method testMethod() to your test class. This method takes an object bean as parameter. Add the annotation @Test(dataProvider = “test1”) to this method. The attribute dataProvider is mapped to “test1”. Create a java class file named ParamTestWithDataProvider2.java in /work/testng/src. import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public
Struts2 – Useful Resources
Struts 2 – Useful Resources ”; Previous Next The following resources contain additional information on Struts2. Please use them to get more in-depth knowledge on this topic. Useful Links on Struts 2 Apache Struts project − Apache”s Official site giving link on Struts material. Sun”s Site on JSP − Sun”s Official site giving link on JSP material. Sun”s Site on Servlets − Sun”s Official site giving link on Servlets material. JSP Engine – Tomcat − Apache Tomcat is an open source software implementation of the Java Servlet and JavaServer Pages technologies. MySQL Connector/J − MySQL Connector/J is the official JDBC driver for MySQL. The JavaTM Tutorials − The Java Tutorials are practical guides for programmers who want to use the Java programming language to create applications. JavaTM 2 SDK, Standard Edition − Official site for JavaTM 2 SDK, Standard Edition Free Java Download − Download Java for your desktop computer now! Sun Developer Network − Sun Microsystem”s official website listing down all the API documentation, latest Java Technologies, Books and other resource. Useful Books on Java and Struts To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;
Spring Boot – Google Cloud Platform ”; Previous Next Google Cloud Platform provides a cloud computing services that run the Spring Boot application in the cloud environment. In this chapter, we are going to see how to deploy the Spring Boot application in GCP app engine platform. First, download the Gradle build Spring Boot application from Spring Initializer page www.start.spring.io. Observe the following screenshot. Now, in build.gradle file, add the Google Cloud appengine plugin and appengine classpath dependency. The code for build.gradle file is given below − buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) classpath ”com.google.cloud.tools:appengine-gradle-plugin:1.3.3” } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” apply plugin: ”com.google.cloud.tools.appengine” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } Now, write a simple HTTP Endpoint and it returns the String success as shown − package com.tutorialspoint.appenginedemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class AppengineDemoApplication { public static void main(String[] args) { SpringApplication.run(AppengineDemoApplication.class, args); } @RequestMapping(value = “/”) public String success() { return “APP Engine deployment success”; } } Next, add the app.yml file under src/main/appengine directory as shown − runtime: java env: flex handlers: – url: /.* script: this field is required, but ignored Now, go to the Google Cloud console and click the Activate Google cloud shell at the top of the page. Now, move your source files and Gradle file into home directory of your google cloud machine by using google cloud shell. Now, execute the command gradle appengineDeploy and it will deploy your application into the Google Cloud appengine. Note − GCP should be billing enabled and before deploying your application into appengine, you should create appengine platform in GCP. It will take few minutes to deploy your application into GCP appengine platform. After build successful you can see the Service URL in console window. Now, hit the service URL and see the output. Google Cloud SQL To connect the Google Cloud SQL into your Spring Boot application, you should add the following properties into your application.properties file. JDBC URL Format jdbc:mysql://google/<DATABASE-NAME>?cloudSqlInstance = <GOOGLE_CLOUD_SQL_INSTANCE_NAME> &socketFactory = com.google.cloud.sql.mysql.SocketFactory&user = <USERNAME>&password = <PASSWORD> Note − The Spring Boot application and Google Cloud SQL should be in same GCP project. The application.properties file is given below. spring.dbProductService.driverClassName = com.mysql.jdbc.Driver spring.dbProductService.url = jdbc:mysql://google/PRODUCTSERVICE?cloudSqlInstance = springboot-gcp-cloudsql:asia-northeast1:springboot-gcp-cloudsql-instance&socketFactory = com.google.cloud.sql.mysql.SocketFactory&user = root&password = rootspring.dbProductService.username = root spring.dbProductService.password = root spring.dbProductService.testOnBorrow = true spring.dbProductService.testWhileIdle = true spring.dbProductService.timeBetweenEvictionRunsMillis = 60000 spring.dbProductService.minEvictableIdleTimeMillis = 30000 spring.dbProductService.validationQuery = SELECT 1 spring.dbProductService.max-active = 15 spring.dbProductService.max-idle = 10 spring.dbProductService.max-wait = 8000 YAML file users can add the below properties to your application.yml file. spring: datasource: driverClassName: com.mysql.jdbc.Driver url: “jdbc:mysql://google/PRODUCTSERVICE?cloudSqlInstance=springboot-gcp-cloudsql:asia-northeast1:springboot-gcp-cloudsql-instance&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=root&password=root” password: “root” username: “root” testOnBorrow: true testWhileIdle: true validationQuery: SELECT 1 max-active: 15 max-idle: 10 max-wait: 8000 Print Page Previous Next Advertisements ”;
Spring Boot – Batch Service
Spring Boot – Batch Service ”; Previous Next You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands as shown below − For Maven, you can use the command given below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the command as shown − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Run the JAR file by using the command given here − java –jar <JARFILE> Now, the application has started on the Tomcat port 8080 as shown. Now, hit the URL http://localhost:8080/ in your web browser and connect the web socket and send the greeting and receive the message. Batch Service is a process to execute more than one command in a single task. In this chapter, you are going to learn how to create batch service in a Spring Boot application. Let us consider an example where we are going to save the CSV file content into HSQLDB. To create a Batch Service program, we need to add the Spring Boot Starter Batch dependency and HSQLDB dependency in our build configuration file. Maven users can add the following dependencies in pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-batch</artifactId> </dependency> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> </dependency> Gradle users can add the following dependencies in build.gradle file. compile(“org.springframework.boot:spring-boot-starter-batch”) compile(“org.hsqldb:hsqldb”) Now, add the simple CSV data file under classpath resources – src/main/resources and name the file as file.csv as shown − William,John Mike, Sebastian Lawarance, Lime Next, write a SQL script for HSQLDB – under the classpath resource directory – request_fail_hystrix_timeout DROP TABLE USERS IF EXISTS; CREATE TABLE USERS ( user_id BIGINT IDENTITY NOT NULL PRIMARY KEY, first_name VARCHAR(20), last_name VARCHAR(20) ); Create a POJO class for USERS model as shown − package com.tutorialspoint.batchservicedemo; public class User { private String lastName; private String firstName; public User() { } public User(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString() { return “firstName: ” + firstName + “, lastName: ” + lastName; } } Now, create an intermediate processor to do the operations after the reading the data from the CSV file and before writing the data into SQL. package com.tutorialspoint.batchservicedemo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.item.ItemProcessor; public class UserItemProcessor implements ItemProcessor<User, User> { private static final Logger log = LoggerFactory.getLogger(UserItemProcessor.class); @Override public User process(final User user) throws Exception { final String firstName = user.getFirstName().toUpperCase(); final String lastName = user.getLastName().toUpperCase(); final User transformedPerson = new User(firstName, lastName); log.info(“Converting (” + user + “) into (” + transformedPerson + “)”); return transformedPerson; } } Let us create a Batch configuration file, to read the data from CSV and write into the SQL file as shown below. We need to add the @EnableBatchProcessing annotation in the configuration class file. The @EnableBatchProcessing annotation is used to enable the batch operations for your Spring Boot application. package com.tutorialspoint.batchservicedemo; import javax.sql.DataSource; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.launch.support.RunIdIncrementer; import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider; import org.springframework.batch.item.database.JdbcBatchItemWriter; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper; import org.springframework.batch.item.file.mapping.DefaultLineMapper; import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; @Configuration @EnableBatchProcessing public class BatchConfiguration { @Autowired public JobBuilderFactory jobBuilderFactory; @Autowired public StepBuilderFactory stepBuilderFactory; @Autowired public DataSource dataSource; @Bean public FlatFileItemReader<User> reader() { FlatFileItemReader<User> reader = new FlatFileItemReader<User>(); reader.setResource(new ClassPathResource(“file.csv”)); reader.setLineMapper(new DefaultLineMapper<User>() { { setLineTokenizer(new DelimitedLineTokenizer() { { setNames(new String[] { “firstName”, “lastName” }); } }); setFieldSetMapper(new BeanWrapperFieldSetMapper<User>() { { setTargetType(User.class); } }); } }); return reader; } @Bean public UserItemProcessor processor() { return new UserItemProcessor(); } @Bean public JdbcBatchItemWriter<User> writer() { JdbcBatchItemWriter<User> writer = new JdbcBatchItemWriter<User>(); writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<User>()); writer.setSql(“INSERT INTO USERS (first_name, last_name) VALUES (:firstName, :lastName)”); writer.setDataSource(dataSource); return writer; } @Bean public Job importUserJob(JobCompletionNotificationListener listener) { return jobBuilderFactory.get(“importUserJob”).incrementer( new RunIdIncrementer()).listener(listener).flow(step1()).end().build(); } @Bean public Step step1() { return stepBuilderFactory.get(“step1”).<User, User>chunk(10).reader(reader()).processor(processor()).writer(writer()).build(); } } The reader() method is used to read the data from the CSV file and writer() method is used to write a data into the SQL. Next, we will have to write a Job Completion Notification Listener class – used to notify after the Job completion. package com.tutorialspoint.batchservicedemo; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.listener.JobExecutionListenerSupport; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Component; @Component public class JobCompletionNotificationListener extends JobExecutionListenerSupport { private static final Logger log = LoggerFactory.getLogger(JobCompletionNotificationListener.class); private final JdbcTemplate jdbcTemplate; @Autowired public JobCompletionNotificationListener(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public void afterJob(JobExecution jobExecution) { if (jobExecution.getStatus() == BatchStatus.COMPLETED) { log.info(“!!! JOB FINISHED !! It”s time to verify the results!!”); List<User> results = jdbcTemplate.query( “SELECT first_name, last_name FROM USERS”, new RowMapper<User>() { @Override public User mapRow(ResultSet rs, int row) throws SQLException { return new User(rs.getString(1), rs.getString(2)); } }); for (User person : results) { log.info(“Found <” + person + “> in the database.”); } } } } Now, create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands. For Maven, use the command as shown − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the command as shown − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Run the JAR file by using the command given here − java –jar <JARFILE> You can see the output in console window as shown − Print Page Previous Next Advertisements ”;