Spring Boot – OAuth2 with JWT ”; Previous Next In this chapter, you will learn in detail about Spring Boot Security mechanisms and OAuth2 with JWT. Authorization Server Authorization Server is a supreme architectural component for Web API Security. The Authorization Server acts a centralization authorization point that allows your apps and HTTP endpoints to identify the features of your application. Resource Server Resource Server is an application that provides the access token to the clients to access the Resource Server HTTP Endpoints. It is collection of libraries which contains the HTTP Endpoints, static resources, and Dynamic web pages. OAuth2 OAuth2 is an authorization framework that enables the application Web Security to access the resources from the client. To build an OAuth2 application, we need to focus on the Grant Type (Authorization code), Client ID and Client secret. JWT Token JWT Token is a JSON Web Token, used to represent the claims secured between two parties. You can learn more about the JWT token at www.jwt.io/. Now, we are going to build an OAuth2 application that enables the use of Authorization Server, Resource Server with the help of a JWT Token. You can use the following steps to implement the Spring Boot Security with JWT token by accessing the database. First, we need to add the following dependencies in our build configuration file. Maven users can add the following dependencies in your pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-jwt</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> Gradle users can add the following dependencies in the build.gradle file. compile(”org.springframework.boot:spring-boot-starter-security”) compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) testCompile(”org.springframework.security:spring-security-test”) compile(“org.springframework.security.oauth:spring-security-oauth2″) compile(”org.springframework.security:spring-security-jwt”) compile(“org.springframework.boot:spring-boot-starter-jdbc”) compile(“com.h2database:h2:1.4.191”) where, Spring Boot Starter Security − Implements the Spring Security Spring Security OAuth2 − Implements the OAUTH2 structure to enable the Authorization Server and Resource Server. Spring Security JWT − Generates the JWT Token for Web security Spring Boot Starter JDBC − Accesses the database to ensure the user is available or not. Spring Boot Starter Web − Writes HTTP endpoints. H2 Database − Stores the user information for authentication and authorization. The complete build configuration file is given below. <?xml version = “1.0” encoding = “UTF-8”?> <project xmlns = “http://maven.apache.org/POM/4.0.0” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>websecurityapp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>websecurityapp</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath /> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-jwt</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Gradle – build.gradle buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-security”) compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) testCompile(”org.springframework.security:spring-security-test”) compile(“org.springframework.security.oauth:spring-security-oauth2″) compile(”org.springframework.security:spring-security-jwt”) compile(“org.springframework.boot:spring-boot-starter-jdbc”) compile(“com.h2database:h2:1.4.191”) } Now, in the main Spring Boot application, add the @EnableAuthorizationServer and @EnableResourceServer annotation to act as an Auth server and Resource Server in the same application. Also, you can use the following code to write a simple HTTP endpoint to access the API with Spring Security by using JWT Token. package com.tutorialspoint.websecurityapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @EnableAuthorizationServer @EnableResourceServer @RestController public class WebsecurityappApplication { public static void main(String[] args) { SpringApplication.run(WebsecurityappApplication.class, args); } @RequestMapping(value = “/products”) public String getProductName() { return “Honey”; } } Use the following code to define the POJO class to store the User information for authentication. package com.tutorialspoint.websecurityapp; import java.util.ArrayList; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; public class UserEntity { private String username; private String password; private Collection<GrantedAuthority> grantedAuthoritiesList = new ArrayList<>(); public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Collection<GrantedAuthority> getGrantedAuthoritiesList() { return grantedAuthoritiesList; } public void setGrantedAuthoritiesList(Collection<GrantedAuthority> grantedAuthoritiesList) { this.grantedAuthoritiesList = grantedAuthoritiesList; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } Now, use the following code and define the CustomUser class that extends the org.springframework.security.core.userdetails.User class for Spring Boot authentication. package com.tutorialspoint.websecurityapp; import org.springframework.security.core.userdetails.User; public class CustomUser extends User { private static final long serialVersionUID = 1L; public CustomUser(UserEntity user) { super(user.getUsername(), user.getPassword(), user.getGrantedAuthoritiesList()); } } You can create the @Repository class to read the User information from the database and send it to the Custom user service and also add the granted authority “ROLE_SYSTEMADMIN”. package com.tutorialspoint.websecurityapp; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.stereotype.Repository; @Repository public class OAuthDao { @Autowired private JdbcTemplate jdbcTemplate; public UserEntity getUserDetails(String username) { Collection<GrantedAuthority> grantedAuthoritiesList = new ArrayList<>(); String userSQLQuery = “SELECT * FROM USERS WHERE USERNAME=?”; List<UserEntity> list = jdbcTemplate.query(userSQLQuery, new String[] { username }, (ResultSet rs, int rowNum) -> { UserEntity user = new UserEntity(); user.setUsername(username); user.setPassword(rs.getString(“PASSWORD”)); return user; }); if (list.size() > 0) { GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(“ROLE_SYSTEMADMIN”); grantedAuthoritiesList.add(grantedAuthority); list.get(0).setGrantedAuthoritiesList(grantedAuthoritiesList); return list.get(0); } return null; } } You can create a Custom User detail service class that extends the org.springframework.security.core.userdetails.UserDetailsService to call the DAO repository class as shown. package com.tutorialspoint.websecurityapp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service public class CustomDetailsService implements UserDetailsService { @Autowired OAuthDao oauthDao; @Override public CustomUser loadUserByUsername(final String username) throws UsernameNotFoundException { UserEntity userEntity = null; try { userEntity = oauthDao.getUserDetails(username); CustomUser customUser = new CustomUser(userEntity); return customUser; } catch (Exception e) { e.printStackTrace(); throw new UsernameNotFoundException(“User ” + username + ” was not found in the database”); } } } Next, create a @configuration class to enable the Web Security, defining the Password encoder (BCryptPasswordEncoder), and defining the AuthenticationManager bean. The Security configuration class should extend WebSecurityConfigurerAdapter class. package com.tutorialspoint.websecurityapp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
Category: Java
Spring Boot – Google OAuth2 Sign-In ”; Previous Next In this chapter, we are going to see how to add the Google OAuth2 Sign-In by using Spring Boot application with Gradle build. First, add the Spring Boot OAuth2 security dependency in your build configuration file and your build configuration file is given below. buildscript { ext { springBootVersion = ”1.5.8.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint.projects” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter”) testCompile(”org.springframework.boot:spring-boot-starter-test”) compile(”org.springframework.security.oauth:spring-security-oauth2”) compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } Now, add the HTTP Endpoint to read the User Principal from the Google after authenticating via Spring Boot in main Spring Boot application class file as given below − package com.tutorialspoint.projects.googleservice; import java.security.Principal; 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 GoogleserviceApplication { public static void main(String[] args) { SpringApplication.run(GoogleserviceApplication.class, args); } @RequestMapping(value = “/user”) public Principal user(Principal principal) { return principal; } } Now, write a Configuration file to enable the OAuth2SSO for web security and remove the authentication for index.html file as shown − package com.tutorialspoint.projects.googleservice; import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableOAuth2Sso public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf() .disable() .antMatcher(“/**”) .authorizeRequests() .antMatchers(“/”, “/index.html”) .permitAll() .anyRequest() .authenticated(); } } Next, add the index.html file under static resources and add the link to redirect into user HTTP Endpoint to read the Google user Principal as shown below − <!DOCTYPE html> <html> <head> <meta charset = “ISO-8859-1”> <title>Insert title here</title> </head> <body> <a href = “user”>Click here to Google Login</a> </body> </html> Note − In Google Cloud console – Enable the Gmail Services, Analytics Services and Google+ service API(s). Then, go the Credentials section and create a credentials and choose OAuth Client ID. Next, provide a Product Name in OAuth2 consent screen. Next, choose the Application Type as “Web application”, provide the Authorized JavaScript origins and Authorized redirect URIs. Now, your OAuth2 Client Id and Client Secret is created. Next, add the Client Id and Client Secret in your application properties file. security.oauth2.client.clientId = <CLIENT_ID> security.oauth2.client.clientSecret = <CLIENT_SECRET> security.oauth2.client.accessTokenUri = https://www.googleapis.com/oauth2/v3/token security.oauth2.client.userAuthorizationUri = https://accounts.google.com/o/oauth2/auth security.oauth2.client.tokenName = oauth_token security.oauth2.client.authenticationScheme = query security.oauth2.client.clientAuthenticationScheme = form security.oauth2.client.scope = profile email security.oauth2.resource.userInfoUri = https://www.googleapis.com/userinfo/v2/me security.oauth2.resource.preferTokenInfo = false Now, you can create an executable JAR file, and run the Spring Boot application by using the following Gradle command. 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 java –jar <JARFILE> and application is started on the Tomcat port 8080. Now hit the URL http://localhost:8080/ and click the Google Login link. It will redirect to the Google login screen and provide a Gmail login details. If login success, we will receive the Principal object of the Gmail user. Print Page Previous Next Advertisements ”;
Spring Boot – Home
Spring Boot Tutorial PDF Version Quick Guide Resources Job Search Discussion Spring Boot is an open source Java-based framework used to create a Micro Service. It is developed by Pivotal Team. It is easy to create a stand-alone and production ready spring applications using Spring Boot. Spring Boot contains a comprehensive infrastructure support for developing a micro service and enables you to develop enterprise-ready applications that you can “just run”. Audience This tutorial is designed for Java developers to understand and develop production-ready spring applications with minimum configurations. It explores major features of Spring Boot such as Starters, Auto-configuration, Beans, Actuator and more. By the end of this tutorial, you will gain an intermediate level of expertise in Spring Boot. Prerequisites This tutorial is written for readers who have a prior experience of Java, Spring, Maven, and Gradle. You can easily understand the concepts of Spring Boot if you have knowledge on these concepts. It would be an additional advantage if you have an idea about writing a RESTful Web Service. If you are a beginner, we suggest you to go through tutorials related to these concepts before you start with Spring Boot. Print Page Previous Next Advertisements ”;
Spring Boot – Quick Start
Spring Boot – Quick Start ”; Previous Next This chapter will teach you how to create a Spring Boot application using Maven and Gradle. Prerequisites Your system need to have the following minimum requirements to create a Spring Boot application − Java 7 Maven 3.2 Gradle 2.5 Spring Boot CLI The Spring Boot CLI is a command line tool and it allows us to run the Groovy scripts. This is the easiest way to create a Spring Boot application by using the Spring Boot Command Line Interface. You can create, run and test the application in command prompt itself. This section explains you the steps involved in manual installation of Spring Boot CLI. For further help, you can use the following link: https://docs.spring.io/springboot/ docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-installing-springboot You can also download the Spring CLI distribution from the Spring Software repository at: https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-manual-cli-installation For manual installation, you need to use the following two folders − spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.zip spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.tar.gz After the download, unpack the archive file and follow the steps given in the install.txt file. Not that it does not require any environment setup. In Windows, go to the Spring Boot CLI bin directory in the command prompt and run the command spring –-version to make sure spring CLI is installed correctly. After executing the command, you can see the spring CLI version as shown below − Run Hello World with Groovy Create a simple groovy file which contains the Rest Endpoint script and run the groovy file with spring boot CLI. Observe the code shown here for this purpose − @Controller class Example { @RequestMapping(“/”) @ResponseBody public String hello() { “Hello Spring Boot” } } Now, save the groovy file with the name hello.groovy. Note that in this example, we saved the groovy file inside the Spring Boot CLI bin directory. Now run the application by using the command spring run hello.groovy as shown in the screenshot given below − Once you run the groovy file, required dependencies will download automatically and it will start the application in Tomcat 8080 port as shown in the screenshot given below − Once Tomcat starts, go to the web browser and hit the URL http://localhost:8080/ and you can see the output as shown. Print Page Previous Next Advertisements ”;
Struts2 – Hibernate
Struts 2 and Hibernate Integration ”; Previous Next Hibernate is a high-performance Object/Relational persistence and query service which is licensed under the open source GNU Lesser General Public License (LGPL) and is free to download. In this chapter. we are going to learn how to achieve Struts 2 integration with Hibernate. If you are not familiar with Hibernate, then you can check our Hibernate tutorial. Database Setup For this tutorial, I am going to use the “struts2_tutorial” MySQL database. I connect to this database on my machine using the username “root” and no password. First of all, you need to run the following script. This script creates a new table called student and creates few records in this table − CREATE TABLE IF NOT EXISTS `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(40) NOT NULL, `last_name` varchar(40) NOT NULL, `marks` int(11) NOT NULL, PRIMARY KEY (`id`) ); — — Dumping data for table `student` — INSERT INTO `student` (`id`, `first_name`, `last_name`, `marks`) VALUES(1, ”George”, ”Kane”, 20); INSERT INTO `student` (`id`, `first_name`, `last_name`, `marks`) VALUES(2, ”Melissa”, ”Michael”, 91); INSERT INTO `student` (`id`, `first_name`, `last_name`, `marks`) VALUES(3, ”Jessica”, ”Drake”, 21); Hibernate Configuration Next let us create the hibernate.cfg.xml which is the hibernate”s configuration file. <?xml version = ”1.0” encoding = ”utf-8”?> <!DOCTYPE hibernate-configuration PUBLIC “-//Hibernate/Hibernate Configuration DTD//EN” “http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”> <hibernate-configuration> <session-factory> <property name = “hibernate.connection.driver_class”>c om.mysql.jdbc.Driver </property> <property name = “hibernate.connection.url”> jdbc:mysql://www.tutorialspoint.com/struts_tutorial </property> <property name = “hibernate.connection.username”>root</property> <property name = “hibernate.connection.password”></property> <property name = “hibernate.connection.pool_size”>10</property> <property name = “show_sql”>true</property> <property name = “dialect”> org.hibernate.dialect.MySQLDialect </property> <property name = “hibernate.hbm2ddl.auto”>update</property> <mapping class = “com.tutorialspoint.hibernate.Student” /> </session-factory> </hibernate-configuration> Let us go through the hibernate config file. First, we declared that we are using MySQL driver. Then we declared the jdbc url for connecting to the database. Then we declared the connection”s username, password and pool size. We also indicated that we would like to see the SQL in the log file by turning on “show_sql” to true. Please go through the hibernate tutorial to understand what these properties mean. Finally, we set the mapping class to com.tutorialspoint.hibernate.Student which we will create in this chapter. Envrionment Setup Next you need a whole lot of jars for this project. Attached is a screenshot of the complete list of JAR files required − Most of the JAR files can be obtained as part of your struts distribution. If you have an application server such as glassfish, websphere or jboss installed, then you can get the majority of the remaining jar files from the appserver”s lib folder. If not you can download the files individually − Hibernate jar files − Hibernate.org Struts hibernate plugin − Struts hibernate plugin JTA files − JTA files Dom4j files − Dom4j log4j files − log4j Rest of the files, you should be able to get from your Struts2 distribution. Hibernate Classes Let us now create required java classes for the hibernate integration. Following is the content of Student.java − package com.tutorialspoint.hibernate; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = “student”) public class Student { @Id @GeneratedValue private int id; @Column(name = “last_name”) private String lastName; @Column(name = “first_name”) private String firstName; private int marks; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public int getMarks() { return marks; } public void setMarks(int marks) { this.marks = marks; } } This is a POJO class that represents the student table as per Hibernate specification. It has properties id, firstName and lastName which correspond to the column names of the student table. Next let us create StudentDAO.java file as follows − package com.tutorialspoint.hibernate; import java.util.ArrayList; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import com.googlecode.s2hibernate.struts2.plugin. annotations.SessionTarget; import com.googlecode.s2hibernate.struts2.plugin. annotations.TransactionTarget; public class StudentDAO { @SessionTarget Session session; @TransactionTarget Transaction transaction; @SuppressWarnings(“unchecked”) public List<Student> getStudents() { List<Student> students = new ArrayList<Student>(); try { students = session.createQuery(“from Student”).list(); } catch(Exception e) { e.printStackTrace(); } return students; } public void addStudent(Student student) { session.save(student); } } The StudentDAO class is the data access layer for the Student class. It has methods to list all students and then to save a new student record. Action Class Following file AddStudentAction.java defines our action class. We have two action methods here – execute() and listStudents(). The execute() method is used to add the new student record. We use the dao”s save() method to achieve this. The other method, listStudents() is used to list the students. We use the dao”s list method to get the list of all students. package com.tutorialspoint.struts2; import java.util.ArrayList; import java.util.List; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.tutorialspoint.hibernate.Student; import com.tutorialspoint.hibernate.StudentDAO; public class AddStudentAction extends ActionSupport implements ModelDriven<Student> { Student student = new Student(); List<Student> students = new ArrayList<Student>(); StudentDAO dao = new StudentDAO(); @Override public Student getModel() { return student; } public String execute() { dao.addStudent(student); return “success”; } public String listStudents() { students = dao.getStudents(); return “success”; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } public List<Student> getStudents() { return students; } public void setStudents(List<Student> students) { this.students = students; } } You will notice that we are implementing the ModelDriven interface. This is used when your action class is dealing with a concrete model class (such as Student) as opposed to individual properties (such as firstName, lastName). The ModelAware interface requires you to implement a method to return the model. In our case we are returning the “student” object. Create View Files Let us now create the student.jsp view file with the following content − <%@ page contentType = “text/html; charset = UTF-8″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <html> <head> <title>Hello World</title> <s:head /> </head> <body> <s:form action = “addStudent”> <s:textfield name = “firstName” label = “First Name”/> <s:textfield name = “lastName” label = “Last Name”/> <s:textfield name
TestNG – TestNG – vs JUnit
TestNG – vs JUnit ”; Previous Next JUnit and TestNG are the most popular testing frameworks for Java applications. Both of these frameworks are easy to use. So when it comes to chose the testing framework for your application, it’s better to have a high-level idea of what features are present in one or the other and then take the informed decision based on your project requirements. JUnit vs TestNG JUnit current version is 5.7.1 and it’s still evolving and working on to include more features. TestNG current version is 7.4.0 and it’s mature and features rich. Following table compares JUnit vs TestNG on different features. The table excludes very specific or common features that are present in both these frameworks, such as testing exceptions, timeout settings, lifecycle callback methods etc. Feature JUnit TestNG Conclusion Annotations Annotations Based Annotations Based Both JUnit 5 and TestNG are annotation based. They are similar in nature and behavior. Ease of Use JUnit 5 is built into various modules, you need JUnit Platform and JUnit Jupiter to write test cases. If you want more features such as Parameterized Tests then you need to add junit-jupiter-params module. Single module to get all TestNG feature. TestNG is better in terms of ease of use. IDE Support Supported on major IDEs such as Eclipse and IntelliJ IDEA. Supported on major IDEs such as Eclipse and IntelliJ IDEA. Both of them are similar and provides easy integration with major IDEs. Data Provider Supports multiple ways to provide test data, such as methods, Enum, CSV, CSV Files etc. Supports data provider methods and from test suite xml file. JUnit is better for injecting test methods input data Test Suite In JUnit, Test Suite is run using @RunWith and @Suite annotations. TestNG uses an XML file to run Suite test. HTML Reports JUnit need external plugin maven-surefire-report-plugin to generate HTML reports. TestNG automatically creates HTML reports for the test run. TestNG HTML reports look outdated but it’s simple to use. If you have to share HTML reports with others, I would suggest to use JUnit. Running from Java Main Method We can use JUnit 5 launcher API to run tests from java main method. We can use TestNG run() method to execute tests from the java main method. Both of them supports execution of test cases from java main method. Assertions JUnit provides enough assertion methods to compare expected and actual test results. TestNG provides enough assertion methods to compare expected and actual test results. Both of them are similar in terms of Assertions support. Assumptions JUnit supports assumptions to skip tests based on certain conditions. TestNG doesn’t support assumptions. JUnit is better if you want to skip tests based on conditions. Test Order Junit does not support Test Order. TestNG supports Test Order for ordering test methods according to priority attribute. TestNG is better when you want to execute tests in specific order. Disable Tests JUnit supports many ways to disable and enable tests. For example, based on OS, JRE, system properties. TestNG supports disabling tests but it’s limited in functionality. JUnit is better when you want to disable or enable tests based on conditions. Parallel Execution JUnit 5 doesn’t support parallel execution yet. TestNG supports parallel execution if run through XML suite. TestNG is better for parallel execution as of now, JUnit 5 development is going on to support this feature. Listeners JUnit supports listeners through Launcher API, there is no mechanism to add listeners using annotations. TestNG supports various types of listeners and can be added using annotations. TestNG listener support is much better compared to JUnit 5. Print Page Previous Next Advertisements ”;
Spring Boot – Apache Kafka
Spring Boot – Apache Kafka ”; Previous Next Apache Kafka is an open source project used to publish and subscribe the messages based on the fault-tolerant messaging system. It is fast, scalable and distributed by design. If you are a beginner to Kafka, or want to gain a better understanding on it, please refer to this link − www.tutorialspoint.com/apache_kafka/ In this chapter, we are going to see how to implement the Apache Kafka in Spring Boot application. First, we need to add the Spring Kafka dependency in our build configuration file. Maven users can add the following dependency in the pom.xml file. <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> <version>2.1.0.RELEASE</version> </dependency> Gradle users can add the following dependency in the build.gradle file. compile group: ”org.springframework.kafka”, name: ”spring-kafka”, version: ”2.1.0.RELEASE” Producing Messages To produce messages into Apache Kafka, we need to define the Configuration class for Producer configuration as shown − package com.tutorialspoint.kafkademo; import java.util.HashMap; import java.util.Map; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; @Configuration public class KafkaProducerConfig { @Bean public ProducerFactory<String, String> producerFactory() { Map<String, Object> configProps = new HashMap<>(); configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, “localhost:9092”); configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); return new DefaultKafkaProducerFactory<>(configProps); } @Bean public KafkaTemplate<String, String> kafkaTemplate() { return new KafkaTemplate<>(producerFactory()); } } To publish a message, auto wire the Kafka Template object and produce the message as shown. @Autowired private KafkaTemplate<String, String> kafkaTemplate; public void sendMessage(String msg) { kafkaTemplate.send(topicName, msg); } Consuming a Message To consume messages, we need to write a Consumer configuration class file as shown below. package com.tutorialspoint.kafkademo; import java.util.HashMap; import java.util.Map; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.annotation.EnableKafka; import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; import org.springframework.kafka.core.ConsumerFactory; import org.springframework.kafka.core.DefaultKafkaConsumerFactory; @EnableKafka @Configuration public class KafkaConsumerConfig { @Bean public ConsumerFactory<String, String> consumerFactory() { Map<String, Object> props = new HashMap<>(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, “localhost:2181”); props.put(ConsumerConfig.GROUP_ID_CONFIG, “group-id”); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); return new DefaultKafkaConsumerFactory<>(props); } @Bean public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(consumerFactory()); return factory; } } Next, write a Listener to listen to the messages. @KafkaListener(topics = “tutorialspoint”, groupId = “group-id”) public void listen(String message) { System.out.println(“Received Messasge in group – group-id: ” + message); } Let us call the sendMessage() method from ApplicationRunner class run method from the main Spring Boot application class file and consume the message from the same class file. Your main Spring Boot application class file code is given below − package com.tutorialspoint.kafkademo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.kafka.core.KafkaTemplate; @SpringBootApplication public class KafkaDemoApplication implements ApplicationRunner { @Autowired private KafkaTemplate<String, String> kafkaTemplate; public void sendMessage(String msg) { kafkaTemplate.send(“tutorialspoint”, msg); } public static void main(String[] args) { SpringApplication.run(KafkaDemoApplication.class, args); } @KafkaListener(topics = “tutorialspoint”, groupId = “group-id”) public void listen(String message) { System.out.println(“Received Messasge in group – group-id: ” + message); } @Override public void run(ApplicationArguments args) throws Exception { sendMessage(“Hi Welcome to Spring For Apache Kafka”); } } The code for complete build configuration file is given below. Maven – pom.xml <?xml version = “1.0” encoding = “UTF-8”?> <project xmlns = “http://maven.apache.org/POM/4.0.0” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>kafka-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>kafka-demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath /> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> <version>2.1.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Gradle – build.gradle buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter”) compile group: ”org.springframework.kafka”, name: ”spring-kafka”, version: ”2.1.0.RELEASE” testCompile(”org.springframework.boot:spring-boot-starter-test”) } Now, create an executable JAR file, and run the Spring Boot application by using the below Maven or Gradle commands as shown − 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, 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. Print Page Previous Next Advertisements ”;
TestNG – Plug with ANT
TestNG – Plug with ANT ”; Previous Next In this chapter, we will demonstrate how to run TestNG using ANT. Let”s follow the steps given below − Step 1: Download Apache Ant Download the latest version of Apache Ant OS Archive Name Windows apache-ant-1.10.10-bin.zip Linux apache-ant-1.10.10-bin.tar.gz Mac apache-ant-1.10.10-bin.tar.gz Step 2: Set Ant Environment Set the ANT_HOME environment variable to point to the base directory location, where ANT libraries are stored on your machine. Let’s assume we”ve stored the Ant libraries in the folder apache-ant-1.8.4 folder. OS Output Windows Set the environment variable ANT_HOME to C:Program FilesApache Software Foundationapache-ant-1.10.10 Linux Export ANT_HOME=/usr/local/apache-ant-1.10.10 Mac Export ANT_HOME=/Library/apache-ant-1.10.10 Append Ant compiler location to System Path as follows − OS Description Windows Append the string %ANT_HOMEbin at the end of the system variable, Path. Linux export PATH=$PATH:$ANT_HOME/bin/ Mac Not required. Step 3: Download TestNG Archive Download the required jar files http://www.testng.org. OS Archive name Windows testng-7.4.jar Linux testng-7.4.jar Mac testng-7.4.jar Step 4: Create Project Structure Create a folder TestNGWithAnt in /work/testng/src. Create a folder src in /work/testng/src/TestNGWithAnt. Create a folder test in /work/testng/src/TestNGWithAnt. Create a folder lib in /work/testng/src/TestNGWithAnt. Create MessageUtil class in /work/testng/src/TestNGWithAnt/src folder. /* * 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 void printMessage() { System.out.println(message); return message; } // add “Hi!” to the message public String salutationMessage() { message = “Hi!” + message; System.out.println(message); return message; } } Create TestMessageUtil class in /work/testng/src/TestNGWithAnt/src folder. import org.testng.Assert; import org.testng.annotations.Test; public class TestMessageUtil { String message = “Manisha”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { System.out.println(“Inside testPrintMessage()”); Assert.assertEquals(message,messageUtil.printMessage()); } @Test public void testSalutationMessage() { System.out.println(“Inside testSalutationMessage()”); message = “Hi!” + “Manisha”; Assert.assertEquals(message,messageUtil.salutationMessage()); } } Copy testng-7.4.jar in /work/testng/src/TestNGWithAnt/lib folder. Create ANT build.xml First, we need to define the TestNG Ant task as follows − <taskdef name = “testng” classname = “org.testng.TestNGAntTask”> <classpath> <pathelement location = “lib/testng-7.4.jar”/> </classpath> </taskdef> Then, we”ll be using <testng> task in Ant to execute our TestNG test cases. The build.xml file is as follows − <project name = “TestNGTest” default = “test” basedir = “.”> <!– Define <testng> task –> <taskdef name = “testng” classname = “org.testng.TestNGAntTask”> <classpath> <pathelement location = “lib/testng-7.4.jar”/> </classpath> </taskdef> <property name = “testdir” location = “test” /> <property name = “srcdir” location = “src” /> <property name = “libdir” location = “lib” /> <property name = “full-compile” value=”true” /> <path id = “classpath.base”/> <path id = “classpath.test”> <fileset dir = “${libdir}”> <include name = “**/*.jar” /> </fileset> <pathelement location = “${testdir}” /> <pathelement location = “${srcdir}” /> <path refid = “classpath.base” /> </path> <target name = “clean” > <delete verbose=”${full-compile}”> <fileset dir = “${testdir}” includes=”**/*.class” /> </delete> </target> <target name = “compile” depends=”clean”> <javac srcdir = “${srcdir}” destdir = “${testdir}” verbose=”${full-compile}”> <classpath refid = “classpath.test”/> </javac> </target> <target name = “test” depends=”compile”> <testng outputdir = “${testdir}” classpathref=”classpath.test”> <xmlfileset dir = “${srcdir}” includes=”testng.xml”/> </testng> </target> </project> Run the following Ant command. /work/testng/src/TestNGWithAnt$ ant Verify the output. test: [testng] [TestNG] Running: [testng] /work/testng/src/TestNGWithAnt/src/testng.xml [testng] [testng] Inside testPrintMessage() [testng] Manisha [testng] Inside testSalutationMessage() [testng] Hi!Manisha [testng] [testng] =============================================== [testng] Plug ANT test Suite [testng] Total tests run: 2, Failures: 0, Skips: 0 [testng] =============================================== [testng] BUILD SUCCESSFUL Total time: 1 second Print Page Previous Next Advertisements ”;
Spring Boot – Web Socket
Spring Boot – Web Socket ”; Previous Next In this chapter, let us understand how to build an interactive web application by using Spring Boot with Web sockets. To build an interactive web application in Spring Boot with Web socket, you need to add the following dependencies. Maven users should add the following dependencies in the pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>webjars-locator</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>sockjs-client</artifactId> <version>1.0.2</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>stomp-websocket</artifactId> <version>2.3.3</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>3.3.7</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.1.0</version> </dependency> Gradle users can add the following dependencies in your build.gradle file − compile(“org.springframework.boot:spring-boot-starter-websocket”) compile(“org.webjars:webjars-locator”) compile(“org.webjars:sockjs-client:1.0.2”) compile(“org.webjars:stomp-websocket:2.3.3”) compile(“org.webjars:bootstrap:3.3.7”) compile(“org.webjars:jquery:3.1.0”) Let us create a Message handling controller to work with STOMP messaging. STOMP messages can be routed to @Controller class file. For example, GreetingController is mapped to handle the messages to destination “/hello”. package com.tutorialspoint.websocketapp; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Controller; @Controller public class GreetingController { @MessageMapping(“/hello”) @SendTo(“/topic/greetings”) public Greeting greeting(HelloMessage message) throws Exception { Thread.sleep(1000); // simulated delay return new Greeting(“Hello, ” + message.getName() + “!”); } } Now, configure Spring for STOMP messaging. Write a WebSocketConfig class file that extends the AbstractWebSocketMessageBrokerConfigurer class as shown below. package com.tutorialspoint.websocketapp; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker(“/topic”); config.setApplicationDestinationPrefixes(“/app”); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint(“/tutorialspoint-websocket”).withSockJS(); } } The @EnableWebSocketMessageBroker annotation is used to configure the Web socket message broker to create STOMP endpoints. You can create a browser client file under the src/main/resources/static/index.html as shown − <!DOCTYPE html> <html> <head> <title>Hello WebSocket</title> <link href = “/webjars/bootstrap/css/bootstrap.min.css” rel = “stylesheet”> <link href = “/main.css” rel = “stylesheet”> <script src = “/webjars/jquery/jquery.min.js”></script> <script src = “/webjars/sockjs-client/sockjs.min.js”></script> <script src = “/webjars/stomp-websocket/stomp.min.js”></script> <script src = “/app.js”></script> </head> <body> <noscript> <h2 style = “color: #ff0000″> Seems your browser doesn”t support Javascript! Websocket relies on Javascript being enabled. Please enable Javascript and reload this page! </h2> </noscript> <div id = “main-content” class = “container”> <div class = “row”> <div class = “col-md-6”> <form class = “form-inline”> <div class = “form-group”> <label for = “connect”>WebSocket connection:</label> <button id = “connect” class = “btn btn-default” type = “submit”>Connect</button> <button id = “disconnect” class = “btn btn-default” type = “submit” disabled = “disabled”>Disconnect </button> </div> </form> </div> <div class = “col-md-6”> <form class = “form-inline”> <div class = “form-group”> <label for = “name”>What is your name?</label> <input type = “text” id = “name” class = “form-control” placeholder = “Your name here…”> </div> <button id = “send” class = “btn btn-default” type = “submit”>Send</button> </form> </div> </div> <div class = “row”> <div class = “col-md-12”> <table id = “conversation” class = “table table-striped”> <thead> <tr> <th>Greetings</th> </tr> </thead> <tbody id = “greetings”></tbody> </table> </div> </div> </div> </body> </html> Let us create an app.js file to consume and produce the messages by using STOMP. var stompClient = null; function setConnected(connected) { $(“#connect”).prop(“disabled”, connected); $(“#disconnect”).prop(“disabled”, !connected); if (connected) { $(“#conversation”).show(); } else { $(“#conversation”).hide(); } $(“#greetings”).html(“”); } function connect() { var socket = new SockJS(”/tutorialspoint-websocket”); stompClient = Stomp.over(socket); stompClient.connect({}, function (frame) { setConnected(true); console.log(”Connected: ” + frame); stompClient.subscribe(”/topic/greetings”, function (greeting) { showGreeting(JSON.parse(greeting.body).content); }); }); } function disconnect() { if (stompClient !== null) { stompClient.disconnect(); } setConnected(false); console.log(“Disconnected”); } function sendName() { stompClient.send(“/app/hello”, {}, JSON.stringify({”name”: $(“#name”).val()})); } function showGreeting(message) { $(“#greetings”).append(“<tr><td>” + message + “</td></tr>”); } $(function () { $( “form” ).on(”submit”, function (e) {e.preventDefault();}); $( “#connect” ).click(function() { connect(); }); $( “#disconnect” ).click(function() { disconnect(); }); $( “#send” ).click(function() { sendName(); }); }); The code for main Spring Boot application is shown below. package com.tutorialspoint.websocketapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class WebsocketappApplication { public static void main(String[] args) { SpringApplication.run(WebsocketappApplication.class, args); } } The complete build configuration file is given below. Maven – pom.xml <?xml version = “1.0” encoding = “UTF-8”?> <project xmlns = “http://maven.apache.org/POM/4.0.0” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>websocketapp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>websocketapp</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>webjars-locator</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>sockjs-client</artifactId> <version>1.0.2</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>stomp-websocket</artifactId> <version>2.3.3</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>3.3.7</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <properties> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Gradle – build.gradle buildscript { repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:1.5.9.RELEASE”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” jar { baseName = ”websocketapp” version = ”0.1.0” } sourceCompatibility = 1.8 targetCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(“org.springframework.boot:spring-boot-starter-websocket”) compile(“org.webjars:webjars-locator”) compile(“org.webjars:sockjs-client:1.0.2”) compile(“org.webjars:stomp-websocket:2.3.3”) compile(“org.webjars:bootstrap:3.3.7”) compile(“org.webjars:jquery:3.1.0”) testCompile(“org.springframework.boot:spring-boot-starter-test”) } Print Page Previous Next Advertisements ”;
TestNG – Quick Guide
TestNG – Quick Guide ”; Previous Next TestNG – Overview Testing is the process of checking the functionality of an application to ensure it works as per requirements. Unit testing comes into picture at the developer level where adequate measures are taken to test every single entity (class or method) to ensure the final product meets the requirements. JUnit has driven developers to understand the usefulness of tests, especially of unit tests, when compared to any other testing framework. Leveraging a rather simple, pragmatic, and strict architecture, JUnit has been able to “infect” great number of developers. Do take a look at our tutorial on JUnit to have a good understanding of its features. JUnit, at the same time, has some shortcomings as well, which are listed below − Initially designed to enable unit testing only, now used for all kinds of testing. Cannot do dependency testing. Poor configuration control (setUp/tearDown). Intrusive (forces you to extend classes and name your methods a certain way). Static programming model (forces you to recompile unnecessarily). The management of different suites of tests in complex projects can be very tricky. What is TestNG? Definition of TestNG as per its documentation is as follows − TestNG is a testing framework inspired from JUnit and NUnit, but introducing some new functionalities that make it more powerful and easier to use. TestNG is an open source automated testing framework; where NG means NextGeneration. TestNG is similar to JUnit (especially JUnit 4), but it is not a JUnit extension. It is inspired by JUnit. It is designed to be better than JUnit, especially when testing integrated classes. The creator of TestNG is Cedric Beust. Eliminating most of the limitations of the older framework, TestNG gives the developer the ability to write more flexible and powerful tests. As it heavily borrows from Java Annotations (introduced with JDK 5.0) to define tests, it can also show you how to use this new feature of the Java language in a real production environment. TestNG Features Supports annotations. TestNG uses more Java and OO features. Supports testing integrated classes (e.g., by default, no need to create a new test class instance for every test method). Separates compile-time test code from run-time configuration/data info. Flexible runtime configuration. Introduces ‘test groups’. Once you have compiled your tests, you can just ask TestNG to run all the “front-end” tests, or “fast”, “slow”, “database” tests, etc. Supports Dependent test methods, parallel testing, load testing, and partial failure. Flexible plug-in API. Support for multi threaded testing. TestNG – Environment TestNG is a framework for Java, so the very first requirement is to have JDK installed in your machine. System Requirement JDK 1.5 or above. Memory No minimum requirement. Disk Space No minimum requirement. Operating System No minimum requirement. Step 1 – Verify Java Installation in Your Machine Open the console and execute a java command based on the operating system you have installed on your system. OS Task Command Windows Open Command Console c:> java -version Linux Open Command Terminal $ java -version Mac Open Terminal machine:~ joseph$ java -version Let”s verify the output for all the operating systems − OS Output Windows java version “1.7.0_25” Java(TM) SE Runtime Environment (build 1.7.0_25-b15) Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode) Linux java version “1.7.0_25” Java(TM) SE Runtime Environment (build 1.7.0_25-b15) Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode) Mac java version “1.7.0_25” Java(TM) SE Runtime Environment (build 1.7.0_25-b15) Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode) If you do not have Java, install the Java Software Development Kit (SDK) from https://www.oracle.com/technetwork/java/javase/downloads/index.html. We are assuming Java 1.7.0_25 as the installed version for this tutorial. Step 2: Set JAVA Environment Set the JAVA_HOME environment variable to point to the base directory location, where Java is installed on your machine. For example, OS Output Windows Set the environment variable JAVA_HOME to C:Program FilesJavajdk1.7.0_25. Linux Export JAVA_HOME=/usr/local/java-current. Mac Export JAVA_HOME=/Library/Java/Home. Append Java compiler location to System Path. OS Output Windows Append the string C:Program FilesJavajdk1.7.0_25bin at the end of the system variable, Path. Linux Export PATH=$PATH:$JAVA_HOME/bin/ Mac Not required Verify Java Installation using the command java -version as explained above. Step 3: Download TestNG Archive Download the latest version of TestNG jar file from http://www.testng.org. At the time of writing this tutorial, we have downloaded testng-6.8.jar and copied it onto C:> TestNG folder. OS Archive name Windows testng-6.8.jar Linux testng-6.8.jar Mac testng-6.8.jar Step 4: Set TestNG Environment Set the TESTNG_HOME environment variable to point to the base directory location, where TestNG jar is stored on your machine. The following table shows how to set the environment variable in Windows, Linux, and Mac, assuming that we”ve stored testng-6.8.jar at the location C:>TestNG. OS Description Windows Set the environment variable TESTNG_HOME to C:TESTNG. Linux Export TESTNG_HOME=/usr/local/TESTNG Mac Export TESTNG_HOME=/Library/TESTNG Step 5: Set CLASSPATH Variable Set the CLASSPATH environment variable to point to the TestNG jar location. OS Description Windows Set the environment variable CLASSPATH to %CLASSPATH%;%TESTNG_HOME%testng-6.8.jar. Linux Export CLASSPATH=$CLASSPATH:$TESTNG_HOME/testng-6.8.jar. Mac Export CLASSPATH=$CLASSPATH:$TESTNG_HOME/testng-6.8.jar. Step 6: Test TestNG Setup Create a java class file named TestNGSimpleTest at C:>TestNG_WORKSPACE. import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class TestNGSimpleTest { @Test public void testAdd() { String str = “TestNG is working fine”; AssertEquals(“TestNG is working fine”, str); } } TestNG can be invoked in several different ways − With a testng.xml file. With ANT. From the command line. Let us invoke using the testng.xml file. Create an xml file with the name testng.xml in C:>TestNG_WORKSPACE 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 = “TestNGSimpleTest”/> </classes> </test> </suite> Step 7: Verify the Result Compile the class using javac compiler as follows − C:TestNG_WORKSPACE>javac TestNGSimpleTest.java Now, invoke the testng.xml to see the result − C:TestNG_WORKSPACE>java -cp “C:TestNG_WORKSPACE” org.testng.TestNG testng.xml Verify the output. =============================================== Suite1 Total tests run: 1, Failures: 0, Skips: 0 =============================================== TestNG – Writing Tests Writing a test in TestNG basically