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

Spring Cloud Configuration Client

Spring Boot – Cloud Configuration Client ”; Previous Next Some applications may need configuration properties that may need a change and developers may need to take them down or restart the application to perform this. However, this might be lead to downtime in production and the need of restarting the application. Spring Cloud Configuration Server lets developers to load the new configuration properties without restarting the application and without any downtime. Working with Spring Cloud Configuration Server First, download the Spring Boot project from https://start.spring.io/ and choose the Spring Cloud Config Client dependency. Now, add the Spring Cloud Starter Config dependency in your build configuration file. Maven users can add the following dependency into the pom.xml file. <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> Gradle users can add the following dependency into the build.gradle file. compile(”org.springframework.cloud:spring-cloud-starter-config”) Now, you need to add the @RefreshScope annotation to your main Spring Boot application. The @RefreshScope annotation is used to load the configuration properties value from the Config server. package com.example.configclient; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.context.config.annotation.RefreshScope; @SpringBootApplication @RefreshScope public class ConfigclientApplication { public static void main(String[] args) { SpringApplication.run(ConfigclientApplication.class, args); } } Now, add the config server URL in your application.properties file and provide your application name. Note − http://localhost:8888 config server should be run before starting the config client application. spring.application.name = config-client spring.cloud.config.uri = http://localhost:8888 The code for writing a simple REST Endpoint to read the welcome message from the configuration server is given below − package com.example.configclient; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RefreshScope @RestController public class ConfigclientApplication { @Value(“${welcome.message}”) String welcomeText; public static void main(String[] args) { SpringApplication.run(ConfigclientApplication.class, args); } @RequestMapping(value = “/”) public String welcomeText() { return welcomeText; } } You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands − For Maven, you can use the command 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 command shown here: java –jar <JARFILE> Now, the application has started on the Tomcat port 8080 as shown here − You can see the log in console window; config-client application is fetching the configuration from the https://localhost:8888 2017-12-08 12:41:57.682 INFO 1104 — [ main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at: http://localhost:8888 Now hit the URL, http://localhost:8080/ welcome message is loaded from the Configuration server. Now, go and change the property value on the Configuration server and hit the actuator Endpoint POST URL http://localhost:8080/refresh and see the new configuration property value in the URL http://localhost:8080/ 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 ”;