Debugging Java | Delegation pattern with constructor based dependency injection


Several real world programming problem statements talk about the difficulties faced while trying to align differently fashioned processing of similar data. Taking a simple example, of processing of payroll/salaries of a company's employees. Payroll processing can get complicated if employees are based out of different geographies; salary components would vary, tax brackets etc will also differ. Core logic of such an application would require an adequate system which would manage such processing effectively.  

The post speaks about a simple implementation of delegation pattern in Java.
Delegation pattern, as the name suggests, is a scenario where the tasks/activities are delegated from one class to another. While there are several ways to do it(read: inheritance etc.), delegation pattern suggests the usage of composition (has-a relationship) instead of using inheritance (is-a relationship). 

We divide and represent our application into the following components:
Delegator Class(DependencyDelegator)
Performer Interface(DelegatedInterface)
Performer Class(DelegatedClassOne,DelegatedClassTwo)
Spring Config Class(SpringConfigClass)

As per the has-a paradigm, Delegator class has Performer's object as data members. All the performers get subscribed through a collection(map) in the Delegator. Performers are identified by markers, which act as key for the map. The method callDelegateEmitMethod in the Delegator is exposed to other applications/systems as an API method. Within the method the relevant performer gets called, based on the incoming marker, and takes up the task. It can emit an event/forward the processing up ahead as well. Maintaining delegation through interface, allows the DependencyDelegator class to inherit any other behaviors too, if need be. Furthermore, facilitating AI through processing legacy data and generating insights & forecasts can get simplified too.

Delegation pattern finds distinctive usage in applications which manage processing of different types of transactions. More-so, when there is range of Objects to cater to, as a part of processing different transactions. With the need of efficient tech. to handle the omni-present data and content created during financial transactions, social media feeds etc., the pattern forms center stage . 

Play around with the delegation pattern here. Blend the pattern with other mechanisms such as spring boot, RESTful end points, messaging frameworks etc. NOTE: The implementation uses Spring 4.3.9 for dependency injection.

Debugging Java 9 module system | Cyclic Dependency : The need and an alternate approach

 The inception of the module system as a part of project Jigsaw has brought in lot of emotions amongst software developers and technology enthusiasts alike. In a way, Java's programming constructs have a fresh feel altogether. A new direction, which if excercised efficiently, will help in having a better view and understanding of the application. Modules pack together all dependencies, which a code would require throughout it's life cycle.

Java 9 enhances the jars to modular jars, wherein each jar file comes with its own package [module] information. By this, we can have a clearer picture of all dependencies and entire object graph at an early stage. 

Cyclic Dependency

Here we discuss the cyclic dependency and the concerns of use cases where we cannot avoid it at all. 
Referring to the below object graph, lets assume we have a module Mod1 (AllTimeRef) with interface Mention & class TechNotes & Mod2 (SecondConcern) with classes ColorNotes[which accesses Mention interface from Mod1] & SamePackageClass. Also, Mod1 accesses ClsOne(SamePackageClass) from Mod2 as well, causing the cyclic dependency to take place.

 

As the general opinion for modules with cyclic dependency expresses: that the modules reflecting cyclic dependency are effectively the same module and should be maintained likewise, because they display a tightly integrated nature. 

Sometimes, due to some unavoidable circumstances, owing to the categorization of business objects, larger concerns etc.; the classes might have to be maintained in separate modules 1 & 2. The primary dependency going in the direction from 1 -> 2. Yet, there might be an object in 1 which would require 2's ClsOne to complete its definition, causing the cycle.



Refactor & add a separate independent smaller module

We might not be able to conjoin the modules and a both-way dependency has to exist. We can strategically tweak the modular design by cutting out ClsOne and maintaining it in a separate module 3. Subsequently, we can have both 1 & 2 depend upon module 3, alongside there current set of dependencies. This breaks the cycle!
Now the step of cutting out ClsOne is very dynamic and will totally depend upon the application design and object layout. In some of the application designs, with a need of cyclic dependency, it might not be possible to fetchout the "cycle causing object" out in a separate module. Whereas, in others, we might be able to achieve this.


