Categories
security spring-boot

spring-boot-security using http basic authentication

In this post, we will learn about spring-boot-security using http basic authentication

In this tutorial we will use spring security where we can enable security for our spring applications

Dependency
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>

Add above dependency in your pom.xml

In this example, we are creating two rest endpoints, which I named as hello and hi

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {

	@GetMapping("hello")
	public String getHello() {
		return "Hello";
	}

	@GetMapping("hi")
	public String getHi() {
		return "Hi";
	}

}

Now we can create new class SecurityConfig.java to configure our security
we need to add @Configuration @EnableWebSecurityannotations in our SecurityConfig.java and also we need to extend WebSecurityConfigurerAdapter 

And also we need to override two configure methods in SecurityConfig.java

In the first configure method we need to configure user and role details, Here I added two users with two roles 


import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
		auth.inMemoryAuthentication()
		.withUser("admin").password(encoder.encode("password")).roles("ADMIN").and()
		.withUser("user").password(encoder.encode("pass")).roles("USER");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
		.authorizeRequests().antMatchers("/hello").permitAll()
		.anyRequest().authenticated().and().httpBasic();
		
	}

}

In the above snippet, we allowed /hello endpoint and remaining endpoints are authenticated with httpBasic authentication

We are using PasswordEncoder to encode the password

Run the application as spring boot application

Testing

Conclusion

The above example is a simple spring security authentication using http basic. Here we added user details in-memory authentication

Github

https://github.com/rkumar9090/spring-security

Categories
java

automatic mouse mover in java

In this post, we will do automatic mouse mover in java

We can move the cursor with random directions using below code

Example
import java.awt.Robot;

public class MouseMover {

