Categories
java

convert JSON string to java object

In this post, we will learn to convert JSON string to java object using GSON

We can convert json string to java object in multiple ways. Among those Gson conversion is familiar and quite easy too.

We need below dependency to convert JSON string to java object

Dependency
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

In this example we are going to convert below json object to java object

{
  "studentId": "001",
  "studentName": "Rajesh",
  "schoolName": "BeginnerBug",
  "department": "Java"
}
Syntax
Student student = gson.fromJson(jsonString, Student.class);
Example
import com.beginnersbug.example.model.Student;
import com.google.gson.Gson;

public class ConvertJsonToJava {

	public static void main(String[] args) {
		try {
			String jsonString = "{\"studentId\":\"001\",\"studentName\":\"Rajesh\",\"schoolName\":\"BeginnerBug\",\"department\":\"Java\"}";
			Gson gson = new Gson();
			Student student = gson.fromJson(jsonString, Student.class);
			System.out.println(student.getStudentName());
			
		} catch (Exception e) {
			e.printStackTrace();

		}
	}
}
Student.java

public class Student {

	private String studentId;

	private String studentName;

	private String schoolName;

	private String department;

	public String getStudentId() {
		return studentId;
	}

	public void setStudentId(String studentId) {
		this.studentId = studentId;
	}

	public String getStudentName() {
		return studentName;
	}

	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}

	public String getSchoolName() {
		return schoolName;
	}

	public void setSchoolName(String schoolName) {
		this.schoolName = schoolName;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

}
Output
Rajesh
Conclusion

From the above code snippet we can easily convert json string to java object

Reference

Json Viewer http://jsonviewer.stack.hu/

Convert string to java object http://www.jsonschema2pojo.org/

Github

https://github.com/rkumar9090/student-example/blob/master/src/main/java/com/beginnersbug/example/ConvertJsonToJava.java

Related Articles

read value from application.properties spring boot

Categories
java spring-boot

read value from application.properties spring boot

In this post, we will learn to read value from application.properties spring boot

In spring boot application we can easily inject the properties value from application.properties or application.yml

Using @value annotation we can inject the properties value from application.properties inside the java code

@value Syntax
@Value("${application.username}")
private String userName;

application.properties
#userName property
application.username=admin

# Add database url here
spring.datasource.url=jdbc:mysql://localhost:3306/beginnersbug
spring.datasource.username=root
spring.datasource.password=password
# Add driver class here 
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

In the below example, we are writing a rest service that will return the properties value from the application.properties

RestController

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class VariableInjectionController {

	@Value("${application.username}")
	private String userName;

	@GetMapping
	public String getUserName() {
		return userName;
	}
}

In the above example, we will return the application. username property via rest service

Default Value

In case of application. username property is not available means, we can set the default value for that property

Default Value Syntax
@Value("${application.name:BegineersBug}")
private String userName;

From the above snippet, it will take userName value as BeginnersBug because we don’t have application.name property in our application.properties

Github Link

https://github.com/rkumar9090/student-service/blob/master/src/main/java/com/beginnersbug/studentservice/controller/VariableInjectionController.java

Related Articles

configure datasource programmatically in spring boot

Categories
spring-boot

unable to determine jdbc url from datasource spring boot

In this post, we will discover about unable to determine jdbc url from datasource spring boot error

Cause of problem

In case if you didn’t configure the properties correctly, then you might face this exception in your application

Solution

Verify below things in your spring boot application

  • dependency in pom.xml
  • database properties in application.properties or application.yml
Dependecies in pom.xml

make sure you have spring data and respective database dependencies in your pom.xml

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>
Application.properties

Verify your application.properties or application.yaml have below database configuration

spring.datasource.url=jdbc:mysql://localhost:3306/beginnersbug
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

After configuring above two properties properly your application should works fine

Related Articles

no main manifest attribute, in – spring boot

Categories
spring-boot

no main manifest attribute, in – spring boot

In this post, we will learn to resolve no main manifest attribute, in – spring boot application

Once your jar is build using maven command, we will attempt to run the jar

