Friday, May 19, 2017

Correlation ID generator

When there is a need to follow the business logic route to collect all activities, a correlation id could be used as a key to bind all related log entries.


import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;

public class CorrelationHolder {
 private final static Random RANDOM = new Random();
 private final static int RANDOM_UPPER_LIMIT = 10000;
 private final static String DEFAULT = "DEFAULT";

 private final static ThreadLocal<String> CORRELATION_ID = new ThreadLocal<String>();

 private CorrelationHolder() {
  // The class is only supposed to be accessed in static
 }

 public static String getCorrelationId() {
  final String identifier = (String) CorrelationHolder.CORRELATION_ID.get();
  if (null == identifier) {
   try {
    CorrelationHolder.setCorrelationId(CorrelationHolder.createCorrelationId());
   } catch (Exception e) {
    CorrelationHolder.setCorrelationId(DEFAULT);
   }
  }
  return CorrelationHolder.CORRELATION_ID.get();
 }

 private static void setCorrelationId(final String identifier) {
  CorrelationHolder.CORRELATION_ID.set(identifier);
 }

 private static String createCorrelationId() throws Exception {
  String identifier = "";
  try {
   identifier = convert(InetAddress.getLocalHost().getHostName(), 12, false)
     + convert(String.valueOf(System.nanoTime()), 11, true)
     + convert(String.valueOf(RANDOM.nextInt(RANDOM_UPPER_LIMIT)), 6, true);
  } catch (UnknownHostException uhe) {
   throw new Exception("Error Creating CorrelationId" + uhe);
  }
  return identifier;
 }

 private static String convert(final String original, final int outputLength, final boolean isLeft) {
  if (original != null) {
   int len = original.length();
   if (len > outputLength) {
    if (isLeft) {
     return original.substring(0, outputLength);
    } else {
     return original.substring(len - outputLength);
    }

   } else if (len < outputLength) {
    final StringBuilder sBuilder = new StringBuilder();
    if (isLeft) {
     for (int i = 0; i < (outputLength - len); i++) {
      sBuilder.append("0");
     }
     sBuilder.append(original);
     return sBuilder.toString();
    } else {
     sBuilder.append(original);
     for (int i = 0; i < (outputLength - len); i++) {
      sBuilder.append("0");
     }
     return sBuilder.toString();
    }
   } else {
    return original;
   }
  }
  final StringBuilder sbuffer = new StringBuilder();
  for (int i = 0; i < outputLength; i++) {
   sbuffer.append("0");
  }
  return sbuffer.toString();
 }

 public static void main(String[] args) {
  System.out.println(CorrelationHolder.getCorrelationId());
 }
}



No comments:

Post a Comment