	public static void main(String[] args) {
		try {
			int xCord = 10;
			int yCord = 20;
			while (true) {

				Robot robot = new Robot();
				robot.mouseMove(xCord++, yCord++);
				System.out.println("Moving mouse to " + xCord + " " + yCord);
				Thread.sleep(10000);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Github

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

Categories
java spring-boot

enable cors in spring boot rest API

In this post we will learn to enable cors in spring boot rest API

For security reasons, browsers prohibit AJAX calls to resources residing outside the current origin.

While we facing cors issue, we need to enable cors in spring boot application explicitly

Enable for whole spring boot

We need to add below class in our spring boot application, this will enable cors for all endpoints

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfig {

	public WebMvcConfigurer corsConfigure() {
		return new WebMvcConfigurerAdapter() {
			public void addCorsMappings(CorsRegistry registry) {
				registry.addMapping("/**");
			}
		};
	}

}
Enable for specific endpoint

Below snippet will enable cors only for endpoint which starts with /api


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfig {

	public WebMvcConfigurer corsConfigure() {
		return new WebMvcConfigurerAdapter() {
			public void addCorsMappings(CorsRegistry registry) {
				registry.addMapping("/api/**");
			}
		};
	}

}
Enable for specific orgins

Below snippet will enable for orgin https://beginnersbug.com

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfig {

	public WebMvcConfigurer corsConfigure() {
		return new WebMvcConfigurerAdapter() {
			public void addCorsMappings(CorsRegistry registry) {
				registry.addMapping("/api/**")
				.allowedOrigins("https://beginnersbug.com");
			}
		};
	}

}
Enable CORS with Annotation

we can enable cors by annotation. we need to mention @crossOrgin annotation in the controller class as like below


import java.util.List;
import java.util.Optional;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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.beginnersbug.studentservice.dao.StudentDao;
import com.beginnersbug.studentservice.model.Student;

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

	@Autowired
	StudentDao studentsDao;

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

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

Related Articles

read value from application.properties spring boot

Categories
date java

change timezone of date in java

In this post, we will learn to change timezone of date in java

In java by default new Date() will give you the system/server timezone.

Syntax
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Example

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ChangeTimeZon {

	public static void main(String[] args) {
		try {
			Date date = new Date();
			System.out.println("Current Date Time : " + date);
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
			// In below line we are mentioned to convert into UTC
			dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
			String utcFormat = dateFormat.format(date);
			System.out.println("After converting into UTC format: " + utcFormat);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
Current Date Time : Thu Jun 18 15:29:35 IST 2020
After converting into UTC format: 2020-06-18 09:59:35 UTC
Conclusion

In the above post, we learned to change timezone of date in java

Github

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

Related Articles

calculate number days between two dates using java

Categories
collections java

join two arraylist in java with example

In this post, we will learn to join two arraylist in java with example

ArrayList is a dynamic array concept in java. We use ArrayList in so many places.

Syntax
list1.addAll(list2);

From the above syntax list2 will added to list1.

Example
import java.util.ArrayList;
import java.util.List;

public class Join2List {

	public static void main(String[] args) {
		try {
			List<String> list1 = new ArrayList<String>();
			List<String> list2 = new ArrayList<String>();

			list1.add("Rajesh");
			list1.add("Usha");

			list2.add("Kumar");
			list2.add("Nandhini");

			System.out.println("---List1 value before adding list2---");
			for (String string : list1) {
				System.out.println(string);
			}

			// Adding list2 to list1
			list1.addAll(list2);

			System.out.println("---List1 value After adding list2---");

			for (String string : list1) {
				System.out.println(string);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
---List1 value before adding list2---
Rajesh
Usha
---List1 value After adding list2---
Rajesh
Usha
Kumar
Nandhini
Github

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

Related Articles

ArrayList in java with example

Categories
java

singleton in java with example

In this post, we will learn singleton in java with example

Singleton is one of the famous design pattern in java. Below are few point of Singleton

  • We Should have the only one instance in the application
  • In below example, we are going to use Lazy Initialization
  • It will create an instance when the application in need
  • We should have a private constructor to avoid outside initialization
public class SingletonExample {

	public static SingletonExample singletonExampleObject = null;

	public String stringVarible = "Singleton string";

	private SingletonExample() {

	}

	public static SingletonExample getSingletonInstance() {
		if (null == singletonExampleObject) {
			singletonExampleObject = new SingletonExample();
		}
		return singletonExampleObject;
	}

}

The above class is an example of Singleton. As mentioned in the above sentence we have a private constructor and static instance of the class

public class Example {

	public static void main(String[] args) {
		try {
			SingletonExample singletonObject = SingletonExample.getSingletonInstance();
			System.out.println(singletonObject.stringVarible);
			singletonObject.stringVarible = "BeginnersBug";

			// Creating another object
			SingletonExample singletonInstance = SingletonExample.getSingletonInstance();
			System.out.println(singletonInstance.stringVarible);
		} catch (Exception e) {
			e.printStackTrace();

		}
	}

}
Singleton string
BeginnersBug

Even though we have two variables for SingletonExample it is sharing same instance

So the Value of stringVaraible is reflected on the second variable

Conclusion

In the above post, we learned about singleton in java with example

Github

https://github.com/rkumar9090/student-example/tree/master/src/main/java/com/beginnersbug/example/singleton

Related Articles

convert java object to JSON string

Categories
java

convert java object to JSON string

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

We can convert Java object to json string using below dependency

Dependency
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>
Syntax
String jsonString = gson.toJson(student);
Example

import com.beginnersbug.example.model.Student;
import com.google.gson.Gson;

public class ConvertJavaToJson {

	public static void main(String[] args) {
		Gson gson = new Gson();
		Student student = new Student();
		student.setStudentId("001");
		student.setStudentName("Rajesh");
		student.setDepartment("JAVA");
		student.setSchoolName("BeginnersBug");

		String jsonString = gson.toJson(student);

		System.out.println(jsonString);

	}
}
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
{"studentId":"001","studentName":"Rajesh","schoolName":"BeginnersBug","department":"JAVA"}
Github

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

Related Articles

convert JSON string to java object

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