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 ”;

Spring Security – Authentication Provider

Spring Security – Authentication Provider ”; Previous Next Spring Security allows us to customize our authentication process as much as we want. Starting from a custom login page to our very own customized authentication providers and authentication filters, we can pretty much customize every aspect of the authentication process. We can define our own authentication process which can range from basic authentication using a username and a password to a complex one such as two-factor authentication using tokens and OTP’s. Also, we can use various databases – both relational and non-relational, use various password encoders, lock malicious users out of their accounts, and so on. Spring Security Architecture The basic components of Spring Security, as we can see in the above diagram are given below. We shall discuss them briefly as we go along. We shall also discuss their roles in the authentication and authorization process. AuthenticationFilter This is the filter that intercepts requests and attempts to authenticate it. In Spring Security, it converts the request to an Authentication Object and delegates the authentication to the AuthenticationManager. AuthenticationManager It is the main strategy interface for authentication. It uses the lone method authenticate() to authenticate the request. The authenticate() method performs the authentication and returns an Authentication Object on successful authentication or throw an AuthenticationException in case of authentication failure. If the method can’t decide, it will return null. The process of authentication in this process is delegated to the AuthenticationProvider which we will discuss next. AuthenticationProvider The AuthenticationManager is implemented by the ProviderManager which delegates the process to one or more AuthenticationProvider instances. Any class implementing the AuthenticationProvider interface must implement the two methods – authenticate() and supports(). First, let us talk about the supports() method. It is used to check if the particular authentication type is supported by our AuthenticationProvider implementation class. If it is supported it returns true or else false. Next, the authenticate() method. Here is where the authentication occurs. If the authentication type is supported, the process of authentication is started. Here is this class can use the loadUserByUsername() method of the UserDetailsService implementation. If the user is not found, it can throw a UsernameNotFoundException. On the other hand, if the user is found, then the authentication details of the user are used to authenticate the user. For example, in the basic authentication scenario, the password provided by the user may be checked with the password in the database. If they are found to match with each other, it is a success scenario. Then we can return an Authentication object from this method which will be stored in the Security Context, which we will discuss later. Spring Security provides following major implementations of AuthenticationProvider. DaoAuthenticationProvider − This provider is used to provide database based authentication. LdapAuthenticationProvider − This provider is specialized for LDAP(Lightweight Directory Access Protocol) based authentication. OpenIDAuthenticationProvider − This provider is used for OpenID based authentication and can be used with OpenID authentication providers like Google/Facebook etc. JwtAuthenticationProvider − For JWT(Java Web Token) based authentication, we can use JwtAuthenticationProvider class. RememberMeAuthenticationProvider − This class is used for user authentication based on remember me token of user. We”ll be creating our own AuthenticationProvider in coming section. UserDetailsService It is one of the core interfaces of Spring Security. The authentication of any request mostly depends on the implementation of the UserDetailsService interface. It is most commonly used in database backed authentication to retrieve user data. The data is retrieved with the implementation of the lone loadUserByUsername() method where we can provide our logic to fetch the user details for a user. The method will throw a UsernameNotFoundException if the user is not found. PasswordEncoder Until Spring Security 4, the use of PasswordEncoder was optional. The user could store plain text passwords using in-memory authentication. But Spring Security 5 has mandated the use of PasswordEncoder to store passwords. This encodes the user’s password using one its many implementations. The most common of its implementations is the BCryptPasswordEncoder. Also, we can use an instance of the NoOpPasswordEncoder for our development purposes. It will allow passwords to be stored in plain text. But it is not supposed to be used for production or real-world applications. Spring Security Context This is where the details of the currently authenticated user are stored on successful authentication. The authentication object is then available throughout the application for the session. So, if we need the username or any other user details, we need to get the SecurityContext first. This is done with the SecurityContextHolder, a helper class, which provides access to the security context. We can use the setAuthentication() and getAuthentication() methods for storing and retrieving the user details respectively. Custom Authenticator We can create a custom Authenticator by implementing AuthenticationProvider interface. AuthenticatorProvider interface has two methods authenticate() and supports(). authenticate() method @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = authentication.getCredentials().toString(); UserDetails user = userDetailsService.loadUserByUsername(username); if (user == null || !password.equals(user.getPassword())) { throw new BadCredentialsException(“Invalid username or password”); } List<GrantedAuthority> authorities = new ArrayList(); authorities.add(new SimpleGrantedAuthority(“ROLE_USER”)); return new UsernamePasswordAuthenticationToken(username, password, authorities); } Here in authenticate() method, we”re getting username and password using authentication object and we”re comparing username/password with the user credentials. In case user details are invalid, we”re throwing an exception as BadCredentialsException. Otherwise, a new role is prepared and UsernamePasswordAuthenticationToken is returned with required role. supports() method @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } Spring Security Configuration Use the AuthenticationProvider created in the AuthenticationManager and mark it as managed bean. @Bean public AuthenticationManager authManager(HttpSecurity http) throws Exception { AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class); WebAuthenticationProvider authProvider = new WebAuthenticationProvider(userDetailsService()); authenticationManagerBuilder.authenticationProvider(authProvider); return authenticationManagerBuilder.build(); } That”s all we need. Now let”s see the complete code in action. Before you start writing your first example using Spring framework, you have to make sure that you have set up your Spring environment properly as explained in Spring Security – Environment Setup Chapter. We also assume that you have a bit of working knowledge on Spring

