Skip to content

Instantly share code, notes, and snippets.

@ankushs92
ankushs92 / DateUtils.java
Last active December 23, 2015 04:55
Friends don't let friends use java.util.Date !
public class DateUtils{
/*
* Converts java.util.Date object to a java.time.LocalDate
* Things are so much more convenient now!
*/
public static LocalDate asLocalDate(final Date date){
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
}
/*
@ankushs92
ankushs92 / SomeInterceptor.java
Last active April 12, 2024 12:23
How to get Path Variables inside a Spring interceptor.[This post assumes that you have an Interceptor registered and set up using XML or Java config]
public class SomeInterceptor extends HandlerInterceptorAdapter{
@Override
public boolean preHandle(final HttpServletRequest request,final HttpServletResponse response,final Object handler)
throws Exception
{
/*Assume the URI is user/{userId}/post/{postId} and our interceptor is registered for this URI.
* This map would then be a map of two elements,with keys 'userId' and 'postId'
*/
final Map<String, String> pathVariables = (Map<String, String>) request
.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
@ankushs92
ankushs92 / SomeClass.java
Created February 9, 2016 17:27
Spring security cache User object when working with JWT.
// Jwt requires an authentication on every request.Assuming that you are storing your User objects in a relational database like MySQL,
// and that your API gets moderate traffic,it is not a good idea to fetch the User object directly from the database every time.
//Instead,once it is retreived ,we cache it locally using Spring Caching abstraction.The cache backend is Google guava.
public class UserServiceImpl implements UserService { //Which further extends UserDetailsService .
@Override
@Cacheable(cacheNames=CacheConstants.USER_CACHE,key="#username") // We cache this guy by its username.
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
final User user = userRepository.findOneByEmail(username);
@ankushs92
ankushs92 / NumberUtils.java
Created February 28, 2016 05:27
Java : Check if a Number object has value null or 0.
public class NumberUtils{
public boolean isNullOrZero(final Number number){
return number == null ||
(
number instanceof Integer ? number.intValue() == 0 :
number instanceof Long ? number.longValue() == 0 :
number instanceof Double ? number.doubleValue() == 0 :
number instanceof Short ? number.shortValue() == 0 :
number.floatValue() == 0
@ankushs92
ankushs92 / LocalDateTimeConverter.java
Created April 16, 2016 17:10
Converting LocalDateTime object to some String pattern
// Format : dd-MM-yyyy HH:mm
// Use case : LocalDateTime object to Json serialization.
final LocalDateTime dateTime = LocalDateTime.now() ; //or something else.
final int day = dateTime.getDayOfMonth();
final int month = dateTime.getMonthValue();
final int year = dateTime.getYear();
final int hour = dateTime.getHour();
final int minute = dateTime.getMinute();
jsonGenerator.writeString(new StringBuilder()
.append(day).append("-")
@ankushs92
ankushs92 / LocalDateTimeJPAConverter.java
Created April 16, 2016 17:12
Converting java.sql.timestamp to LocalDateTime and vice versa
import java.sql.Timestamp;
import java.time.LocalDateTime;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime ldt) {
@ankushs92
ankushs92 / EnumUtils.java
Created April 16, 2016 17:15
Convert a String to an Enumeration (if possible).
public class EnumUtils {
public static <T extends Enum<T>> T getEnumFromString(final Class<T> enumClass,final String value) {
if(enumClass == null){
throw new IllegalArgumentException("enumClass cannot be null");
}
for (final Enum<?> enumValue : enumClass.getEnumConstants()) {
if (enumValue.toString().equalsIgnoreCase(value)) {
@ankushs92
ankushs92 / JsonUtils.java
Last active December 28, 2017 08:56
Some Json utilities that I use for every project.Uses Jackson library.
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtils {
private static final ObjectMapper objMapper = new ObjectMapper();
public static <T> T toObject(final String json , final Class<T> clazz) throws Exception{
@ankushs92
ankushs92 / PreCondition.java
Created April 16, 2016 17:22
Some Pre conditions/assertions that one would encounter in everyday programming
public class PreCondition {
public static <T> void checkNull(final T t, final String errorMsg){
if(t==null){
throw new IllegalArgumentException(errorMsg);
}
}
public static void checkEmptyString(final String str, final String errorMsg){
if(!Strings.hasText(str)){
throw new IllegalArgumentException(errorMsg);
@ankushs92
ankushs92 / gist:420bbbef948285b912a8f1ff706f3705
Last active September 26, 2017 14:02
.gitignore for Most groovy,gradle,java and spring boot projects
# Directories #
/build/
bin/
repos/
/repos/
doc/
/doc/
.gradle/
/bin/
target/