Tuesday, July 7, 2015

How to debug unix (shell/perl) scripts

As a professional we also need to be the solution provider which essentially means you need to be ready to get your hands dirty with anything which comes your way in order to serve the business.

Many a times you will come across the situations where you need to fix critical problem or software bug in short span in order to keep your website or product up to date. So there comes the debugging in picture and you all will be adapt to debugging java applications using eclipse (local and remote) and so will not discuss that here but sometimes critical business aspects or functionalists are implemented in unix scripts like shell script or perl script which can be tedious task to deal with if you come across the bugs in these sections.

So today, we will see how to debug both of these scripts.

Debug Shell Scripts:

Suppose you have a critical function which is doing some X task but you are not seeing the step x or statement x within the same function being executed, as expected.

So how to deal with this situation. Sometimes you might work it around by putting lot of print statements to print some useful information. well, nothing wrong with it but what if those print statements are not getting triggered either or your favorite function is doing lot of things and have complex branching with if/else or switch statements.

So here what you want to do is to check how each statements are triggered inside the fuction and how if/else or other branching logics are evaluated. Consider below example:

function audit_upd
{
  stat=$1
  step=$2
  ins=${ins_rows:-0}
  upd=${upd_rows:-0}
  del=${del_rows:-0}

  TbNm=${TbNm:-MSTAR}
  print "\n\n  `$TIME`:  $Function step $step $stat start ... "

  print "  `$TIME`:  run $sql_dir/audit_upd.sql $DateFlag $AsofDate"

  run_sql $ORACLE_SID_A $DB_ID $sql_dir/audit_upd.sql \
  $DateFlag $AsofDate MSTAR $TbNm $stat

  print "  `$TIME`: $stat DONE"
}

All it does is, calls .sql file with required parameters.

Now, say you want to see the entire execution sequence while this function gets triggered. So you can put set -x as the first line in the function as above.

It will show you entire sequence as given below.

Output:

+ stat=START
+ step=20
+ ins=0
+ upd=0
+ del=0
+ TbNm=MSTAR
+ date +%H:%M
+ print '\n\n  13:39:  get_audit_info step 20 START start ... '

+ print '  13:39:  run /db/sql/audit_upd.sql M 20140630'
  13:39:  run /db/sql/audit_upd.sql M 20140630
+ run_sql TPAQ.WORLD APPUSR /db/sql/audit_upd.sql M 20140630 MSTAR MSTAR START
+ date +%H:%M
+ print '  13:39: START DONE'
  13:39: START DONE

So as you can see not only the execution sequence but it also shows you the assigned values of each variable inside the function.

Debug Perl Scripts:

Now, say similarly you want to debug the perl script then you can do so by using -d option.

It will execute the script but in debug mode and here you have advantage above shell script that -d provides you interactive mode similar to debugging java application in Eclipse.

so let's say you execute below script with -d,

perl -d $subscripts/xml_decode.pl

it will prompt you with  DB<1> on first executable line which is interactive mode and it will await the input from the user.

1) Step over:

 You can provide n or s after the prompt like below.
 DB<1>n (Enter)

n or s are both are similar commands for step by step execution of each executable statements like F6 & F5 in Eclipse.

n (same as F6) will execute the statement in single step which means any subroutine or function will be executed and response will be assigned back, same as F6 in Eclipse debug mode.

s, on the contrary, will step into the subroutine or function if called on this break point; similar to F5.

2) Break Point:

It also allows you to set the break point at particular statement. For ex, say you have a function at line #60 and you want to set the break point.

 DB<1>b 60 (Enter)

So any statement on line 60 will be triggered once the execution reaches there.

3) Inspect Variables:

p command allows you to inspect or print the value of any variable. For ex, say execution is at line #70 which is a variable called $count and you want to inspect the value at this particular point of time.


 DB<1> p $count (Enter)

Output: 20

4) Jump to break point:

Suppose you want to skip few lines and interested to see what happens at certain point, let's say at line #75. below command will exactly do that for you,

 DB<1> c 75 (Enter)

5) View the break points:

Now, say you want to see all the break points in the sequence from the current execution point. so l command allows you to see next window of lines.


 DB<1> l (Enterr)

Output:

DB<8> l
46
47        SWITCH: {
48          # evaluate the expression
49:         if (/([^<]*)<([^>]*)\/>$/) {
50:           print "Inside first if condition \n";
51:           last SWITCH;
52          };
53


6) Quit the interactive mode:

Finally if you want to quit the debug mode during the process then you can use q to quit the debug mode once you are done with it.

So these are some the useful tips to debug the scripts which can be tedious task sometime without adequate knowledge on particular scripting language.

Hope, this will help you to be more productive and efficient with the unix scripts......












Saturday, January 3, 2015

Mule Part I: Introduction

Mule is widely used open source framework for Enterprise Integration. In this post, I will  try to cover basics of Mule and why you should be using Mule since there is very less documentation available for the mule.


What is Enterprise Integration?

In an organization, there will be multiple applications or products or processes to complete the end to end business flow or transaction. Needless to say that, these applications might be owned by different business groups or teams and so the underlying architecture or communication protocol will defer as well. 

So to serve the business, there is always the need to allow these applications or processes to communicate to each other regardless of the underlying architecture or protocol or communication style. For ex, to settle the trade, Frond office will receive the trade instruction, Middle office will process the trade and back office will settle the trade with market feed. Now let's assume, front office application which will receive the trade is designed using .Net framework and Middle office application which processes the trade is designed in Java. In order to communicate either of this application need to change (Java or .Net) which would be a disaster and there comes the power of Enterprise Integration Software or tools !! 

In our case, front office can send trade message or instruction to middle office process through web service and middle office can process the same through Mule or any other Integration tool like apache camel or spring integration etc without changing underlying architecture and same way send it to downstream system or back office. So two systems can work in isolation without interfering to what other system offers....

Now let's understand how we can achieve this through Mule ESB.


What Is Mule?

Mule is a transport-agnostic, Java-based messaging framework that allows disparate applications to connect without having to call each other directly. Mule supports multiple threading/messaging models, input and output to various transports (email, files, databases, etc.), and web services through protocols such as SOAP (see Figure 1).



With Mule, you can...

  • integrate applications or systems on premise or in the cloud
  • use out-of-the-box connectors to create SaaS integration applications
  • build and expose APIs
  • consume APIs
  • create Web services which orchestrate calls to other services
  • create interfaces to expose applications for mobile consumption
  • integrate B2B with solutions that are secure, efficient, and quick to build and deploy
  • shift applications onto the cloud
  • connect B2B e-commerce activities

Leveraging the three layers of its architecture: application, integration, and transport, Mule implements an enterprise service bus (ESB) and provides a platform for a service oriented architecture (SOA). The layered approach promotes reusability (see Figure 2).


So stay tuned for more of Mule..............

Thursday, December 25, 2014

How to create your own Unmodifiable List in Java ?

java.util.Collections class offers numerous utility methods, mostly static ones, to operate collection objects effectively.

This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends. One of the most used utility from this class is unmodifiableCollections or lists.

 So today we will see how we can implement this feature using Java but before we go into more details; let's first understand what unmodifiableList offers to us.

Features:

Like UnmodifiableCollections it returns the wrapper object of the original list which is read-only view of original list. However, important thing to remember here is that it's not immutable list and so state of the object can be changed by modifying original list object.

For ex, any modification made to the original list will be visible to unmodifiable object reference as well.

So now let's see how we can achieve this features by our own custom implementations.

Implementation:

We will need two main classes: MyCollections class to provide the static method which will return our wrapper object and MyUnmodifiableList class which will be the wrapper here to be returned to the caller.

So as it's very much evidant from the API call that unmodifiableList method will be a static method

public class MyCollections {

    public final static  List unmodifiableList(final List list) {
        return (List) new MyUnmodifiableList(list);
    }
}


Since our static method returns the MyUnmodifiableList, we will need concrete implementation of this class. So what do we need from this class ??

1. It should be type of List in order to keep List reference.
2. It should maintain the reference to the original list since we will need to reflect the updates made to the original list.
3. It should not allow any modifications to this object.

So essentially it should behave like the way view does on database table .

To satisfy point #1 here, we will need to implement List interface so class definition will become like this...

public class MyUnmodifiableList implements List {

Now, to get point #2 right,  will need to have List reference in the class;