Spring Boot – Internationalization

Spring Boot – Internationalization ”; Previous Next Internationalization is a process that makes your application adaptable to different languages and regions without engineering changes on the source code. In ither words, Internationalization is a readiness of Localization. In this chapter, we are going to learn in detail about How to implement the Internationalization in Spring Boot. Dependencies We need the Spring Boot Starter Web and Spring Boot Starter Thymeleaf dependency to develop a web application in Spring Boot. Maven <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> Gradle compile(”org.springframework.boot:spring-boot-starter-web”) compile group: ”org.springframework.boot”, name: ”spring-boot-starter-thymeleaf” LocaleResolver We need to determine default Locale of your application. We need to add the LocaleResolver bean in our Spring Boot application. @Bean public LocaleResolver localeResolver() { SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver(); sessionLocaleResolver.setDefaultLocale(Locale.US); return sessionLocaleResolver; } LocaleChangeInterceptor LocaleChangeInterceptor is a used to change the new Locale based on the value of the language parameter added to a request. @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName(“language”); return localeChangeInterceptor; } To take this effect, we need to add the LocaleChangeInterceptor into the application’s registry interceptor. The configuration class should extend the WebMvcConfigurerAdapter class and override the addInterceptors() method. @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } Messages Sources Spring Boot application by default takes the message sources from src/main/resources folder under the classpath. The default locale message file name should be message.properties and files for each locale should name as messages_XX.properties. The “XX” represents the locale code. All the message properties should be used as key pair values. If any properties are not found on the locale, the application uses the default property from messages.properties file. The default messages.properties will be as shown − welcome.text=Hi Welcome to Everyone The French language messages_fr.properties will be as shown − welcome.text=Salut Bienvenue à tous Note − Messages source file should be saved as “UTF-8” file format. HTML file In the HTML file, use the syntax #{key} to display the messages from the properties file. <h1 th:text = “#{welcome.text}”></h1> The complete code 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>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath /> </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-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </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.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” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-web”) compile group: ”org.springframework.boot”, name: ”spring-boot-starter-thymeleaf” testCompile(”org.springframework.boot:spring-boot-starter-test”) } The main Spring Boot application class file is given below − package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } The controller class file is given below − package com.tutorialspoint.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ViewController { @RequestMapping(“/locale”) public String locale() { return “locale”; } } Configuration class to support the Internationalization package com.tutorialspoint.demo; import java.util.Locale; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.i18n.SessionLocaleResolver; @Configuration public class Internationalization extends WebMvcConfigurerAdapter { @Bean public LocaleResolver localeResolver() { SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver(); sessionLocaleResolver.setDefaultLocale(Locale.US); return sessionLocaleResolver; } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName(“language”); return localeChangeInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } } The Message sources – messages.properties is as shown − welcome.text = Hi Welcome to Everyone The Message sources – message_fr.properties is as shown − welcome.text = Salut Bienvenue à tous The HTML file locale.html should be placed under the templates directory on the classpath as shown − <!DOCTYPE html> <html> <head> <meta charset = “ISO-8859-1″/> <title>Internationalization</title> </head> <body> <h1 th:text = “#{welcome.text}”></h1> </body> </html> You can create an executable JAR file, and run the Spring boot application by using the following Maven or Gradle commands − For Maven, use the following command − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, use the following command − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Now, run the JAR file by using the command as shown − java –jar <JARFILE> You will find that the application has started on the Tomcat port 8080. Now hit the URL http://localhost:8080/locale in your web browser and you can see the following output − The URL http://localhost:8080/locale?language=fr will give you the output as shown − Print Page Previous Next Advertisements ”;

