Tuesday, August 30, 2016

Getting KeyCloakContext From ServletRequest

When REST APIs are protected with keycloak authentication, we might need to get user realm in the backend to get some user information.

In the ServletRequestFilter implementation,

public class ApplicationFilter implements Filter {

private Base64 decoder = new Base64(true);

ServletRequestHolder requestHolder;

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
try {

* Get the logged in user info from the request.
* @param request
private void checkAuthentication(ServletRequest request) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
KeycloakSecurityContext kContext = (KeycloakSecurityContext) httpServletRequest
String bearerToken;

if (kContext != null) {

bearerToken = kContext.getTokenString();
String[] jwtToken = bearerToken.split("\\.");
byte[] decodedClaims = decoder.decode(jwtToken[1]);
JSONObject jsonObj = new JSONObject(new String(decodedClaims));

Thursday, August 11, 2016

Supporting hibernate precision/scale for BigDecimal with MySql

When we use BigDecimal in our POJOs, we define the precision /scale  values for it to make sure how many digits database column has to allocate to represent the values. MySql does not support the scale more than 2 digits, we can have only  19/2 for BigDecimal Data types.

@Column(name = "metre" ,precision = 19, scale = 10)
private BigDecimal metre = BigDecimal.ZERO;

To overcome this issue, we can convert BigDecimal datatype to Double when we store the values. JPA provides @Convert annotation which can be used to convert datatypes .


@Convert(converter = BigDecimalConverter.class)
private  BigDecimal metre = BigDecimal.ZERO;

We need to write a custom converter for this.


import java.math.BigDecimal;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

public class BigDecimalConverter implements AttributeConverter {

public Double convertToDatabaseColumn(BigDecimal bigDecimalValue) {
if (bigDecimalValue == null) {
return null;

return bigDecimalValue.doubleValue();

public BigDecimal convertToEntityAttribute(Double doubleValue) {
if (doubleValue == null) {
return null;

return BigDecimal.valueOf(doubleValue);