We can incorporate this approach for all the plausible cases. 


Configuration

We can conveniently configure the above approach in our projects. Please note the below configuration has been done in Eclipse Oxygen with JDK 9 using maven as build tool.


Assumptions
Lets name our modules as per below:

Mod 1: AllTimeRef(module: com.jvb.self.modone), Mod 2: SecondConcern(module: com.jvb.self.modtwo), Mod 3: ThirdConcern(module: com.jvb.self.modthree). 

The main class is in SecondConcern (com.jvb.self.modtwo.BlackBookMain). The main class will be calling artifacts from all three modules. 


The class which breaks the cyclic dependency: SamePackageClass is moved to the module ThirdConcern (com.jvb.self.modthree). Its accessed(required) by both AllTimeRef and SecondConcern[of which it was originally a part, hence dependent]



  •  Make sure SecondConcern's pom has AllTimeRef & ThirdConcern dependencies. Also true for AllTimeRef's pom.xml to have ThirdConcern dependency.
  • Ensure that maven-compiler-plugin has both goals(compile, testCompile) mentioned in the plugin management.                                              
  • To refer ThirdConcern in AllTimeRef, we should have a 'requires' for modthree in AllTimeRef's modone:              
  • To refer ThirdConcern & AllTimeRef in SecondConcern, we should have a 'requires' for both in SecondConcern's modtwo:                                      

















  • For the dependencies to be available at run time, its imperative that they should be present already. To achieve this with maven, we do the routine mvn clean install against the dependencies first, then for the referring module.

      modthree.SamePackageClass in AllTimeRef 's modone 
        modone & modthree in SecondConcern's modtwo

    • One we have dependencies in place, the following modules will run successfully and will get all relevant imports from different modules as well.
    • Running the maven command mvn exec:java -Dexec.mainClass="com.jvb.self.modtwo.BlackBookMain" will run our artifacts, import resources from all dependencies, break the cycle without really disturbing the entire object graph.

    Debugging Go Programming Language | Implementing a binary tree: encoding to json & parallel processing

        Been a while since I took-up exploring Go Lang. The language's simplistic design, quick compilation & efficient concurrency mechanism gives enough substance for the language to be perceived as one of the potential platforms to develop web servers; container platforms(Docker) etc.

    Here we go through some of the features which can be capitalized to unleash the true innovation behind simplistic designs. Picking up an example of implementing a binary tree, we explore Go's salient features.

    Simplistic web servers                            

    Web server, traditionally, is an outcome of some lengthy designs based upon established methodologies/patterns. In the parallel world of Go, web servers can be created and initiated in as small as 3-5 lines of code.









    http.HandleFunc unleashes the in-built url routing by Go. Extending to that, we can conveniently route the request URIs based on URL parameter with the help of below code.

    Request URI: www.web.com/fetchinfo/4


           idstr := strings.TrimPrefix(request.URL.Path, "/fetchinfo/")

       id,err := strconv.Atoi(idstr)

    Making use of methods from "strings" & "strconv" libraries, we fetch the URL parameter and conditionally decide the request processing and corresponding function execution with http's 'HandleFunc'

    http.ListenAndServe in the last line of the below snippet, kick-starts the server at port 1706. With that port setting, we can time-travel to any year we want :D

    Self Ref. Pointers                      

    The pointer is a very efficient mechanism of transmitting data between functions, routines etc. A simple use-case which follows, highlights mentioning appropriate return types. The Go Playground highlights the efficient usage of 'pointer to struct' as return type of functions in a binary tree implementation & encoding to json. The self reference of struct makes the pointer as return type crucial for the design.

















    Forming an empty interface of TestObject struct at line # 68 and returning the pointer from the function helps return the content dynamically formed in the implementation (Line # 40) of inserttotree function and encode to json format in line # 70

    RESTful and APIs                        


    Go enables us to publish any and every sort of content, and expose methods as API. Below is an example of a binary tree generated in the Go Playground published in json.

     

    Parallel processing                     

    Go has an efficient mechanism which exploits multi-processor/multi-core environment. Goroutines are lightweight threads managed by the runtime

    Take a look above as to how the goroutines, reduce the execution time of multiple iterations of simple functions [taking ~ 1 second to complete] and spread the execution across mutli-processors.

    Go Programming opens doors to another bunch of simple, yet powerful features. Example: Multiple return values from a function implemenation etc. We'll continue exploring those in forthcoming posts.

    Debugging Java | Spring RESTful, JPA with Spring Boot | Separation of concerns

    This one's a brief update on the previous work on the basic implementation of Spring RESTful with JPA Repositories with separation of business logic and web aspect. I tried to migrate the same project on Spring boot.
    The spring boot reference gives an elaborate peak into developing a Spring boot application. Below are a few points which might be helpful from a migration perspective:


    • Boot application to detect entities from classpath: If we require model classes, business logic & JPA Repositories to be detected and injected from a jar in the classpath, scanBasePackages property of @SpringBootApplication will help us wire those with the main class being in a different project hierarchy
           

    • Config goes away Spring boot removes dependency on having any configuration setup. A web.xml file is also not needed. We can initialize the servlet in the boot main application class. The superpower annotation @SpringBootApplication enables MVC for us and initializes the dispatcher servlets. It additionally scans and wires the beans & components.
    • Specific qualifier infrastructure beans Spring boot configures the application based on the libraries in the classpath. For example, spring-tx-XYZ.jar facilitates configuring of transactionManager, spring-webmvc-XYZ.jar enables mvc in the application etc.
      But spring boot expects specific qualifier beans: for the transaction manager, it will require a bean with the name:
      transactionManager implementing PlatformTransactionManager. If P1.jar doesnt already supply a bean with the name, we must configure the bean with qualifier: transactionManager. We must autowire the EntityManagerFactoryBean as well.


    There are definitely many more points to be uncovered while we study & implement the genetics behind Java and related technologies. 

    Keep coding, keep exploring! 

    Watch this space for more. 

    Debugging Java Spring REST service | Segregation of project's business logic and web service implementation in diff jars

    This would be a trivial aspect to discuss, but I've been missing out on some specific points related to this while working on a similar requirement.

    I had earlier implemented a simple model project (read: P1)based on Spring, JPA API (with JPA repositories)
    (Find the implementation details of Spring + JPA nature of P1 in the hyperlink above)
    It was followed by implementing a Spring based REST web service (read: P2) on top of the project.

    To achieve modularity, some system designs want to control different natures of an application differently. If we can efficiently pluck the web aspect of an application away from the core business logic, it might be a different take on managing RESTful web applications.

    This post captures the challenges I faced while implementing the REST part in a separate project 'P2' while importing the model project 'P1' as a jar file in Eclipse IDE deployed on Tomcat server.

    Placing P1.jar in the P2's classpath, requires some additional configuration to ensure that all pieces fall in place.


    • Along with the usual <import resource="classpath*:targetConfig.xml"/> , we need to add XML Config in the Spring -> Beans support tab. Also, check the option of 'Enable support for <import/> element in configuration files'




    Doing this will have all the spring elements (Spring Beans, JpaRepositories, Service class, DataSource, EntityManagerFactory, TransactionManager) in the current project's context.
    • Ensure the import of beans from the P1's config xml in P2's spring element(which you can see by P2 -> Right click -> Spring Tools -> Add Spring Project Nature)

    • An important yet a very common setup requires providing a default persistence unit in P2's persistence.xml file. While running P2 without specifying the default persistence does capture the persistence unit from P1.jar, but strangely it doesn't capture the related properties of the persistence unit from P1, for example the managed classes listed in P1's persistence unit. Therefore, it becomes sort of a pre-requisite to register a default persistence-unit in P2 too (anybody among the readers, please correct me here if I am missing out on any points).CHECK: If we dont mention the default persistence unit in P2, it won't recognize the managed class from P1's persistence, and while running the Spring REST service, it gives the error: not a managed type.

    • Register spring controller with @RestController and method with @RequestMapping with appropriate RequestType (method=RequestMethod.POST/RequestMethod.GET)

    • Custom RequestBody: While running a POST request, create a custom class containing all the appropriate parameters to be provided as member variables in the class. Use this class as @RequestBody element in the POST request's method
    With all these settings in place, fly away with your Spring REST web service!

    Debugging Java with Spring,JPA API and Apache Derby DB

    This post highlights the usage of Spring with JPA API and basic configuration aspects for database interactions with Apache Derby database. The CHECK segments list resolution to some of the obstacles which I faced while trying to achieve the solution

    Once the object model is ready with you, you can create JPA Entities from tables.

    CHECK: Make sure the @Table annotation contains correct schema and table name against all Java entity beans. Otherwise the API won't hit the correct database, without even giving any error in the console, confusing the user even more.


    J.1.1 Autowiring components and persistence unit

    J.1.2 JPA Data repository for DB interaction

    We are using JPA Data repositories (one for each entity in the current design) for performing CRUD operations. JPA repositories are traditionally interfaces which supply CRUD methods: save(Entity T), findOne(Long Id) etc.


    The implementation (Service Implementation, which can also be exposed as a REST service) should contain an autowired instance of repository and the EntityManager(instance of EntityManagerFactory)


    CHECK: The call to the repository save method supplied by the JPA Data repository performs the actual merge. And there is no explicit need to call the commit method from the entity manager.

    J.1.3 Transactional Service

    If you want the CRUD operations to be transaction managed, then you'll have to incorporate TransactionManager (Section J.1.1) to wrap around the Entity Manager factory. Also, make appropriate use of @Transactional annotation as below:

    Experience rock music, the mystic way!

    “If you want the truth, 
    I’ll tell you the truth: 
    Listen to the secret sound, 
    the real sound, 
    which is inside you.”
    -Kabir

     Aristotle once said that knowing oneself is the beginning of all wisdom. The wanderer would be going places, meeting people, seeing things happening and would be experiencing his soul sinking into the transformations led by the concoction of the feelings. Amidst all this, he manages to talk back to his soul. He manages to disclose the realities of life, some of them really harsh. Yet another soul characterizing experience is that of indulging oneself into the verses of kabir's dohe which illustrate life's truthful lessons. And the folks at Neeraj Arya's Kabir Cafe provide a perfect means to impart a sense of wisdom in the listeners. Adding melody to the dohe, one at a time, they have certainly chosen an offbeat path in an already unconventional folk music scene. 
    There musicals begin with a classical touch of the mandolin or the violin giving a strong freshness to kabir's folklore. As it proceeds, the simplicity of Kabir's poetry blends with the rhythm. And the revelation of the divine takes place, through vernacular hindi. The instruments and the verses seem to share a tight bond. 
    The music is adorned with nature and there are many aspects of the group which give every bit of justification to the ancient poetry. The sturdy voice of Neeraj Arya himself serves as the chief constituent. Mukund Ramaswamy gives a unique texture to the melody through his violin. The mystical riffs from Raman Iyer's mandolin are guaranteed to strike the euphoric cords within the heart. Viren Solanki's percussion and Poubuanpou Bryeetokc's Guitar work as super adhesive holding all the entities together. All these additives are sufficient enough to get the verses back to life and reach out to the world. 
    The picturization of the group's compositions is minimalist. The videos consolidate a sense of parallelism between the 600 year old legacy and today's sketch of the society. Very simple aspects are uncovered in the videos. 
    Take a bow, you guys, for having been so keenly devoted towards promoting such a distinguished genre(read: Kabir Rock). 
    It is very important to decide between what one loves and what people think is right. - Neeraj Arya's Kabir Cafe