big decimal number rounding

Limit BigDecimal to n decimal places

Limit BigDecimal to n places only

In java, when you are working with currency and other important precision based calculation, you will use Big Decimal. In some cases you might want to round the number to two (2) decimal places only or, lets say, to n, decimal places.

When to use limited decimal places

There are a couple of cases where you need to round or just to limit the number of decimal places. Once example is when you are working on the currency, after conversion, you may get a long decimal and in that case – rounding will be necessary.

Using big decimal functions for rounding the numbers


BigDecimal bill = new BigDecimal("23.9876546");
bill.setScale(2, RoundingMode.DOWN);

The above will be produce 23 this is because of the flag passed to it of RoundingMode.DOWN. There are other important flags that needs to be passed when rounding.

All the flags are here.

spring upload multiple file

spring upload multiple files

Spring upload multiple files with restful API

Spring upload multiple files with restful api is one of the most requires task. If you are working with spring, chances are high that you are working with file as well.

If you are doing registration, you might need to have multiple files to be uploaded to your server. So how to do spring upload multiple files is what I will be showing you.
Continue reading spring upload multiple files

custom spring validator

custom spring validator

creating custom spring validator

Spring boot comes with lots of validation out of the box, Min, Max, NotNull. But, those are not enough as custom validations are important and needed.

When to use custom spring validator

When there is specific business logic that needs to be validated, custom validation will be to the rescue.

An example of creating a custom spring validator can be the following scenario. On your application there is a registration page.

Let’s say you have a survey sent out before registration and you want a user to fill out a survey using their email associated with it before registration.

When the user comes to your website for registration, one criteria as validated user is a completion of the survey. Here, you can create this validator and use it on more than one forms.

What do I need for custom spring validator

A basic knowledge of java and spring framework is good enough for this. Also make sure if it is worth creating spring custom validator. This is also the same if you are considering custom spring boot validator

Custom Spring validator example, spring validator tutorial

Let us extend the above example and work on it. We would like to have a unique email to be read from database as custom spring validator.

Let’s call it UniqueEmailValidator. This is will be checked mostly during registration and we can assume it can also used in a couple of other places.

First, we need to create a custom target interface


/**
 * Custom email validation
 * Checks if the email already exists or not.
 * 
 * @author Kaleb Woldearegay 
 *
 */
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniqueEmailValidator.class)
public @interface UniqueEmail {
    String message() default "{Email already exists}";
    Class[] groups() default {};
    Class[] payload() default {};
}

You can find the full code on github here.

Then we will need a concrete class that implements the interface


/**
 * Custom email validation. Check if the provided email is unique or not.
 * @author Kaleb Woldearegay 
 *
 */
@Configurable
public class UniqueEmailValidator implements ConstraintValidator {

    private MemberService memberService; //this is injected to the class
    
    public UniqueEmailValidator() {}
    
    @Autowired
    public UniqueEmailValidator(MemberService memberService) {
        this.memberService = memberService;
    }
    
    public void initialize(UniqueEmail constraint) {
    }
 
    public boolean isValid(String email, ConstraintValidatorContext context) {
        if (email == null) {
            return false;
        }
        //actual logic of search for the member goes here..
        Optional member = this.memberService.findByEmail(email);
        return !member.isPresent();
    }

You can see the full class here

The important part of the implementation is the isValid one. That should return the boolean outcome.

That is it, now you have the a full-fledged custom spring validator in created.

You can use it using the annotation @UniqueEmailValidator in your controller or wherever you need to validate.

If you have any questions or comments, let me know.

spring boot validation

spring boot validation

Spring boot validation and Custom Validations

Spring boot validation is probably one of the cool features spring has to provide. Not only spring provided validations but also, it allows custom validation as well.

Custom Spring boot validator will allow you to act like the native validator in your application. Not only that, once you create custom spring validator, you can reuse it.

What is spring validator

Spring validator allows validating the data of the request. The validator will handle basic logic of handling validation than re-inventing the wheel.
Continue reading spring boot validation

Create Tables From Entity Definitions From JPA Spring

How to create database tables from JPA using Hibernate

We know ORM. It will be a nightmare or a bliss based on the angle you are looking at it. This time a bliss :)

If you have started development from the java side and you have all the entities figured out, then hibernate can create the database for you from the entities.

For this example I will be assuming you are using Spring and Hibernate, with that, how do you create the database from the entities

Initial Setup assumptions

So, I will be assuming you have the spring being setup already, the configuration file for your application would look like:


jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/database
jdbc.username = root
jdbc.password = 123
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = create|create-drop|update|none

Here the values to hibernate.hbm2ddl.auto could be create – if you want to crate during the sessionFactory initiation, create-drop, update when you want to update the exiting database when there is a change on the schema or none if you don’t want to do anything with it.

java class not found exception

spring error ClassNotFoundException org.springframework.web.context.ContextLoaderList

ClassNotFoundException org.springframework.web.context.ContextLoaderList

When working on spring framework, you might get this error specially on eclipse. I am assuming you are working on maven and eclipse environment.

The ClassNotFound exception is a bit self explanatory that eclipse could not find the mentioned class ContextLoaderList

The web.xml file for the spring configuration might look like


<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>/WEB-INF/application-context.xml</param-value>
 </context-param>

 <listener>
   <listener-class>
         org.springframework.web.context.ContextLoaderListener
   </listener-class>
 </listener>

With this, you might have similar file like application-context in the WEB-INF path

How to fix ClassNotFoundException for ContextLoaderList

The problem will during deployment. It is not basically compile time error. It is rather runtime error.

So, we have to make sure the jar responsible for this class is available in the classpath that eclipse is reading.

Pom dependency check

Make sure you have the same/similar configuration as the one listed below on your pom file.


		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
	
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
	
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

You can have the right version for your spring in the parameter section or you can just replace it with the current version you have.

Using Deployment Assembly fix in eclipse

As we know, it is a deployment time problem, hence we have to tell the assembly where it can get its dependencies.

      Right click on the project
      Go to/search for Deployment Assembly
      Click on Add
      Select on Java Build path entries
      Select all the maven dependencies
      Finish
      Clean and build the project

Either of the above methods should fix the problem

The superclass “javax.servlet.http.HttpServlet” was not found on the Java Build Path

The superclass “javax.servlet.http.HttpServlet” was not found on the Java Build Path error in java webapp

If you are using eclipse, this might be due to project facet, right click on the project, go to project facet and select Runtimes and check the server you have configured.

if the app you are running is not spring or other web app framework that already comprised of servlet, then you need to add servlet to the build path.

You can add the servlet either through dependency management tools like gradle and maven or you can add it to the project lib file and compile it.

Also, you can add the dependency to servlet in your pom and get rid of the problem.


<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>

spring boot

Spring Data error: getOutputStream() has already been called for this response

Spring data with spring boot error when using mapping

Spring boot has made life of the java developers a bliss. Thanks a million for the dedicated guys in spring.

Saying that, if you are working typical database related project with spring boot, you might have some error like this


java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:624) ~[tomcat-embed-core-8.5.16.jar!/:8.5.16]
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:211) ~[tomcat-embed-core-8.5.16.jar!/:8.5.16]
Continue reading Spring Data error: getOutputStream() has already been called for this response