Spring Boot – Unit Test Cases ”; Previous Next Unit Testing is a one of the testing done by the developers to make sure individual unit or component functionalities are working fine. In this tutorial, we are going to see how to write a unit test case by using Mockito and Web Controller. Mockito For injecting Mockito Mocks into Spring Beans, we need to add the Mockito-core dependency in our build configuration file. Maven users can add the following dependency in your pom.xml file. <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.13.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> Gradle users can add the following dependency in the build.gradle file. compile group: ”org.mockito”, name: ”mockito-core”, version: ”2.13.0” testCompile(”org.springframework.boot:spring-boot-starter-test”) The code to write a Service class which contains a method that returns the String value is given here. package com.tutorialspoint.mockitodemo; import org.springframework.stereotype.Service; @Service public class ProductService { public String getProductName() { return “Honey”; } } Now, inject the ProductService class into another Service class file as shown. package com.tutorialspoint.mockitodemo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class OrderService { @Autowired ProductService productService; public OrderService(ProductService productService) { this.productService = productService; } public String getProductName() { return productService.getProductName(); } } The main Spring Boot application class file is given below − package com.tutorialspoint.mockitodemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MockitoDemoApplication { public static void main(String[] args) { SpringApplication.run(MockitoDemoApplication.class, args); } } Then, configure the Application context for the tests. The @Profile(“test”) annotation is used to configure the class when the Test cases are running. package com.tutorialspoint.mockitodemo; import org.mockito.Mockito; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Profile; @Profile(“test”) @Configuration public class ProductServiceTestConfiguration { @Bean @Primary public ProductService productService() { return Mockito.mock(ProductService.class); } } Now, you can write a Unit Test case for Order Service under the src/test/resources package. package com.tutorialspoint.mockitodemo; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @SpringBootTest @ActiveProfiles(“test”) @RunWith(SpringJUnit4ClassRunner.class) public class MockitoDemoApplicationTests { @Autowired private OrderService orderService; @Autowired private ProductService productService; @Test public void whenUserIdIsProvided_thenRetrievedNameIsCorrect() { Mockito.when(productService.getProductName()).thenReturn(“Mock Product Name”); String testName = orderService.getProductName(); Assert.assertEquals(“Mock Product Name”, testName); } } The complete code for 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>mockito-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>mockito-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.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.13.0</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.mockito”, name: ”mockito-core”, version: ”2.13.0” testCompile(”org.springframework.boot:spring-boot-starter-test”) } You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle1 commands. For Maven, you can use the command as shown − mvn clean install You can see the test results in console window. For Gradle, you can use the command as shown − gradle clean build You can see the rest results in console window. Print Page Previous Next Advertisements ”;
Category: Java
TestNG – Basic Annotations
TestNG – Basic Annotations ”; Previous Next The traditional way to indicate test methods in JUnit 3 is by prefixing their names with test. This is a very effective method for tagging certain methods in a class as having a special meaning, but the naming doesn’t scale very well (what if we want to add more tags for different frameworks?) and is rather inflexible (what if we want to pass additional parameters to the testing framework?). Annotations were formally added to the Java language in JDK 5, and TestNG made the choice to use annotations to annotate test classes. Here is the list of annotations that TestNG supports − Sr.No. Annotation & Description 1 @BeforeSuite The annotated method will be run only once before all tests in this suite have run. 2 @AfterSuite The annotated method will be run only once after all tests in this suite have run. 3 @BeforeClass The annotated method will be run only once before the first test method in the current class is invoked. 4 @AfterClass The annotated method will be run only once after all the test methods in the current class have run. 5 @BeforeTest The annotated method will be run before any test method belonging to the classes inside the <test> tag is run. 6 @AfterTest The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run. 7 @BeforeGroups The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked. 8 @AfterGroups The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked. 9 @BeforeMethod The annotated method will be run before each test method. 10 @AfterMethod The annotated method will be run after each test method. 11 @DataProvider Marks a method as supplying data for a test method. The annotated method must return an Object[ ][ ], where each Object[ ] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation. 12 @Factory Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[ ]. 13 @Listeners Defines listeners on a test class. 14 @Parameters Describes how to pass parameters to a @Test method. 15 @Test Marks a class or a method as a part of the test. Benefits of Using Annotations Following are some of the benefits of using annotations − TestNG identifies the methods it is interested in, by looking up annotations. Hence, method names are not restricted to any pattern or format. We can pass additional parameters to annotations. Annotations are strongly typed, so the compiler will flag any mistakes right away. Test classes no longer need to extend anything (such as TestCase, for JUnit 3). Print Page Previous Next Advertisements ”;
Rest Controller Unit Test
Spring Boot – Rest Controller Unit Test ”; Previous Next Spring Boot provides an easy way to write a Unit Test for Rest Controller file. With the help of SpringJUnit4ClassRunner and MockMvc, we can create a web application context to write Unit Test for Rest Controller file. Unit Tests should be written under the src/test/java directory and classpath resources for writing a test should be placed under the src/test/resources directory. For Writing a Unit Test, we need to add the Spring Boot Starter Test dependency in your build configuration file as shown below. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> Gradle users can add the following dependency in your build.gradle file. testCompile(”org.springframework.boot:spring-boot-starter-test”) Before writing a Test case, we should first build RESTful web services. For further information on building RESTful web services, please refer to the chapter on the same given in this tutorial. Writing a Unit Test for REST Controller In this section, let us see how to write a Unit Test for the REST Controller. First, we need to create Abstract class file used to create web application context by using MockMvc and define the mapToJson() and mapFromJson() methods to convert the Java object into JSON string and convert the JSON string into Java object. package com.tutorialspoint.demo; import java.io.IOException; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = DemoApplication.class) @WebAppConfiguration public abstract class AbstractTest { protected MockMvc mvc; @Autowired WebApplicationContext webApplicationContext; protected void setUp() { mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } protected String mapToJson(Object obj) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.writeValueAsString(obj); } protected <T> T mapFromJson(String json, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(json, clazz); } } Next, write a class file that extends the AbstractTest class and write a Unit Test for each method such GET, POST, PUT and DELETE. The code for GET API Test case is given below. This API is to view the list of products. @Test public void getProductsList() throws Exception { String uri = “/products”; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri) .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); Product[] productlist = super.mapFromJson(content, Product[].class); assertTrue(productlist.length > 0); } The code for POST API test case is given below. This API is to create a product. @Test public void createProduct() throws Exception { String uri = “/products”; Product product = new Product(); product.setId(“3”); product.setName(“Ginger”); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(201, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, “Product is created successfully”); } The code for PUT API Test case is given below. This API is to update the existing product. @Test public void updateProduct() throws Exception { String uri = “/products/2”; Product product = new Product(); product.setName(“Lemon”); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri) .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, “Product is updated successsfully”); } The code for Delete API Test case is given below. This API will delete the existing product. @Test public void deleteProduct() throws Exception { String uri = “/products/2”; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, “Product is deleted successsfully”); } The full Controller Test class file is given below − package com.tutorialspoint.demo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import com.tutorialspoint.demo.model.Product; public class ProductServiceControllerTest extends AbstractTest { @Override @Before public void setUp() { super.setUp(); } @Test public void getProductsList() throws Exception { String uri = “/products”; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri) .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); Product[] productlist = super.mapFromJson(content, Product[].class); assertTrue(productlist.length > 0); } @Test public void createProduct() throws Exception { String uri = “/products”; Product product = new Product(); product.setId(“3”); product.setName(“Ginger”); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(201, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, “Product is created successfully”); } @Test public void updateProduct() throws Exception { String uri = “/products/2”; Product product = new Product(); product.setName(“Lemon”); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, “Product is updated successsfully”); } @Test public void deleteProduct() throws Exception { String uri = “/products/2”; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, “Product is deleted successsfully”); } } You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below − For Maven, you can use the command given below − mvn clean install Now, you can see the test results in console window. For Gradle, you can use the command as shown below − gradle clean build You can see the rest results in console window as shown below. Print Page Previous Next Advertisements ”;
TestNG – Home
TestNG Tutorial PDF Version Quick Guide Resources Job Search Discussion TestNG is a testing framework developed in the lines of JUnit and NUnit, however it introduces some new functionalities that make it more powerful and easier to use. TestNG is designed to cover all categories of tests: unit, functional, end-to-end, integration, etc., and it requires JDK 5 or higher. This tutorial provides a good understanding on TestNG framework needed to test an enterprise-level application to deliver it with robustness and reliability. Audience This tutorial is designed for software professionals interested in learning the features of TestNG Framework in simple and easy steps and implement it in practice. Prerequisites Before proceeding with this tutorial, you should have a basic understanding of Java programming language, text editor, and execution of programs, etc. As you are going to use TestNG to handle all levels of Java project testing, it will be helpful if you have a prior knowledge of software development and software testing processes. Print Page Previous Next Advertisements ”;
TestNG – Environment
TestNG – Environment ”; Previous Next TestNG is a framework for Java, so the very first requirement is to have JDK installed in your machine. System Requirement JDK 1.7 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 “15.0.2” 2021-01-19 Java(TM) SE Runtime Environment (build 15.0.2+7-27) Java HotSpot(TM) 64-Bit Server VM (build 15.0.2+7-27, mixed mode, sharing) Linux openjdk version “11.0.11” 2021-04-20 OpenJDK Runtime Environment (build 11.0.11+9-Ubuntu-0ubuntu2.20.04) OpenJDK 64-Bit Server VM (build 11.0.11+9-Ubuntu-0ubuntu2.20.04, mixed mode, sharing) 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 FilesJavajdk15.0.2. Linux export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64/bin/java. You can also set this environment variable in the /etc/environment. Restart the machine after setting else it will be lost in the session. 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 or from here. At the time of writing this tutorial, we have downloaded testng-7.4.jar and copied it onto /work/testng folder. OS Archive name Windows testng-7.4.jar Linux testng-7.4.jar Mac testng-7.4.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-7.4.jar at the location /work/testng. OS Description Windows Set the environment variable TESTNG_HOME to C:testng. Linux export TESTNG_HOME=/work/testng. You can also set this environment variable in the /etc/environment. Restart the machine after setting else it will be lost in the session. 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-7.4.jar. Linux export CLASSPATH=$CLASSPATH:$TESTNG_HOME/testng-7.4.jar. This classpath is applicable only for current session. Once the current command termical closes, you will have to reset it. Mac export CLASSPATH=$CLASSPATH:$TESTNG_HOME/testng-7.4.jar. Step 6: Test TestNG Setup Create a java class file named TestNGSimpleTest at /work/testng/src 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 /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 = “TestNGSimpleTest”/> </classes> </test> </suite> Step 7: Verify the Result Compile the class using javac compiler as follows − /work/testng/src$ javac TestNGSimpleTest.java Now, invoke the testng.xml to see the result − /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. =============================================== Suite Total tests run: 1, Passes: 1, Failures: 0, Skips: 0 =============================================== Print Page Previous Next Advertisements ”;
Example – Tables
Swing Examples – Tables ”; Previous Next Learn how to play with Tables in Swing UI programming. Here are most commonly used examples − How to create a table in Swing? How to add sort functionality to each header of a table in Swing? Print Page Previous Next Advertisements ”;
Struts2 – Discussion
Discuss Struts 2 ”; Previous Next Apache Struts 2 is an elegant, extensible framework for creating enterprise-ready Java web applications. This framework is designed to streamline the full development cycle from building, to deploying and maintaining applications over time. Apache Struts 2 was originally known as Web Work 2. This tutorial will teach you, how to use Apache Struts for creating enterprise-ready Java web applications in simple and easy steps. Print Page Previous Next Advertisements ”;
Spring Boot – Twilio
Spring Boot – Twilio ”; Previous Next Twilio is a 3rd party application used to send SMS and make voice calls from our application. It allows us to send the SMS and make voice calls programmatically. In this chapter, you are going to learn how to implement the SMS sending and making voice calls by using Spring Boot with Twilio. Note − We used the Trail account in Twilio to send the SMS and making voice calls. You can learn more about Twilio at www.twilio.com. First, we need to add the Twilio dependency in our build configuration file. Maven users can add the following dependency in the pom.xml file. <dependency> <groupId>com.twilio.sdk</groupId> <artifactId>twilio</artifactId> <version>7.16.1</version> </dependency> Gradle users can add the following dependency in the build.gradle file. compile group: “com.twilio.sdk”, name:”twilio”, version: “7.16.1” Now, initialize the Twilio account with ACCOUNT_SID and AUTH_ID in static block as shown − static { Twilio.init(ACCOUNT_SID, AUTH_ID); } Sending SMS To send the SMS, we need to provide a from-number and to-number to the Message.create() method. Message body content also we need to provide for the method Message.creator()as shown − Message.creator(new PhoneNumber(“to-number”), new PhoneNumber(“from-number”), “Message from Spring Boot Application”).create(); The main Spring Boot application class file looks below. package com.tutorialspoint.smsdemo; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.twilio.Twilio; import com.twilio.rest.api.v2010.account.Message; import com.twilio.type.PhoneNumber; @SpringBootApplication public class SmsdemoApplication implements ApplicationRunner { private final static String ACCOUNT_SID = “<your-account-sid>”; private final static String AUTH_ID = “<your-auth-id>”; static { Twilio.init(ACCOUNT_SID, AUTH_ID); } public static void main(String[] args) { SpringApplication.run(SmsdemoApplication.class, args); } @Override public void run(ApplicationArguments arg0) throws Exception { Message.creator(new PhoneNumber(“to-number”), new PhoneNumber(“from-number”), “Message from Spring Boot Application”).create(); } } The complete code to 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>smsdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>smsdemo</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.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.twilio.sdk</groupId> <artifactId>twilio</artifactId> <version>7.16.1</version> </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”) testCompile(”org.springframework.boot:spring-boot-starter-test”) compile group: “com.twilio.sdk”, name:”twilio”, version: “7.11.+” } 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 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 as given below − java –jar <JARFILE> Now, you will receive the SMS to your “to-number”. Message received to “to-number”. Sent from your Twilio trail account – Message from Spring Boot Application Note − In this example, we used the Trail account. So, you should verify the numbers before sending the SMS. Voice Calls To make voice calls by using Twilio, we need to call the Call.creator() method. For this method, we need to provide a to-number, from-number, and voice-note as shown here. Call.creator(new PhoneNumber(“<to-number>”), new PhoneNumber(“<from-number>”), new URI(“http://demo.twilio.com/docs/voice.xml”)).create(); The code for main Spring Boot application class file is given below. package com.tutorialspoint.smsdemo; import java.net.URI; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.twilio.Twilio; import com.twilio.rest.api.v2010.account.Call; import com.twilio.type.PhoneNumber; @SpringBootApplication public class SmsdemoApplication implements ApplicationRunner { private final static String ACCOUNT_SID = “<ACCOUNT-SID>”; private final static String AUTH_ID = “AUTH-ID”; static { Twilio.init(ACCOUNT_SID, AUTH_ID); } public static void main(String[] args) { SpringApplication.run(SmsdemoApplication.class, args); } @Override public void run(ApplicationArguments arg0) throws Exception { Call.creator(new PhoneNumber(“<to-number>”), new PhoneNumber(“<from-number>”), new URI(“http://demo.twilio.com/docs/voice.xml”)).create(); } } 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>smsdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>smsdemo</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.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.twilio.sdk</groupId> <artifactId>twilio</artifactId> <version>7.16.1</version> </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”) testCompile(”org.springframework.boot:spring-boot-starter-test”) compile group: “com.twilio.sdk”, name:”twilio”, version: “7.11.+” } 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 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. Now, run the JAR file by using the command given here − java –jar <JARFILE> Now, you will receive call to your “to-number” from Twilio. Press any key after attending the call, you will hear the voice note from https://demo.twilio.com/docs/voice.xml Note − In this example, we used the Trail account. So, you should verify the numbers before making calls. Print Page Previous Next Advertisements ”;
Spring Boot – Creating Docker Image ”; Previous Next Docker is a container management service that eases building and deployment. If you are a beginner to Docker, you can learn about is in detail at this link − https://www.tutorialspoint.com/docker/index.htm In this chapter, we are going to see How to create a Docker image by using Maven and Gradle dependencies for your Spring Boot application. Create Dockerfile First, create a file with the name Dockerfile under the directories src/main/docker with the contents shown below. Note that this file is important to create a Docker image. FROM java:8 VOLUME /tmp ADD dockerapp-0.0.1-SNAPSHOT.jar app.jar RUN bash -c ”touch /app.jar” ENTRYPOINT [“java”,”-Djava.security.egd=file:/dev/./urandom”,”-jar”,”/app.jar”] Maven For Maven, add the Docker Maven plugin into your build configuration file pom.xml <properties> <docker.image.prefix>spring-boot-tutorialspoint</docker.image.prefix> </properties> <build> <plugins> <plugin> <groupId>com.spotify</groupId> <artifactId>docker-maven-plugin</artifactId> <version>1.0.0</version> <configuration> <imageName>${docker.image.prefix}/${project.artifactId}</imageName> <dockerDirectory>src/main/docker</dockerDirectory> <resources> <resource> <directory>${project.build.directory}</directory> <include>${project.build.finalName}.jar</include> </resource> </resources> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> The complete pom.xml file is given below − <?xml version = “1.0” encoding = “UTF-8”?> <project xmlns = “http://maven.apache.org/POM/4.0.0” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>dockerapp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>dockerapp</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> <docker.image.prefix>spring-boot-tutorialspoint</docker.image.prefix> </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>com.spotify</groupId> <artifactId>docker-maven-plugin</artifactId> <version>1.0.0</version> <configuration> <imageName>${docker.image.prefix}/${project.artifactId}</imageName> <dockerDirectory>src/main/docker</dockerDirectory> <resources> <resource> <directory>${project.build.directory}</directory> <include>${project.build.finalName}.jar</include> </resource> </resources> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Now, you can run your application by using the Maven command mvn package docker:build Note − Enable the Expose daemon on tcp://localhost:2375 without TLS. After build success, you can see the output on the console as shown below − Now, see the Docker images by the command using docker images and see the image info on the console. Gradle To build a Docker image by using Gradle build configuration, we need to add the docker plugin and need to write a task buildDocker to create a Docker image. The code for Gradle Docker configuration is given below. buildscript { ….. dependencies { ….. classpath(”se.transmode.gradle:gradle-docker:1.2”) } } group = ”spring-boot-tutorialspoint” ….. apply plugin: ”docker” task buildDocker(type: Docker, dependsOn: build) { applicationName = jar.baseName dockerfile = file(”src/main/docker/Dockerfile”) doFirst { copy { from jar into stageDir } } } The complete build.gradle file is given below. buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) classpath(”se.transmode.gradle:gradle-docker:1.2”) } } group = ”spring-boot-tutorialspoint” apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” apply plugin: ”docker” 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”) } task buildDocker(type: Docker, dependsOn: build) { applicationName = jar.baseName dockerfile = file(”src/main/docker/Dockerfile”) doFirst { copy { from jar into stageDir } } } Now, create a Docker image by using the command shown below − gradle build buildDocker After executing the command, you can see the BUILD SUCCESSFUL log on the console window. Now, see the Docker images by the command using docker images and see the image’s info on the console. Print Page Previous Next Advertisements ”;
Spring Boot – File Handling
Spring Boot – File Handling ”; Previous Next In this chapter, you will learn how to upload and download the file by using web service. File Upload For uploading a file, you can use MultipartFile as a Request Parameter and this API should consume Multi-Part form data value. Observe the code given below − @RequestMapping(value = “/upload”, method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public String fileUpload(@RequestParam(“file”) MultipartFile file) { return null; } The complete code for the same is given below − package com.tutorialspoint.demo.controller; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; @RestController public class FileUploadController { @RequestMapping(value = “/upload”, method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public String fileUpload(@RequestParam(“file”) MultipartFile file) throws IOException { File convertFile = new File(“/var/tmp/”+file.getOriginalFilename()); convertFile.createNewFile(); FileOutputStream fout = new FileOutputStream(convertFile); fout.write(file.getBytes()); fout.close(); return “File is upload successfully”; } } File Download For file download, you should use InputStreamResource for downloading a File. We need to set the HttpHeader Content-Disposition in Response and need to specify the response Media Type of the application. Note − In the following example, file should be available on the specified path where the application is running. @RequestMapping(value = “/download”, method = RequestMethod.GET) public ResponseEntity<Object> downloadFile() throws IOException { String filename = “/var/tmp/mysql.png”; File file = new File(filename); InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); HttpHeaders headers = new HttpHeaders(); headers.add(“Content-Disposition”, String.format(“attachment; filename=”%s””, file.getName())); headers.add(“Cache-Control”, “no-cache, no-store, must-revalidate”); headers.add(“Pragma”, “no-cache”); headers.add(“Expires”, “0”); ResponseEntity<Object> responseEntity = ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType( MediaType.parseMediaType(“application/txt”)).body(resource); return responseEntity; } The complete code for the same is given below − package com.tutorialspoint.demo.controller; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class FileDownloadController { @RequestMapping(value = “/download”, method = RequestMethod.GET) public ResponseEntity<Object> downloadFile() throws IOException { String filename = “/var/tmp/mysql.png”; File file = new File(filename); InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); HttpHeaders headers = new HttpHeaders(); headers.add(“Content-Disposition”, String.format(“attachment; filename=”%s””, file.getName())); headers.add(“Cache-Control”, “no-cache, no-store, must-revalidate”); headers.add(“Pragma”, “no-cache”); headers.add(“Expires”, “0”); ResponseEntity<Object> responseEntity = ResponseEntity.ok().headers(headers).contentLength( file.length()).contentType(MediaType.parseMediaType(“application/txt”)).body(resource); return responseEntity; } } The 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 given below − <?xml version = “1.0” encoding = “UTF-8”?> <project xmlns = “http://maven.apache.org/POM/4.0.0” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>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 given below − buildscript { ext { springBootVersion = ”1.5.8.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } Now 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 given below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under target directory. For Gradle, you ca use the command shown below − sgradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under build/libs directory. Now, run the JAR file by using the following command − java –jar <JARFILE> This will start the application on the Tomcat port 8080 as shown below − Now hit the below URL’s in POSTMAN application and you can see the output as shown below − File upload − http://localhost:8080/upload File download − http://localhost:8080/upload Print Page Previous Next Advertisements ”;