This exception will occur if you didn’t add maven build plugin in your pom.xml file

Solution

Add below maven build plugin in your pom.xml

<plugin>
    <groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-maven-plugin</artifactId>
	<executions>
		<execution>
			<goals>
			<goal>repackage</goal>
			</goals>
	    </execution>
	</executions>
</plugin>

After adding above plugin in your pom.xml, Build your spring boot project using maven command mvn clean install

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.0.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<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>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<executions>
					<execution>
						<goals>
							<goal>repackage</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

After adding maven build plugin, you can build and run your spring boot application successfully.

Categories
java spring-boot

configure datasource programmatically in spring boot

In this post, we will learn about configure datasource programmatically in spring boot

In below example we are using mysql as database. We are reading database properties from application.properties using @ConfigurationProperties

Using DataSourceBuilder
    @ConfigurationProperties(prefix = "datasource.custom")
	@Bean
	@Primary
	public DataSource dataSource() {
		return DataSourceBuilder.create().build();
	}

In the above snippet spring boot will create datasource with values from application.properties

datasource.custom.jdbcUrl=jdbc:mysql://localhost:3306/beginnersbug
datasource.custom.username=root
datasource.custom.password=password
datasource.custom.driverClassName=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

make sure your prefix correct matching text. In this example I am using datasource.custom as prefix

CREATE TABLE students (
    id int NOT NULL,
	firstname varchar(255) NOT NULL,
    lastname varchar(255) NOT NULL,    
    department int,
    PRIMARY KEY (id)
);
dependency
<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

Configuration Class

Your configuration class should annotated with @configuration

import javax.sql.DataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class DatasourceConfig {

	@ConfigurationProperties(prefix = "datasource.custom")
	@Bean
	@Primary
	public DataSource dataSource() {
		return DataSourceBuilder.create().build();
	}

}

In this program we are connecting to mysql database. Below is DaoInterface where I am using JpaRepository for CRUD operations

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.beginnersbug.studentservice.model.Student;

@Repository
public interface StudentDao extends JpaRepository<Student, Long> {

}

From Controller class we are invoking DAO interface to retrieve strudents table data


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.beginnersbug.datasource.StudentDao;
import com.beginnersbug.datasource.model.Student;

@RestController()
@RequestMapping("/api/student")
public class StudentController {

	@Autowired
	StudentDao studentsDao;

	@RequestMapping(method = RequestMethod.GET)
	public List<Student> getStudentsList() {
		return studentsDao.findAll();
	}

}
Testing

Hit http://localhost:8080/api/student from Chrome brower, It will return all the values from the students table

Github

https://github.com/rkumar9090/datasource

Related Articles

connect MySQL database from spring boot

Categories
java

com.sun.net.httpserver.httpexchange not found in eclipse

In this post we will learn about com.sun.net.httpserver.httpexchange not found in eclipse

While I am trying to add Http Server in Core java application I faced below exception

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

If you are not to able to add above dependencies in java code, please verify below points

  • You should use java version above 1.6
  • Make sure you have configured correct JDK in your build path

If above things are correct still you are facing the issue means you need to do below thing in eclipse

you need to add com/sun/net/httpserver/ package in the access rule

  • Open Eclipse
  • Navigate to java build path
  • Click on the access rule under JRE System Libray
  • Click on the edit button and add an access rule like below image
Reference

https://stackoverflow.com/questions/13155734/eclipse-cant-recognize-com-sun-net-httpserver-httpserver-package

Related Articles

add rest service in core java application

Categories
java

add rest service in core java application

In this post, we will learn about add rest service in core java application

We are in spring boot world, where exposing a http endpoint is much easier, but when it comes to a standalone java application we will get confused

Java has a feature to expose Http endpoint from a standalone application.
Using import com.sun.net.httpserver.HttpExchange;

In below example, we are exposing an Http endpoint on port number 8080 with endpoint /health

