SWING – Environment

SWING – Environment Setup ”; Previous Next This section guides you on how to download and set up Java on your machine. Please use the following steps to set up the environment. Java SE is freely available from the link Download Java. Hence, you can download a version based on your operating system. Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set the environment variables to point to the correct installation directories. Setting Up the Path for Windows 2000/XP Assuming you have installed Java in c:Program Filesjavajdk directory − Step 1 − Right-click on ”My Computer” and select ”Properties”. Step 2 − Click the ”Environment variables” button under the ”Advanced” tab. Step 3 − Alter the ”Path” variable so that it also contains the path to the Java executable. Example, if the path is currently set to ”C:WINDOWSSYSTEM32”, then change your path to read ”C:WINDOWSSYSTEM32;c:Program Filesjavajdkbin”. Setting Up the Path for Windows 95/98/ME Assuming you have installed Java in c:Program Filesjavajdk directory − Step 1 − Edit the ”C:autoexec.bat” file and add the following line at the end: ”SET PATH=%PATH%;C:Program Filesjavajdkbin”. Setting Up the Path for Linux, UNIX, Solaris, FreeBSD Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your Shell documentation if you have trouble doing this. Example, if you use bash as your shell, then you would add the following line to the end ”.bashrc: export PATH=/path/to/java:$PATH”. Popular Java Editors To write your Java programs, you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following − Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad. Netbeans − Netbeans is a Java IDE that is open source and free, which can be downloaded from https://www.netbeans.org/index.html. Eclipse − Eclipse is also a Java IDE developed by the Eclipse open source community and can be downloaded from https://www.eclipse.org/. Print Page Previous Next Advertisements ”;

TestNG – Useful Resources

TestNG – Useful Resources ”; Previous Next The following resources contain additional information on TestNG. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Selenium And Java Advanced Course with Live Project Best Seller 296 Lectures 146 hours Arun Motoori More Detail TestNG Complete Bootcamp For Beginners 39 Lectures 4.5 hours Lets Kode It More Detail Selenium WebDriver 4 with Java – Zero To Hero Most Popular 294 Lectures 41.5 hours Lets Kode It More Detail தமிழ் மொழியில் Selenium கற்றுக்கொள்ளுங்கள் | Learn Selenium 35 Lectures 8.5 hours Programming Line More Detail Learn TestNG 15 Lectures 1.5 hours Quaatso Learning More Detail The Complete Selenium WebDriver with Java Course Most Popular 202 Lectures 21 hours Dezlearn Education More Detail Print Page Previous Next Advertisements ”;

TestNG – Overview

TestNG – Overview ”; Previous Next 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. 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