Spring Boot – Service Components

Spring Boot – Service Components ”; Previous Next Service Components are the class file which contains @Service annotation. These class files are used to write business logic in a different layer, separated from @RestController class file. The logic for creating a service component class file is shown here − public interface ProductService { } The class that implements the Interface with @Service annotation is as shown − @Service public class ProductServiceImpl implements ProductService { } Observe that in this tutorial, we are using Product Service API(s) to store, retrieve, update and delete the products. We wrote the business logic in @RestController class file itself. Now, we are going to move the business logic code from controller to service component. You can create an Interface which contains add, edit, get and delete methods using the code as shown below − package com.tutorialspoint.demo.service; import java.util.Collection; import com.tutorialspoint.demo.model.Product; public interface ProductService { public abstract void createProduct(Product product); public abstract void updateProduct(String id, Product product); public abstract void deleteProduct(String id); public abstract Collection<Product> getProducts(); } The following code will let you to create a class which implements the ProductService interface with @Service annotation and write the business logic to store, retrieve, delete and updates the product. package com.tutorialspoint.demo.service; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Service; import com.tutorialspoint.demo.model.Product; @Service public class ProductServiceImpl implements ProductService { private static Map<String, Product> productRepo = new HashMap<>(); static { Product honey = new Product(); honey.setId(“1”); honey.setName(“Honey”); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId(“2”); almond.setName(“Almond”); productRepo.put(almond.getId(), almond); } @Override public void createProduct(Product product) { productRepo.put(product.getId(), product); } @Override public void updateProduct(String id, Product product) { productRepo.remove(id); product.setId(id); productRepo.put(id, product); } @Override public void deleteProduct(String id) { productRepo.remove(id); } @Override public Collection<Product> getProducts() { return productRepo.values(); } } The code here show the Rest Controller class file, here we @Autowired the ProductService interface and called the methods. package com.tutorialspoint.demo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.model.Product; import com.tutorialspoint.demo.service.ProductService; @RestController public class ProductServiceController { @Autowired ProductService productService; @RequestMapping(value = “/products”) public ResponseEntity<Object> getProduct() { return new ResponseEntity<>(productService.getProducts(), HttpStatus.OK); } @RequestMapping(value = “/products/{id}”, method = RequestMethod.PUT) public ResponseEntity<Object> updateProduct(@PathVariable(“id”) String id, @RequestBody Product product) { productService.updateProduct(id, product); return new ResponseEntity<>(“Product is updated successsfully”, HttpStatus.OK); } @RequestMapping(value = “/products/{id}”, method = RequestMethod.DELETE) public ResponseEntity<Object> delete(@PathVariable(“id”) String id) { productService.deleteProduct(id); return new ResponseEntity<>(“Product is deleted successsfully”, HttpStatus.OK); } @RequestMapping(value = “/products”, method = RequestMethod.POST) public ResponseEntity<Object> createProduct(@RequestBody Product product) { productService.createProduct(product); return new ResponseEntity<>(“Product is created successfully”, HttpStatus.CREATED); } } The code for POJO class – Product.java is shown here − package com.tutorialspoint.demo.model; public class Product { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } A main Spring Boot application is given below − package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } The code for Maven build – pom.xml is shown 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>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath/> </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-web</artifactId> </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> The code for Gradle Build – build.gradle is shown 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” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below − For Maven, use the command as shown below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the command as shown below − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under build/libs directory. Run the JAR file by using the command given below − java –jar <JARFILE> Now, the application has started on the Tomcat port 8080 as shown in the image given below − Now hit the below URL’s in POSTMAN application and you can see the output as shown below − GET API URL is − http://localhost:8080/products POST API URL is − http://localhost:8080/products PUT API URL is − http://localhost:8080/products/3 DELETE API URL is − http://localhost:8080/products/3 Print Page Previous Next Advertisements ”;