    List originalList;


Remember, this variable has to keep reference to the originalList and so you might start getting confused now because you kept hearing this whole your life that "java is pass by value and not by reference". Then how on the earth you can keep the reference here to the original List !!

Well, everything you heard is right that Java is pass by value only but in case of objects, it passes the object reference by the value and so any change in original list will still reflect in MyUnmodifiableList reference. Excellent, so we are almost there.....

So last but not least, for point #3, all you need is to keep this class Immutable as the definition says and so what are the methods which can change your object state ??

To name few: add(), addAll(), remove(), removeAll() and few more. Yes, will need to override all of List interface methods here and so you'll need to update it accordingly so that it doesnt support the object state to change.


    public boolean add(E e) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean remove(Object o) {
        throw new UnsupportedOperationException();
    }


So finally we are done now as we have satisfied all of the above conditions and requirements mentioned above for the unmodifiableList interface.

Why I chose this particular example is because it checks lot of core concepts of Java & OOPS. So if you carefully observe this example, it touched upon OOPS (List interface), Program against Interface, Composition over inheritance, Pass by value or reference , Immutable Objects, Exception Handling etc......

If you could implement or understand this example means, you know all of this concepts and  ready to touch upon some more complex examples.

So keep reading.........................................!!!!



Tuesday, December 23, 2014

Java Reflection for Enumerations


Enumerations are pretty handy when it comes to define your own schema for static fields and we all know the power of enumerations so I'm not going to discuss more about enumerations here as you would find many blogs and articles on it.

Today, we are going to discuss the use case where we will need to use enumerations to provide dynamic validations on input fields using reflection and also will see bit more complex example where will need to use reflection to invoke enumeration itself.

Problem Statement: 

Suppose you are receiving the input as CSV file and need to validate all the input fields based on below criteria:
- Field should be validated based on max length.
- Field should be validated based on access types: mandatory or optional.
- Field should be validated based on data type: alphanumeric, numeric (decimal), date etc.

Now, in order to satisfy above requirements, obvious way one would think of is to put if else blocks on each input fields and validate all of above criteria.

Well, nothing wrong with that but it's a old fashioned or rather cruel way of doing things. Java provides many robust features after 1.5 version onwards and we should leverage it.

So, closely observing above requirements you can see we need two static schemas at first: Data type & Access type which can be defined as given below.

public enum DataTypes {
    ALPHANUMERIC, NUMERIC, DATE, STRING;
}


public enum AccessTypes {
    OPTIONAL, CONDITIONAL, MANDATORY;
}

Now using above schema, we want to define the CSV schema for the field validations.

public enum CSVFieldEnumerations {
    ESCROW_ACCOUNT(0, "escrowAccount", "Escrow Account", DataTypes.ALPHANUMERIC, 12 , 0, AccessTypes.MANDATORY),
    CURRENCY(1, "currency", "Currency", DataTypes.ALPHANUMERIC, 3, 0, AccessTypes.MANDATORY),
    PRINCIPAL(2, "principal", "Principal", DataTypes.NUMERIC, 17, 2, AccessTypes.MANDATORY),
    START_DATE(3, "startDate", "Start Date", DataTypes.ALPHANUMERIC, 8, 0, AccessTypes.MANDATORY);


    private int columnNumber;
    private String columnName;
    private String columnDescription;
    private DataTypes columnType;
    private int maxLength;
    private int decimalPlaces;
    private AccessTypes accessType;

    private CSVFieldEnumerations(int columnNumber,
                                    String columnName,
                                    String columnDescription,
                                    DataTypes columnType,
                                    int maxLength,
                                    int decimalPlaces,
                                    AccessTypes accessType) {   
       
        this.columnNumber = columnNumber;
        this.columnName = columnName;
        this.columnDescription = columnDescription;
        this.columnType = columnType;
        this.maxLength = maxLength;
        this.decimalPlaces =  decimalPlaces;
        this.accessType =  accessType;
    }  
 }


Suppose we are using the CSVParser class to read the CSV and validate all input values.JDK provides special Set & Map interfaces to iterate through the enums: EnumSet & EnumMap. We will be using EnumSet here to iterate over the enumerations defined here.

