Friday, May 15, 2015

Ignore Self-signed Certificate in Node.js

Issues: 

Error : self-signed certificate using npm or jasmine-node

Solution:

ADD process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0" before the request is sent.

Generate HamcMD5 Hashcode

public class TokenUtil {


public static String HMAC_MD5_encode(String key, String message) {

if (key != null && message != null){
   SecretKeySpec keySpec = new SecretKeySpec(
           key.getBytes(),
           "HmacMD5");
   Mac mac;
   byte[] rawHmac = null;
try {
mac = Mac.getInstance("HmacMD5");
mac.init(keySpec);
   rawHmac = mac.doFinal(message.getBytes());
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
            if (rawHmac.length > 0) {
       return Hex.encodeHexString(rawHmac);
            } else {
            return null;
            }
   } else {
return null;
}
}

}

Encrypt and Decrypt String with Key

public class EncryptorUtil {

private static String paramKey = "1234567890123456";
public static String encrypt(String key, String value) {
   try {
       IvParameterSpec iv = new IvParameterSpec(paramKey.getBytes("UTF-8"));

       SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"),
                   "AES");
       Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
       cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
       byte[] encrypted = cipher.doFinal(value.getBytes());
           return Base64.encodeBase64String(encrypted);
       } catch (Exception ex) {
           ex.printStackTrace();
       }
       return null;
   }

public static String decrypt(String key, String encrypted) {
   try {
       IvParameterSpec iv = new IvParameterSpec(paramKey.getBytes("UTF-8"));

       SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"),
                   "AES");
       Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
       cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
       byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));

       return new String(original);
   } catch (Exception ex) {
       ex.printStackTrace();
   }
       return null;
}

public static void main(String[] args) {

   String key = "9876543210123456"; // 256 bit key
       
   System.out.println(encrypt(key, "djkhflasdjdf"));
   System.out.println(decrypt(key, "iUoMmTT9n/NEA5mXhgDnn0/SM8fvpMTKyJcFQU=="));
}
}

Implement JSON Response Entity

public class ResponseJson {

    /**
     * A record is created successfully
     * @param msg
     * @return
     */
@ResponseBody
    public ResponseEntity<?> handleSuccess(String msg) {
        return successResponse(msg, HttpStatus.CREATED);
    }

    protected ResponseEntity<SuccessMessage> successResponse(String msg,
    HttpStatus status) {
        if (null != msg) {
            return response(new SuccessMessage(msg), status);
        } else {
            return response(null, status);
        }
    }

   
    /**
     *
     * @param msg
     * @return
     */
    @ResponseBody
    public ResponseEntity<?> handleNegative(String msg) {
        return negativeResponse(msg, HttpStatus.EXPECTATION_FAILED);
    }

    protected ResponseEntity<NegativeMessage> negativeResponse(String msg,
    HttpStatus status) {
        if (null != msg) {
            return response(new NegativeMessage(msg), status);
        } else {
            return response(null, status);
        }
    }

    /**
     * Authentication failure
     * @param msg
     * @return
     */
    @ResponseBody
    public ResponseEntity<?> handleUnAuth(String msg) {
        return unAuthResponse(msg, HttpStatus.UNAUTHORIZED);
    }
   
    protected ResponseEntity<NegativeMessage> unAuthResponse(String msg,
    HttpStatus status) {
        if (null != msg) {
            return response(new NegativeMessage(msg), status);
        } else {
            return response(null, status);
        }
    }

    /**
     * Json response
     * @param body
     * @param status
     * @return
     */
    protected <T> ResponseEntity<T> response(T body, HttpStatus status) {
        return new ResponseEntity<T>(body, new HttpHeaders(), status);
    }
}

Add Filter for Cross-Domain Response

@Component
public class ExampleFilter implements Filter {

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, origin, content-type, accept");
chain.doFilter(req, res);
}

public void init(FilterConfig filterConfig) {}

public void destroy() {}

}


Add it from WebApplicationInitializer

servletContext.addFilter("ExampleFilter ", ExampleFilter .class)
        .addMappingForUrlPatterns(null, false, "/*");

Global Exception Handling for Spring-Boot Application Using @ControllerAdvice

@ControllerAdvice
public class GlobalExceptionHandling {

protected Logger logger;

public GlobalExceptionHandling() {
logger = LoggerFactory.getLogger(getClass());
}

@ResponseBody
    public ResponseEntity<?> handleUnauthenticationException(Exception e) {
        return errorResponse(e, HttpStatus.BAD_REQUEST);
    }

@ExceptionHandler({DataIntegrityViolationException.class, SQLIntegrityConstraintViolationException.class})
@ResponseBody
    public ResponseEntity<?> handleConflictException(Exception e) {
        return errorResponse(e, HttpStatus.CONFLICT);
    }

@ExceptionHandler({ SQLException.class, DataAccessException.class, RuntimeException.class })
@ResponseBody
    public ResponseEntity<?> handleSQLException(Exception e) {
        return errorResponse(e, HttpStatus.INTERNAL_SERVER_ERROR);
    }

@ExceptionHandler({ IOException.class, ParseException.class, ProcessingException.class, JsonParseException.class, JsonMappingException.class })
@ResponseBody
    public ResponseEntity<?> handleParseException(Exception e) {
        return errorResponse(e, HttpStatus.BAD_REQUEST);
    }

@ExceptionHandler({ InvalidKeyException.class, NoSuchAlgorithmException.class })
@ResponseBody
    public ResponseEntity<?> handleHashException(Exception e) {
        return errorResponse(new Exception("Encrypt/Decrypt key is requested"), HttpStatus.LOCKED);
    }

    @ExceptionHandler({ Exception.class })
    @ResponseBody
    public ResponseEntity<?> handleAnyException(Exception e) {
        return errorResponse(e, HttpStatus.INTERNAL_SERVER_ERROR);
    }
   
    protected ResponseEntity<ExceptionMessage> errorResponse(Throwable throwable,
            HttpStatus status) {
        if (null != throwable) {
            return response(new ExceptionMessage(throwable), status);
        } else {
            return response(null, status);
        }
    }

    protected <T> ResponseEntity<T> response(T body, HttpStatus status) {
        return new ResponseEntity<T>(body, new HttpHeaders(), status);
    }
}



Another class

import com.fasterxml.jackson.annotation.JsonProperty;

public class ExceptionMessage {

private final Throwable throwable;

public ExceptionMessage(Throwable throwable) {
this.throwable = throwable;
}

@JsonProperty("error")
public String getError() {
return throwable.getMessage();
}

}

Deployment of Spring-Boot Application on WebSphere

Error Message:

No Spring WebApplicationInitializer types detected on classpath

Solutions:

1. Add  JVM property named classinfocachesize and its value is 16000

2. IBM Web Sphere 8.0 and above started supporting servlet 3.0 which should give you the ability to configure your application without specifying a web.xml. If you are using spring-boot, ibm websphere, and servlet 3.0 and are trying to deploy without a web.xml there might be a possible issue. One workaround is creating an empty web.xml file and then set the metadata-complete="false".

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0" metadata-complete="false">
    
  <display-name>Archetype Created Web Application</display-name>
  


</web-app>