Let me introduce a lightweight and sample library called helper-util which I develop. That is a small lightweight java library to help our java projects as an assistant helper utility.
You can get some help like password encoding, validating email, validation String, etc functions and can use many datetime functions by using that helper-util library.
Below are the usage of helper-util library.
- Firstly, add this below dependency inside your
pom.xml
file in your java maven project. - Please check out the latest version in here, maven-central-repository
<dependency>
<groupId>io.github.yewin-mm</groupId>
<artifactId>helper-util</artifactId>
<version>1.0.3</version>
</dependency>
- Copy above dependency and add inside
<dependencies> <dependencies>
tag in yourpom.xml
file. - Refresh or Reload your maven pom file.
- You can check out this library is already in your project or not by checking under External Libraries folder.
- After successfully adding this library in your application, you can use start to use methods in that library.
Usage
- There are six utility classes that you can use.
- CommonUtil -> To use some common methods like get integer length, printing out, etc.
- ValidationUtil -> To validate like empty String, email validation, empty Collection, etc.
- PasswordUtil -> To encode and verify password.
- DateTimeUtil -> To get datetime as per zoneId, two dates different, etc.
- ResponseUtil -> To get formatted microservice response object.
- ConstantUtil -> To use some common constant like error message, info message, etc.
Below are detail explanation.
- CommonUtil
- Here are the sample usage for
CommonUtil class
that you can apply in your application.
String greeting = "hello world";
CommonUtil.printInfo("print hello world"); // no param
CommonUtil.printInfo("print hello: {}", greeting); // one param
CommonUtil.printInfo(greeting, YOUR_LOGGER); // no param and print using your logger
CommonUtil.printInfo("print hello: {}", greeting, YOUR_LOGGER); // one param and print using your logger
/** you can use other logger methods like below as well. */
// CommonUtil.printWarn();
// CommonUtil.printError();
// CommonUtil.printDebug();
int count = 35; // this is demo data and that value might get from request or anywhere
int length = CommonUtil.getNumberLength(count); // get NumberLength and you can use long as well
CommonUtil.printInfo("length of input is {}", String.valueOf(length)); // use printInfo method
// sample output at console -> 13:22:32.667 [main] INFO helper.CommonUtil -- length of input is 2
if(length > 5){ // example condition
// do your process
}else {
// do your process
}
2. ValidationUtil
- Here are the sample usage for
ValidationUtil class
that you can apply in your application.
String name = ""; // this is demo data and that value might get from request or anywhere
if(ValidationUtil.isEmptyString(name)){ // isEmptyString method with one param
// here, I used print warn method with two params from CommonUtil class.
CommonUtil.printWarn("input is null or empty, input: {}", name);
// do your process like returning error or etc... when input is null or empty
}else {
// do your process when the input has data
}
String name1 = null; // this is demo data and that value might get from request or anywhere
if(!ValidationUtil.isEmptyString(name1, "name1")){ // isEmptyString method with two params for printing logs
// do your process when the input has data
}
// auto printing at console if you use two params methods
// sample output at console -> 12:51:55.001 [main] WARN helper.ValidationUtil -- name1 is null or empty, input: null
List<String> itemList = new ArrayList<>(); // this is demo data and that value might get from request or anywhere
if(ValidationUtil.isEmptyCollection(itemList)){ // isEmptyCollection method with one param
// here, I used print warn method with one param from CommonUtil class.
CommonUtil.printWarn("input list is null or empty, input: "+ itemList);
// do your process like returning error or etc... when input is null or empty
}else {
// do your process when the input has data
}
List<String> itemList1 = new ArrayList<>(); // this is demo data and that value might get from request or anywhere
if(!ValidationUtil.isEmptyCollection(itemList1, "itemList data")){ // isEmptyCollection method with two params for printing logs
// do your process when the input has data
}
// auto printing at console if you use two params methods
// sample output at console -> 13:00:53.468 [main] WARN helper.ValidationUtil -- itemList data is null or empty, input: []
/** you can use Set instead of List */
String email = "aa@"; // this is demo data and that value might get from request or anywhere
if(ValidationUtil.isValidEmail(email)){
// do your process when the email is valid format
}else {
// do your process like returning error or etc... when the email is not valid format
CommonUtil.printWarn("input email is not valid, input: {}", email);
}
String email1 = "a@c"; // this is demo data and that value might get from request or anywhere
if(ValidationUtil.isValidEmail(email1, "email1")){
// do your process when the email is valid format
}
// sample output at console -> 13:03:38.223 [main] WARN helper.ValidationUtil -- email1 is invalid format, input: a@c
int count = -1; // this is demo data and that value might get from request or anywhere
if(ValidationUtil.isPositiveNumber(count)){
// do your process when the input is positive number
}else {
// do your process like returning error or etc... when the input is not positive number
CommonUtil.printWarn("input is not positive, input: "+ count);
}
int count1 = -2; // this is demo data and that value might get from request or anywhere
if(ValidationUtil.isPositiveNumber(count1, "count1")){
// do your process when the input is positive number
}
// sample output at console -> 13:12:59.520 [main] WARN helper.ValidationUtil -- count1 is null or not positive number, input: -2
/** you can use long instead of int. */
3. PasswordUtil
- Here are the sample usage for
PasswordUtil class
that you can apply in your application.
String inputPassword = "P@ssw0rd"; // sample data and it might get from register form
String encodedPassword = encode(inputPassword); // call encode method from PasswordUtil to hash the password
CommonUtil.printInfo("encodedPassword: {}", encodedPassword); // print console by using printInfo method
// sample output at console -> 15:21:22.169 [main] INFO helper.CommonUtil -- encodedPassword: J78+7Cbv/IZSyUygAD/BDw$xgiAdngMzyWUzJSmrnW+YM6BGE578TaDGnTeB3+8Vvs
// do your process like storing the password into database or etc...
String loginPassword = "P@ssw0rd"; // sample data and it might get from login form
String encodedDBPassword = "J78+7Cbv/IZSyUygAD/BDw$xgiAdngMzyWUzJSmrnW+YM6BGE578TaDGnTeB3+8Vvs"; // this value might get from database
boolean match = checkPassword(loginPassword, encodedDBPassword); // call checkPassword method from PasswordUtil to check the login password is match or not
if(match){ // it will true if two passwords are same
CommonUtil.printInfo("successful login");
// do your process eg. approve login
}else {
CommonUtil.printWarn("password doesn't match");
// do your process eg. reject login
}
4. DatetimeUtil
- Here are the sample usage for
DateTimeUtil class
that you can apply in your application.
Instant instant = Instant.now(); // current datetime
// this getDateTime method will give you datetime by using java 8 Instant object and zoneId (eg. UTC, etc) and format pattern (eg. "HH:mm:ss dd/MM/yyyy", etc) as param.
// SAMPLE_FORMATTER is "yyyy-MM-dd HH:mm:ss.SSS" and get that from ConstantUtil class. You can use any string date format pattern here.
String utcDateTime = DateTimeUtil.getDateTime(instant, "UTC", ConstantUtil.SAMPLE_FORMATTER);
CommonUtil.printInfo(utcDateTime); // printInfo is a method to print at console which is in CommonUtil.class
// sample output -> 21:46:20.780 [main] INFO helper.CommonUtil - 2023-04-22 15:16:20.586
/**
* you can add any zone id and dateformat pattern instead of UTC and SAMPLE_FORMATTER as you want
* ZoneId ref - https://docs.oracle.com/middleware/12211/wcs/tag-ref/MISC/TimeZones.html
* Pattern ref - https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
*/
// example of adding custom zoneId and date pattern format
String mmDateTime = DateTimeUtil.getDateTime(instant, "Asia/Yangon", "HH:mm:ss dd/MM/yyyy");
CommonUtil.printInfo(mmDateTime);
// sample output -> 21:46:20.786 [main] INFO helper.CommonUtil - 21:46:20 22/04/2023
// this currentDateTime method will give you datetime by using zoneId (eg. UTC, etc) as param.
String currentDateTime = DateTimeUtil.getCurrentDateTime("UTC");
CommonUtil.printInfo(currentDateTime);
// sample output -> 21:46:20.787 [main] INFO helper.CommonUtil - 2023-04-22 15:16:20.787
// this currentDateTime method will give you datetime by using zoneId (eg. UTC, etc) and format pattern (eg. "HH:mm:ss dd/MM/yyyy", etc) as param.
String currentDateTimeParam = DateTimeUtil.getCurrentDateTime("UTC", "HH:mm:ss dd/MM/yyyy");
CommonUtil.printInfo(currentDateTimeParam);
// sample output -> 21:46:20.787 [main] INFO helper.CommonUtil - 15:16:20 22/04/2023
// this getCurrentUTCDateTime method will give you UTC datetime by using format pattern (eg. "HH:mm:ss dd/MM/yyyy", etc) as param.
String currentUTCDateTime = DateTimeUtil.getCurrentUTCDateTime("HH:mm:ss dd/MM/yyyy");
CommonUtil.printInfo(currentUTCDateTime);
// sample output -> 21:46:20.787 [main] INFO helper.CommonUtil - 15:16:20 22/04/2023
// this getUTCDateTime method will give you UTC datetime by using java 8 Instant object and format pattern (eg. "HH:mm:ss dd/MM/yyyy", etc) as param.
String utcDateTimeParam = DateTimeUtil.getUTCDateTime(instant, "HH:mm:ss dd/MM/yyyy");
CommonUtil.printInfo(utcDateTimeParam);
// sample output -> 21:46:20.787 [main] INFO helper.CommonUtil - 15:16:20 22/04/2023
// this getCurrentLocalDateTime method will give your local country datetime
LocalDateTime currentLocalDateTime = DateTimeUtil.getCurrentLocalDateTime();
CommonUtil.printInfo(currentLocalDateTime.toString());
// sample output -> 21:46:20.788 [main] INFO helper.CommonUtil - 2023-04-22T21:46:20.788103
// this getCurrentLocalTime method will give your local country time
LocalTime currentLocalTime = DateTimeUtil.getCurrentLocalTime();
CommonUtil.printInfo(currentLocalTime.toString());
// sample output -> 21:46:20.789 [main] INFO helper.CommonUtil - 21:46:20.789065
LocalDateTime localDateTime1 = LocalDateTime.of(2021,6,15,14,50,12);
LocalDateTime localDateTime2 = LocalDateTime.of(2021,7,17,15,54,15);
// this differenceDateByMilliSeconds method will give you the milliseconds which is difference between two LocalDateTime objects
long milliDiff = DateTimeUtil.differenceDateByMilliSeconds(localDateTime1, localDateTime2);
CommonUtil.printInfo("difference in milliseconds: "+milliDiff);
// sample output -> 21:46:20.789 [main] INFO helper.CommonUtil - difference in milliseconds: 2768643000
// this differenceDateBySeconds method will give you the seconds which is difference between two LocalDateTime objects
long secDiff = DateTimeUtil.differenceDateBySeconds(localDateTime1, localDateTime2);
CommonUtil.printInfo("difference in seconds: "+secDiff);
// sample output -> 21:46:20.789 [main] INFO helper.CommonUtil - difference in seconds: 2768643
// this differenceDateByMinutes method will give you the minutes which is difference between two LocalDateTime objects
long minDiff = DateTimeUtil.differenceDateByMinutes(localDateTime1, localDateTime2);
CommonUtil.printInfo("difference in minutes: {}", String.valueOf(minDiff));
// sample output -> 21:46:20.789 [main] INFO helper.CommonUtil - difference in minutes: 46144
// this differenceDateByHours method will give you the hours which is difference between two LocalDateTime objects
long hourDiff = DateTimeUtil.differenceDateByHours(localDateTime1, localDateTime2);
CommonUtil.printInfo("difference in hours: {}", String.valueOf(hourDiff));
// sample output -> 21:46:20.792 [main] INFO helper.CommonUtil - difference in hours: 769
// this differenceDateByDays method will give you the days which is difference between two LocalDateTime objects
long dayDiff = DateTimeUtil.differenceDateByDays(localDateTime1, localDateTime2);
CommonUtil.printInfo("difference in days: {}", String.valueOf(dayDiff));
// sample output -> 21:46:20.792 [main] INFO helper.CommonUtil - difference in days: 32
// this differenceDateByMonths method will give you the months which is difference between two LocalDateTime objects
long monthsDiff = DateTimeUtil.differenceDateByMonths(localDateTime1, localDateTime2);
CommonUtil.printInfo("difference in months: {}", String.valueOf(monthsDiff));
// sample output -> 21:46:20.792 [main] INFO helper.CommonUtil - difference in months: 1
// this differenceDateByYears method will give you the years which is difference between two LocalDateTime objects
long yearDiff = DateTimeUtil.differenceDateByYears(localDateTime1, localDateTime2);
CommonUtil.printInfo("difference in years: {}", String.valueOf(yearDiff));
// sample output -> 21:46:20.793 [main] INFO helper.CommonUtil - difference in years: 0
5. ResponseUtil
- Here are the sample usage for
ResponseUtil class
that you can apply in your application.
Employee employee = new Employee("Mr.Test", "123456"); // sample pojo class
ServiceResponse serviceResponse = getResponseObj("SUCCESS", "success", employee, "UTC");
LOGGER.info("Response data: {}", serviceResponse);
// sample output -> 15:32:23.516 [main] INFO Test -- Response data: Response{status=Status{status='SUCCESS', message='success'}, data=Employee{name='Mr.Test', phone='123456'}, timestamp='2023-04-21 09:02:23.512'}
6. ConstantUtil
- Here are the sample usage for
ConstantUtil class
that you can apply in your application.
String errMessage = ConstantUtil.VALUE_IS_EXISTED_MESSAGE; // one of the sample message
CommonUtil.printWarn(errMessage);
// sample output -> 21:55:12.402 [main] WARN helper.CommonUtil - Value is already existed.
/** you can use other constant values, please check out ConstantUtil class*/
- Below are constant values
Have Fun and Enjoy in Learning Code
Below is the Project Link for Spring-boot application with Jenkins.
Below is my GitHub profile and you can checkout all of my projects under repository tag, If you satisfied with my projects or you got some help from my projects, please help me also by giving star on GitHub and give recommendation in LinkedIn as I dropped my LinkedIn profile in below Contact Me section.
Ye Win Github — https://github.com/yewin-mm
✉️ Contact Me
Name — Ye Win
LinkedIn profile — Ye Win
Email Address — yewin.mmr@gmail.com
WhatsApp — +959252656065
Website — https://yewin.me
Project Link: helper-util
🥰 Becoming a Sponsor
If you like any of my projects or if you want to support my work, please kindly consider becoming a sponsor. It gives me great motivation and I can relentlessly maintain my projects and contribute to the open-source community.