Example

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class HttpServerExample {

	public static void main(String[] args) throws Exception {
		try {
			HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
			server.createContext("/health", new Handler());
			server.setExecutor(null);
			server.start();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	static class Handler implements HttpHandler {
		@Override
		public void handle(HttpExchange t) throws IOException {
			String response = "Up & Running";
			t.sendResponseHeaders(200, response.length());
			OutputStream os = t.getResponseBody();
			os.write(response.getBytes());
			os.close();
		}
	}
}
Output

http://localhost:8080/health

Up & Running

If you are not found com.net.sun.http package in your eclipse follow this URL https://beginnersbug.com/com-sun-net-httpserver-httpexchange-not-found-in-eclipse

Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/HttpServerExample.java

Categories
collections java

convert iterator to list in java

In this tutorial, we will learn convert iterator to list in java

Here we are giving two approach to convert iterator to list in java

Syntax in Java 8
ArrayList<String> list = new ArrayList<String>();
iterator.forEachRemaining(list::add);
Syntax in Java 7
ArrayList<String> list = new ArrayList<String>();
while (iterator.hasNext()) {
  String string = (String) iterator.next();
  list.add(string);
}
Example
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

public class IteratorToList {

	public static void main(String[] args) {

		Iterator<String> iterator = Arrays.asList("Rajesh", "Kumar", "Beginners", "Bug").iterator();
		convertToListJava7(iterator);
		convertToListJava8(iterator);

	}

	/**
	 * Java 7 Approach
	 * 
	 * @param iterator
	 * @return
	 */
	public static ArrayList<String> convertToListJava7(Iterator<String> iterator) {
		ArrayList<String> list = new ArrayList<String>();
		while (iterator.hasNext()) {
			String string = (String) iterator.next();
			list.add(string);
		}

		return list;
	}

	/**
	 * Java 8 Apporach
	 * 
	 * @param iterator
	 * @return
	 */
	public static ArrayList<String> convertToListJava8(Iterator<String> iterator) {
		ArrayList<String> list = new ArrayList<String>();
		iterator.forEachRemaining(list::add);
		return list;
	}

}
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/list/IteratorToList.java

Related Articles

Iterate list using streams in java

Categories
spring-boot

add swagger in spring boot application

In this tutorial, we will learn to add swagger in spring boot application

What is Swagger ?

Swagger is an open-source software framework backed by a large ecosystem of tools that helps developers design, build, document, and consume RESTful web services.

How to add in Spring boot

It is easy to integrate with spring boot. with help of few dependencies and some configuration we can easily integrate with spring boot

Depedency
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.6.1</version>	
</dependency>
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.6.1</version>
</dependency>
Annotation
@EnableSwagger2
Bean
@Bean
	public Docket api() {
		return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any())
				.paths(PathSelectors.any()).build();
	}
Main Class

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
public class StudentServiceApplication {

	public static void main(String[] args) {
		SpringApplication.run(StudentServiceApplication.class, args);
	}

	@Bean
	public Docket api() {
		return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any())
				.paths(PathSelectors.any()).build();
	}
}

Time needed: 10 minutes

Steps

  1. dependency in pom.xml

    add above dependency in pom.xml

  2. Annotation in Configuration file

    add above annotation in a configuration file

  3. Bean method

    add above bean

  4. Testing

    Open http://localhost:8080/swagger-ui.html in browserswagger

Conclusion

With the help of two dependencies and one bean method we can easily add swagger in spring boot application

Related Articles

crud operations in spring boot with Mysql

Categories
spring-boot

Field ‘id’ doesn’t have a default value

Field ‘id’ doesn’t have a default value: You will face this exception when you not properly configured your model class or table

Exception
java.sql.SQLException: Field ‘id’ doesn’t have a default value
Solution
  • Make sure your table has a primary key and Auto_Increment property
  • In the case of Oracle database, your table should have Sequence
  • Your model class should have below properties
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;

To learn more about Spring boot database operations use this link
https://beginnersbug.com/crud-operations-in-spring-boot-with-mysql/

References

https://stackoverflow.com/questions/804514/hibernate-field-id-doesnt-have-a-default-value