        for (CSVFieldEnumerations schema: EnumSet.allOf(CSVFieldEnumerations.class)) {
Now, lets see how we can utilize the schema to provide the dynamic validations. We will create static methods to access these dynamic properties and provide validations.

    public final static String validateAlphaNumericField(CSVFieldEnumerations column, String value) {
        if(StringValidation.checkLength(value, column.getMaxLength())) {
             if(!StringValidation.isAlphanumeric(column.getColumnName())) {
                 return column.getColumnDescription() + " is not an alphanumeric value";
             } else {
                 return null;
             }
        } else {
            return "Mandatory field " + column.getColumnDescription() + " exceeds size " + column.getMaxLength();
        }
    }


As you can see here, we are accessing the schema values using the enumerations to do validations here.


So we have used the schema to do dynamic validations but we also want to create CSVRecord object from the raw input data and our enumeration will do that as well for us. Remember we have defined columnName in our schema which will be the field name of CSVRecord object.

Reflection:

Field field = CSVRecord.class.getDeclaredField(schema.getColumnName());
setterMethod = CSVRecord.class.getMethod("set" +   StringUtils.capitalize(schema.getColumnName()), (Class) field.getType());
setterMethod.invoke(result, currentColumn.trim());


So here we will iterate through the EnumSet for each enumeration constants defined in the schema and will validate based on the metadata defined along with setting up the CSVRecord Object.  

So two birds with single stone !!
This is the power of Enumeration when combined with Reflection.

Reflection to load Enumerations:

Now, let's make above example bit more complex and consider the scenario where you need one more layer to load enumerations itself using the reflection.

Say, you have 4 different CSVs to parse and prepare common CSVRecord to send out as XML. so one will say what's the big deal, I'll set the CSV type in the parser and then will use  that to load enumeration and then iterate it over using EnumSet like we did above.

Well, here is the catch, while you fetch the enumeration using EnumSet.allOf(), you need to cast it to perticular enumeration but here you don't have any type to cast unless you do it in if else blocks for each enumeration defined for the CSV type because Enumerations cannot subclassed and so you dont' have supertype here.

Well, alternately you can use generics to load enumerations using the reflection as given here.

        Class enumClass = Class.forName("com.csv." + this.csvTypes);
        Object[] enumConstants = enumClass.getEnumConstants();

        for (int i = 0; i < enumConstants.length; i++) {
            Class sub = enumConstants[0].getClass();              
            enumColumnName = sub.getDeclaredMethod("getColumnName");
            columnNameValue = String.valueOf(enumColumnName.invoke(enumConstants[i]));
          .

          .
          .
          .
         
 So, here we are using '?' since we don't know the type of the returned enumeration but still able to invoke the getters on the enum properties to achieve the desired results !!

Hope, this will help you understand enumerations and refection concepts.

so happy reading......





Saturday, November 22, 2014

Java Thread IV: BlockingQueue to Print Odd/Even Numbers

Today, we will see how to print odd even numbers using Blocking Queue.  

We want to print odd even numbers using two different threads and so it will obviously require some kind of thread synchronization to communicate while one thread is printing the number. So one thread will become producer (odd) and other one (even) will become consumer. Java provides BlockingQueue for thread synchronization in these kind of scenarios. 

BlockingQueue provides functions to support operations that awaits for the queue to become non-empty while retrieving elements or wait for the space to become available while inserting the elements.

In our example, we will use LinkedBlockingQueue which uses ReentrantLock (refer my earlier post) internally for thread synchronization. To implement the solution for our odd even thread, we will need two classes: TakeAndOfferNext class which is callable thread and OddAndEvenSignalling which will invoke the thread.

TakeAndOfferNext:

Now let's see the implementation of TakeAndOfferNext. We will need two blocking queues here: one for odd numbers and another one for even numbers.

    BlockingQueue takeFrom;
    BlockingQueue offerTo;

Blocking queue offers two synchronous operations called take() and offer(e). Take removes the element from the queue if it's non-empty and offer inserts to the queue if it's not full. Here, you dont' need to be aware of thread synchronization as blocking queue will take care of it through these two methods. So let's print odd even numbers using these blocking queues:

    public void print()    {
        while (true)  {
            try   {
                int i = takeFrom.take(); //removes the value in the "from" queue

                System.out.println(Thread.currentThread().getName() + " --> " + i);

                offerTo.offer(i + 1);    //increments the value by 1 and puts it in the "to" queue.

                if (i >= (maxNumber - 1)) {
                    System.exit(0);
                }
            } catch (InterruptedException e) {
                throw new IllegalStateException("Unexpected interrupt", e);
            }
        }
    }

As you can see here we are looping through the continuous loop until it reaches the max number. In the loop, we first take the first number (odd one) from the first queue and pass the next number (even one) to the another queue.

Okay, half work is done now how do we take even element from the another queue which we set at the end ? Well, we will need two threads to do this job which will switch the odde and even queues alternately in below class.

OddAndEvenSignalling:

        BlockingQueue odds = new LinkedBlockingQueue();
        BlockingQueue
evens = new LinkedBlockingQueue();
        ExecutorService executorService = Executors.newFixedThreadPool(2);

Now, our two threads are ready to print odd and even numbers. So, let's pass it on to the TakeAndOfferNext class in such a way that it will switch odd and even queues in the print() method.

        executorService.submit(new TakeAndOfferNext(odds, evens, MAX_NUMBER));
        executorService.submit(new TakeAndOfferNext(evens, odds, MAX_NUMBER));

And that's it, your job is done !!!

Working code samples can be found here.


You can try producer consumer example using blocking queue as an exercise.

Monday, November 3, 2014

Java Design Patterns II: Command Pattern to get rid of ugly if else blocks in Java

In my career, I came across many legacy applications and code and saw many bizarre code samples because it has been served by many different programmers over the period and everybody was probably lazy or under pressure to meet the deadline !!!

I personally hate ugly code and have very bad habit of re-factoring it on the spot whether it's bad naming conventions, incorrect formatting, duplicate code or hard coded string literals etc. because I  cannot just read through it without that. One of the thing I observed constantly in all those applications was code duplication and abuse of if-else blocks. 


Many programmers just love if else blocks simply because it's convenient to satisfy business logic quickly. There is nothing bad in it because it's very common to have multiple conditional logic in your business requirements but it starts getting ugly when you try adjusting tens (or sometimes hundreds, yes that's right) of conditions in one method or class using if-else blocks. 


In one of my recent assignments, we had to write pseudo SWIFT parser to process trade instructions and convert SWIFT message to XML. It was obvious that we had to write Parser to convert all the SWIFT tags (around 200 tags) into XML after doing some processing on each of the swift tag. Here is the sample code we had in it's original form....



public void uglyMethodWithNastyIfElseBlocks(String tagName){
             
   if(tagName.equals("NetAmount")){
       System.out.println("Doing something with NetAmount and having value :32B:");
   } else if(tagName.equals("GrossAmount")){
      System.out.println("Doing something with GrossAmount and having value :32M:");
   } else if(tagName.equals("SecurityId")){
       System.out.println("Doing something with SecurityId and having value :35B:");
   }
   .
   .
   .
   .
   } else {
       System.out.println("No Tags Found");
   }
}

Now imagine you have around 100 odd tags and doing some of processing on all of them which are accommodated inside same method. So to avoid this kind of situations Java provides you Command Pattern.

Now, lets re-factor this class using Command Pattern. To achieve clean code we will need one interface TagValueProvider to define the command for each tag which is currently inside if-else blocks, Enumeration: TagEnumeration to define Tag properties and Mapper class to map Tags with it's concrete implementation:

TagValueProvider: Each tag with different  behavior will implement below command.

      public void processTag(TagEnumeration tag);

ReturnTagValueProvider: Concrete implementation of each command.

@Override
public void processTag(TagEnumeration tag) {
System.out.println("Doing something with "+ tag.NETAMOUNT.getTagName() +" and having value " + tag.NETAMOUNT.getTagValue());

}

TagEnumeration: Each tag will have it's own properties and so will be mapped in this enumeration.

NETAMOUNT("NetAmount", ":32B:"), //key value pair of tags
GROSSAMOUNT("GrossAmount", ":32M:"),

SECURITYID("SecurityId", ":35B:");

TagMapper:  Schema to map the tags with implementing class. So you can have multiple tags mapping with common class or separate class having specific implementation.


  public static Map tagSchemaMapper = new HashMap();

static {
tagSchemaMapper.put(TagEnumeration.NETAMOUNT, new ReturnNetAmount());
tagSchemaMapper.put(TagEnumeration.GROSSAMOUNT, new ReturnGrossAmount());
tagSchemaMapper.put(TagEnumeration.SECURITYID, new ReturnSecurityId());
}

Now, let's see how our ugly method will look like after this re-factoring in below case.

public void correctMethodWithCommandPattern(TagEnumeration tags){
TagMapper.tagSchemaMapper.get(tags).processTag(tags);
}

So as you can see your multiple if else blocks will be replaced with single statement since command for each tag is now moved to concrete classes.

This is much cleaner approach because you don't have to accommodate entire business logic in one single method and more importantly it provides more readability to the code since each tag will have it's concrete implementation.

Advantages:
Separate implementation of each command with interface.
Enumeration to define each tag and it's properties.
HashMap to map the tag with it's behavior.

Saturday, November 1, 2014

Java Desing Patterns I: Chain Of Responsibility For Trade Enrichment.

Sometime back in one of the interviews with top Investment Bank, I was asked to write top level design diagram and highlight Interfaces, Classes and important mehthods.

Below is the detailed problem statement:

1. Trade domain objects may be enriched to add further information.
2. There are many different types of enrichment which may be carried out on a trade. 
     Party & Booking enrichment are two specific types of Enricher.
3. All enrichment is done normally at certain point in Trade processing (e.g. multiple Enrichers operating sequentially on Trades). This must be done via single Enricher.
4. It may be important to control the order of some Enrichers.

This is smart question because it makes you think and touches upon few of basic core java concepts like: Open Closed principle, Program against interface and also your design pattern knowledge on Strategy & Chain Of Responsibility but most importantly it checks your analytical and designing skills.

I liked the question because it's smart, simple and yet tricky. It's much better than asking singltons & hashmaps and all those useless questions which are repeatedly asked over and over again and people still think knowing these concepts can only make them smart coders !!

Till, first two points, I was sure they are asking me to explain Strategy pattern and will be straight forward but when I read 3rd point, I was sure they are asking something tricky which needed to be done with combination of some design patterns.

After putting my analytical skills in action for couple of minutes, I realized they are indirectly asking me to implement Chain Of Responsibility to check my designing skills. So here is what I came up with:

We will mainly need one interface (TradeEnrichment) to define enrichment and two concrete implementations: BookingEnricher & PartyEnricher.

public interface TradeEnrichment {

public void enrichment(TradeAccount tradeAccount);

public void setNextEnricher(TradeEnrichment nextEnricher);

}

Here, second method is important because it will provide us order of execution. Now, let's see one concrete implementation of this interface as asked in the question.


public class BookingEnricher implements TradeEnrichment {


TradeEnrichment enricher;

@Override
public void enrichment(TradeAccount tradeAccount) {

System.out.println("Enriching The Trade Booked");

if(enricher != null)
this.enricher.enrichment(tradeAccount); // call next enrichment
}

@Override
public void setNextEnricher(TradeEnrichment nextEnricher) {
this.enricher = nextEnricher;
}

}

Here, I have provided dummy implementation of Booking enrichment. Important thing to note here is the last statement which calls next Enricher in the sequence. So after completing the job Enricher simply passes the call to next Enricher in the sequence set using setNextEnricher() method.

Now, using Strategy Pattern here we can make sure that TradeEnrichment can have any number of concrete implementations in future as required and so our design follows Open-Closed principle (Open for enhancement but closed for modifications)

We will also need one class to invoke all these components and control sequencing order for the Trades: EnrichmentProvider.


public class EnrichmentProvider {

TradeEnrichment firstEnricher;

public void EnrichmentProvider(){

this.firstEnricher = new BookingEnricher();
TradeEnrichment secondEnricher = new PartyEnricher();

/** 
* set enrichment sequence here. you may have N number of enrichers in                                futures and you can control 
* the order of sequence here without impacting actual implementation in                             TradeEnrichment.
*/
firstEnricher.setNextEnricher(secondEnricher);

}

public static void main(String[] args) {

EnrichmentProvider tradeEnrichmentProvider = new EnrichmentProvider();

TradeAccount account = new TradeAccount();
account.setTradeType(TradeType.BOOK);

tradeEnrichmentProvider.firstEnricher.enrichment(account);
}

}

As you can see we are controlling the order of enrichers in the constructor by setting the next enricher in the chain.

Interviewers were quite impressed with clear understanding or design concepts and ability to craft clean interfaces because it helps  to discuss problems in terms of design patterns during design sessions and building new softwares. You don't have to explain your team how you will set order, how you can keep your implementations open for enhancements but closed for modifications etc. All you need to tell them is use Strategy Pattern & Chain Of Responsibility for Trade Enricher to control the order here and your job as a manager or architect is done, provided, you have hired right tech resource !!!!

Working code can be found here.