TestNG – Writing Tests

TestNG – Writing Tests ”; Previous Next Writing a test in TestNG basically involves the following steps − Write the business logic of your test and insert TestNG annotations in your code. Add the information about your test (e.g. the class name, the groups you wish to run, etc.) in a testng.xml file or in build.xml. Run TestNG. Here, we will see one complete example of TestNG testing using POJO class, Business logic class and a test xml, which will be run by TestNG. Create EmployeeDetails.java in /work/testng/src, which is a POJO class. public class EmployeeDetails { private String name; private double monthlySalary; private int age; // @return the name public String getName() { return name; } // @param name the name to set public void setName(String name) { this.name = name; } // @return the monthlySalary public double getMonthlySalary() { return monthlySalary; } // @param monthlySalary the monthlySalary to set public void setMonthlySalary(double monthlySalary) { this.monthlySalary = monthlySalary; } // @return the age public int getAge() { return age; } // @param age the age to set public void setAge(int age) { this.age = age; } } EmployeeDetails class is used to − get/set the value of employee”s name. get/set the value of employee”s monthly salary. get/set the value of employee”s age. Create an EmpBusinessLogic.java in /work/testng/src, which contains business logic. public class EmpBusinessLogic { // Calculate the yearly salary of employee public double calculateYearlySalary(EmployeeDetails employeeDetails) { double yearlySalary = 0; yearlySalary = employeeDetails.getMonthlySalary() * 12; return yearlySalary; } // Calculate the appraisal amount of employee public double calculateAppraisal(EmployeeDetails employeeDetails) { double appraisal = 0; if(employeeDetails.getMonthlySalary() < 10000) { appraisal = 500; } else { appraisal = 1000; } return appraisal; } } EmpBusinessLogic class is used for calculating − the yearly salary of employee. the appraisal amount of employee. Now, let”s create a TestNG class called TestEmployeeDetails.java in /work/testng/src. A TestNG class is a Java class that contains at least one TestNG annotation. This class contains test cases to be tested. A TestNG test can be configured by @BeforeXXX and @AfterXXX annotations (we will see this in the chapter TestNG – Execution Procedure), which allows to perform some Java logic before and after a certain point. import org.testng.Assert; import org.testng.annotations.Test; public class TestEmployeeDetails { EmpBusinessLogic empBusinessLogic = new EmpBusinessLogic(); EmployeeDetails employee = new EmployeeDetails(); @Test public void testCalculateAppriasal() { employee.setName(“Rajeev”); employee.setAge(25); employee.setMonthlySalary(8000); double appraisal = empBusinessLogic.calculateAppraisal(employee); Assert.assertEquals(500, appraisal, 0.0, “500”); } // Test to check yearly salary @Test public void testCalculateYearlySalary() { employee.setName(“Rajeev”); employee.setAge(25); employee.setMonthlySalary(8000); double salary = empBusinessLogic.calculateYearlySalary(employee); Assert.assertEquals(96000, salary, 0.0, “8000”); } } TestEmployeeDetails class is used for testing the methods of EmpBusinessLogic class. It does the following − Tests the yearly salary of the employee. Tests the appraisal amount of the employee. Before you can run the tests, you must configure TestNG using a special XML file, conventionally named testng.xml. The syntax for this file is very simple, and its contents are as shown below. Create this file in /work/testng/src. <?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 = “TestEmployeeDetails”/> </classes> </test> </suite> Details of the above file are as follows − A suite is represented by one XML file. It can contain one or more tests and is defined by the <suite> tag. Tag <test> represents one test and can contain one or more TestNG classes. <class> tag represents a TestNG class. It is a Java class that contains at least one TestNG annotation. It can contain one or more test methods. Compile the Test case classes using javac. /work/testng/src$ javac EmployeeDetails.java EmpBusinessLogic.java TestEmployeeDetails.java Now TestNG with the following command − /work/testng/src$ java org.testng.TestNG testng.xml If all has been done correctly, you should see the results of your tests in the console. Furthermore, TestNG creates a very nice HTML report in a folder called test-output that is automatically created in the current directory. If you open it and load index.html, you will see a page similar to the one in the image below − Print Page Previous Next Advertisements ”;

Spring Boot – Eureka Server

Spring Boot – Eureka Server ”; Previous Next Eureka Server is an application that holds the information about all client-service applications. Every Micro service will register into the Eureka server and Eureka server knows all the client applications running on each port and IP address. Eureka Server is also known as Discovery Server. In this chapter, we will learn in detail about How to build a Eureka server. Building a Eureka Server Eureka Server comes with the bundle of Spring Cloud. For this, we need to develop the Eureka server and run it on the default port 8761. Visit the Spring Initializer homepage https://start.spring.io/ and download the Spring Boot project with Eureka server dependency. It is shown in the screenshot below − After downloading the project in main Spring Boot Application class file, we need to add @EnableEurekaServer annotation. The @EnableEurekaServer annotation is used to make your Spring Boot application acts as a Eureka Server. The code for main Spring Boot application class file is as shown below − package com.tutorialspoint.eurekaserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class EurekaserverApplication { public static void main(String[] args) { SpringApplication.run(EurekaserverApplication.class, args); } } Make sure Spring cloud Eureka server dependency is added in your build configuration file. The code for Maven user dependency is shown below − <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> The code for Gradle user dependency is given below − compile(”org.springframework.cloud:spring-cloud-starter-eureka-server”) 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>eurekaserver</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>eurekaserver</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> <spring-cloud.version>Edgware.RELEASE</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <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() } ext { springCloudVersion = ”Edgware.RELEASE” } dependencies { compile(”org.springframework.cloud:spring-cloud-starter-eureka-server”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } dependencyManagement { imports { mavenBom “org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}” } } By default, the Eureka Server registers itself into the discovery. You should add the below given configuration into your application.properties file or application.yml file. application.properties file is given below − eureka.client.registerWithEureka = false eureka.client.fetchRegistry = false server.port = 8761 The application.yml file is given below − eureka: client: registerWithEureka: false fetchRegistry: false server: port: 8761 Now, you can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands shown below − For Maven, use the command as shown below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the command shown below − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Now, run the JAR file by using the following command − java –jar <JARFILE> You can find that the application has started on the Tomcat port 8761 as shown below − Now, hit the URL http://localhost:8761/ in your web browser and you can find the Eureka Server running on the port 8761 as shown below − Print Page Previous Next Advertisements ”;

TestNG – Dependency Test

TestNG – Dependency Test ”; Previous Next Sometimes, you may need to invoke methods in a test case in a particular order, or you may want to share some data and state between methods. This kind of dependency is supported by TestNG, as it supports the declaration of explicit dependencies between test methods. TestNG allows you to specify dependencies either with − Using attribute dependsOnMethods in @Test annotations, OR. Using attribute dependsOnGroups in @Test annotations. Example Using dependsOnMethods Create a Class Create a java class to be tested, say, MessageUtil.java in /work/testng/src. public class MessageUtil { private String message; // Constructor // @param message to be printed public MessageUtil(String message) { this.message = message; } // prints the message public String printMessage() { System.out.println(message); return message; } // add “Hi!” to the message public String salutationMessage() { message = “Hi!” + message; System.out.println(message); return message; } } Create Test Case Class Create a java test class, say, DependencyTestUsingAnnotation.java in /work/testng/src. Add test methods, testPrintMessage() and testSalutationMessage(), and initEnvironmentTest(), to your test class. Add attribute dependsOnMethods = {“initEnvironmentTest”} to the @Test annotation of testSalutationMessage() method. Following are the DependencyTestUsingAnnotation.java contents. import org.testng.Assert; import org.testng.annotations.Test; public class DependencyTestUsingAnnotation { String message = “Manisha”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { System.out.println(“Inside testPrintMessage()”); message = “Manisha”; Assert.assertEquals(message, messageUtil.printMessage()); } @Test(dependsOnMethods = { “initEnvironmentTest” }) public void testSalutationMessage() { System.out.println(“Inside testSalutationMessage()”); message = “Hi!” + “Manisha”; Assert.assertEquals(message, messageUtil.salutationMessage()); } @Test public void initEnvironmentTest() { System.out.println(“This is initEnvironmentTest”); } } Create testng.xml Create testng.xml in /work/testng/src to execute test case(s). <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd” > <suite name = “Suite1”> <test name = “test1”> <classes> <class name = “DependencyTestUsingAnnotation” /> </classes> </test> </suite> Compile the MessageUtil, Test case classes using javac. /work/testng/src$ javac MessageUtil.java DependencyTestUsingAnnotation.java Now, run the testng.xml, which will run the testSalutationMessage() method only after the execution of initEnvironmentTest() method. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. This is initEnvironmentTest Inside testPrintMessage() Manisha Inside testSalutationMessage() Hi!Manisha =============================================== Suite1 Total tests run: 3, Failures: 0, Skips: 0 =============================================== Example Using dependsOnGroups You can also have methods that depend on entire groups. Let”s have an example to demonstrate this. Create a Class Create a java class to be tested, say, MessageUtil.java in /work/testng/src. public class MessageUtil { private String message; // Constructor // @param message to be printed public MessageUtil(String message) { this.message = message; } // prints the message public String printMessage() { System.out.println(message); return message; } // add “Hi!” to the message public String salutationMessage() { message = “Hi!” + message; System.out.println(message); return message; } } Create Test Case Class Create a java test class, say, DependencyTestUsingAnnotation.java. Add test methods, testPrintMessage() testSalutationMessage(), and initEnvironmentTest() to your test class, and add them to the group “init”. Add the attribute dependsOnMethods = {“init.*”} to the @Test annotation of testSalutationMessage() method. Create a java class file named DependencyTestUsingAnnotation.java in /work/testng/src. import org.testng.Assert; import org.testng.annotations.Test; public class DependencyTestUsingAnnotation { String message = “Manisha”; MessageUtil messageUtil = new MessageUtil(message); @Test(groups = { “init” }) public void testPrintMessage() { System.out.println(“Inside testPrintMessage()”); message = “Manisha”; Assert.assertEquals(message, messageUtil.printMessage()); } @Test(dependsOnGroups = { “init.*” }) public void testSalutationMessage() { System.out.println(“Inside testSalutationMessage()”); message = “Hi!” + “Manisha”; Assert.assertEquals(message, messageUtil.salutationMessage()); } @Test(groups = { “init” }) public void initEnvironmentTest() { System.out.println(“This is initEnvironmentTest”); } } In this example, testSalutationMessage() is declared as depending on any group, matching the regular expression “init.*”, which guarantees that the methods testPrintMessage() and initEnvironmentTest() will always be invoked before testSalutationMessage(). If a method depended upon fails, and you have a hard dependency on it (alwaysRun=false, which is the default), the methods that depend on it are not marked as FAIL but as SKIP. Skipped methods will be reported as such in the final report (in a color that is neither Red nor Green in HTML), which is important since skipped methods are not necessarily failures. Create testng.xml Create testng.xml in /work/testng/src to execute test case(s). <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd” > <suite name = “Suite1”> <test name = “test1”> <classes> <class name = “DependencyTestUsingAnnotation” /> </classes> </test> </suite> Compile the MessageUtil, Test case classes using javac. /work/testng/src$ javac MessageUtil.java DependencyTestUsingAnnotation.java Now, run the testng.xml, which will run the testSalutationMessage() method only after the execution of initEnvironmentTest() method. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. This is initEnvironmentTest Inside testPrintMessage() Manisha Inside testSalutationMessage() Hi!Manisha =============================================== Suite1 Total tests run: 3, Failures: 0, Skips: 0 =============================================== dependsOnGroups Vs dependsOnMethods On using groups, we are no longer exposed to refactoring problems. As long as we don’t modify the dependsOnGroups or groups attributes, our tests will keep running with the proper dependencies set up. Whenever a new method needs to be added in the dependency graph, all we need to do is put it in the right group and make sure it depends on the correct group. We don’t need to modify any other method. Print Page Previous Next Advertisements ”;