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
pyspark

greatest() and least() in pyspark

In this post, we will learn the functions greatest() and least() in pyspark.

greatest() in pyspark

Both the functions greatest() and least() helps in identifying the greater and smaller value among few of the columns.

Creating dataframe

With the below sample program, a dataframe can be created which could be used in the further part of the program.

To understand the creation of dataframe better, please refer to the earlier post

Sample program
from pyspark.sql import SparkSession
from pyspark import SparkContext
sc = SparkContext()
spark = SparkSession(sc)
from pyspark.sql import Row
df=sc.parallelize([Row(name='Gokul',Class=10,level1=480,level2=380,level3=280,level4=520,grade='A'),Row(name='Usha',Class=12,level1=670,level2=720,level3=870,level4=920,grade='A'),Row(name='Rajesh',Class=12,level1=180,level2=560,level3=660,level4=850,grade='B')]).toDF()
print("Printing the dataframe df below")
Output
Printing the dataframe df below
+-----+-----+------+------+------+------+------+
|Class|grade|level1|level2|level3|level4|  name|
+-----+-----+------+------+------+------+------+
|   10|    A|   480|   380|   280|   520| Gokul|
|   12|    A|   670|   720|   870|   920|  Usha|
|   12|    B|   180|   560|   660|   850|Rajesh|
+-----+-----+------+------+------+------+------+
greatest() in pyspark

In order to compare the multiple columns row-wise, the greatest and least function can be used.

In the below program, the four columns level1,level2,level3,level4 are getting compared to find the larger value.

Sample program
from pyspark.sql.functions import greatest,col
df1=df.withColumn("large",greatest(col("level1"),col("level2"),col("level3"),col("level4")))
print("Printing the dataframe df1 below")
df1.show()

The column large is populated with the greater value among the four levels for each row .

Output
Printing the dataframe df1 below
+-----+-----+------+------+------+------+------+-----+
|Class|grade|level1|level2|level3|level4|  name|large|
+-----+-----+------+------+------+------+------+-----+
|   10|    A|   480|   380|   280|   520| Gokul|  520|
|   12|    A|   670|   720|   870|   920|  Usha|  920|
|   12|    B|   180|   560|   660|   850|Rajesh|  850|
+-----+-----+------+------+------+------+------+-----+
least() in pyspark

The least function helps us to get a smaller value among the four levels for each row. 

Sample program
from pyspark.sql.functions import least,col
df2=df.withColumn("Small",least(col("level1"),col("level2"),col("level3"),col("level4")))
print("Printing the dataframe df2 below")
df2.show()
Output
Printing the dataframe df2 below
+-----+-----+------+------+------+------+------+-----+
|Class|grade|level1|level2|level3|level4|  name|Small|
+-----+-----+------+------+------+------+------+-----+
|   10|    A|   480|   380|   280|   520| Gokul|  280|
|   12|    A|   670|   720|   870|   920|  Usha|  670|
|   12|    B|   180|   560|   660|   850|Rajesh|  180|
+-----+-----+------+------+------+------+------+-----+
Reference

https://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html#pyspark.sql.functions.greatest

https://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html#pyspark.sql.functions.least

Categories
pyspark

spark SQL operation in pyspark

In this post, let us look into the spark SQL operation in pyspark with example.

What is spark SQL in pyspark ?

Spark SQL helps us to execute SQL queries. We can store a dataframe as table using the function createOrReplaceTempView.

Sample program

In the following sample program, we are creating an RDD using parallelize method and later converting it into dataframe.

To understand the process of creating dataframes better, Please refer to the below link.

createOrReplaceTempView helps us to register the dataframe created as temporary table.

We can execute all the SQL queries with the help of spark SQL operation in pyspark.

#Libraries required
from pyspark.sql import SparkSession
from pyspark import SparkContext
sc = SparkContext()
spark = SparkSession(sc)
from pyspark.sql import Row
#creating rdd and converting to dataframe
df=sc.parallelize([Row(name='Gokul',Class=10,marks=480,grade='A'),Row(name='Usha',Class=12,marks=450,grade='A'),Row(name='Rajesh',Class=12,marks=430,grade='B')]).toDF()
#Registering temporary table with create dataframedf.createOrReplaceTempView("df_view")
#Executing SQl queries using spark SQl operation
spark.sql("select * from df_view").show()
Output

We can even manipulate the data by filtering based on some conditions using where clause.

But Below is the entire data of the dataframe without any filteration and modification.

+-----+-----+-----+------+
|Class|grade|marks|  name|
+-----+-----+-----+------+
|   10|    A|  480| Gokul|
|   12|    A|  450|  Usha|
|   12|    B|  430|Rajesh|
+-----+-----+-----+------+
Reference

https://stackoverflow.com/questions/32788387/pipelinedrdd-object-has-no-attribute-todf-in-pyspark

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