<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: charles1303</title>
    <description>The latest articles on DEV Community by charles1303 (@charles1303).</description>
    <link>https://dev.to/charles1303</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F125443%2F983ea1b9-813f-4b9f-a70c-80d42aa1ec30.jpg</url>
      <title>DEV Community: charles1303</title>
      <link>https://dev.to/charles1303</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/charles1303"/>
    <language>en</language>
    <item>
      <title>Security Using Spring and JWT</title>
      <dc:creator>charles1303</dc:creator>
      <pubDate>Sun, 23 Jun 2019 13:14:24 +0000</pubDate>
      <link>https://dev.to/charles1303/security-using-spring-and-jwt-aai</link>
      <guid>https://dev.to/charles1303/security-using-spring-and-jwt-aai</guid>
      <description>&lt;h3&gt;
  
  
  Introduction
&lt;/h3&gt;

&lt;p&gt;I've finally been able to get this article out. It took this long because of two major reasons; firstly I was enmeshed in a very interesting project over the past few weeks. It really felt good when we deployed it, did a test run and saw that all the stakeholders were happy about how the product met the expected criteria and the desired features. Secondly and on the sad side, my hard disk crashed and the recovery process was quite daunting. (I'm still taking stock of what I've lost so far especially my write ups and documentations). But thankfully most of my project codes were on their respective git repositories and the delta wasn't that much with what was on my laptop. Which is why I would like to use this opportunity to remind we developers again that we should always push to our code repositories as often as we can to a current working branch. Even if the task is not completely done or the code ain't compiling after working on it over time. It doesn't have to be everyday but at least make sure you commit and push within the week. That push could make you gush later in the future.&lt;/p&gt;

&lt;p&gt;Now that we have that out of the way, let's focus on what I really want to talk about in this article. In my last two articles &lt;a href="https://dev.to/charles1303/a-use-case-implementation-for-external-api-integration-eoj"&gt;here&lt;/a&gt; and &lt;a href="https://dev.to/charles1303/exception-handling-and-logging-2okh"&gt;here&lt;/a&gt;, I demonstrated on how to build REST APIs and integrate them with external APIs using Design patterns and best practices in developing applications. In this article I will be demonstrating on how to implement Security using JWT to secure our REST APIs. I will also highlight other strategies in securing our application especially with respect to data. I know this might be familiar topic, but they are usually written in isolation from the overall context of developing application. So we will be building on what we have developed in the previous articles I wrote. I will still be using the same approach in terms of class, component and method referencing so you might want to access the repo &lt;a href="https://github.com/charles1303/binlistImpl"&gt;here&lt;/a&gt; and also take a look at the previous articles to play catch up a bit.&lt;/p&gt;

&lt;h3&gt;
  
  
  Code Implementation
&lt;/h3&gt;

&lt;p&gt;Imagine you are a consultant, and you are about to book an appointment with a new client of yours. You know that the drill is to first register with the client as a consultant where you provide all your details that will be kept in their records. This is akin to the &lt;em&gt;Registration&lt;/em&gt; process that we do online when you want to use an application for the first time. After registration you then proceed to booking an appointment at an agreed upon date. Upon arrival at the premise, you identify yourself at the reception and if all checks out you are then given a visitor's tag or card which grants you access to certain parts or floors of the building. This process could be mapped to the login process of the application using your credentials when you registered. This is the &lt;em&gt;Authentication&lt;/em&gt; process and if your credentials are valid, you are granted access to the application. At the same time you are also issued a JWT(token) (or a session is generated for you in a stateful web application or a cookie for the browser). This token represents the visitor's tag that was issued to you. And just like the tag, token will grant you controlled access to resources in the application domain based on the role(s) assigned to the token. This is used in the &lt;em&gt;Authorization&lt;/em&gt; process to determine whether you can access a resource or not based on your role(s) (just as how the visitor's tag will only grant you access to certain floors in the building). Now just like the tag which can only be used for that day only, the token also has an expiration date and becomes invalid hence resulting in authorization failures and denial of access to resources. In some cases though, assuming you are not done with your consultation for that day, the tag can be reused for the next day based upon agreement. In the same vein, the token can also be refreshed upon request and a new expiration date is set for it after validating the old token. In the event, you are done with your consultation, you have to submit the tag before leaving the building. Likewise when you are done using the application, you need to logout so that the token is invalidated. And once you are out of the building or logged out of the application, you will have to repeat the identification process at the reception or the login process again to access the facility or the application in order to perform your activities. Now that we have a picture of how Authentication, Authorization and Token Generation and Management work together, Let's connect the dots using the Spring Security Framework and JWT:&lt;/p&gt;

&lt;p&gt;First we create our &lt;strong&gt;JwtManager&lt;/strong&gt; class to handle generating, validating and retrieval of information from our token. Then we create our &lt;strong&gt;CustomUserDetails&lt;/strong&gt; class. This class will store details of the Spring authenticated user or prinicipal. By implementing the &lt;em&gt;org.springframework.security.core.userdetails.UserDetails&lt;/em&gt; interface, it can access information such as username, password and the authorities granted to the principal via the user's assigned role(s). Next we create our &lt;strong&gt;CustomUserDetailsService&lt;/strong&gt; class. This class defines the custom implementation of the &lt;em&gt;loadUserByUsername&lt;/em&gt; method in the &lt;em&gt;org.springframework.security.core.userdetails.UserDetailsService&lt;/em&gt; interface that it implements and based on the outcome returns the CustomUserDetails instance we defined earlier. In this case we are querying the database with the username supplied to see if it exists or not. &lt;/p&gt;

&lt;p&gt;We then create our &lt;strong&gt;JwtAuthenticationFilter&lt;/strong&gt; class. This is class filters every incoming request against a protected resource to inspect and validate the token that is sent using the &lt;em&gt;validateToken&lt;/em&gt; method defined in our JwtManager class. If valid, it extracts the username (subject) and the roles from the token claims using the &lt;em&gt;getUsernameFromJWT&lt;/em&gt; and &lt;em&gt;getRolesFromJwt&lt;/em&gt; methods respectively that were defined in our JwtManager class and uses it to create a valid secuity context for the user so the user remains authenticated in the application. We could have equally used a second approach with just the username and the loadUserByUsername method of the CustomUserDetailsService class to achieve this with this code snippet&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        String jwt = getJwtFromRequest(request);

            if (StringUtils.hasText(jwt) &amp;amp;&amp;amp; jwtManager.validateToken(jwt)) {
                String username = jwtManager.getUsernameFromJWT(jwt);

        //Using an injected CustomUserDetailsService instance
        CustomUserDetails customUserDetails = customUserDetailsService.loadUserByUsername(username);
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(customUserDetails.getPrincipal(), "", customUserDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }else {
                SecurityContextHolder.getContext().setAuthentication(null);
            }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The disadvantage with the second approach is that there will be a performance database hit using the loadUserByUsername method for every request unlike the first approach where we gained application performance by retrieving the user's detail from the sent token. On the other hand, the second approach allows for real time modification of granted authorities when user roles are changed whereas the first approach will require the token to expire before it takes effect. Whichever approach you employ here is usually based on a design and requirement decision.&lt;/p&gt;

&lt;p&gt;Next we will create our &lt;strong&gt;CustomRestAccessDenied&lt;/strong&gt; and &lt;strong&gt;CustomRestAuthenticationEntryPoint&lt;/strong&gt; classes. As you can see, they implement the &lt;em&gt;org.springframework.security.web.access.AccessDeniedHandler&lt;/em&gt; and the &lt;em&gt;org.springframework.security.web.AuthenticationEntryPoint&lt;/em&gt; interfaces respectively. The &lt;em&gt;handle&lt;/em&gt; method in the CustomRestAccessDenied class is meant to be triggered for requests where users have been authenticated but do not have the permissible role to access the resources and returns a HTTP 403 status while the &lt;em&gt;commence&lt;/em&gt; method in the CustomRestAuthenticationEntryPoint class is triggered for unauthenticated users and returns a HTTP 401 status. You will see how this is setup when we look at our Security Configuration class implementation. Also note how the response is tailored to return in a particular format. This is so that we adhere to a consistent response structure in our application. For those who saw my last article on Exception handling, you maybe wondering why didn't we use that approach in this scenario. The reason for this is that the Access Denied and Unauthorized exceptions are thrown at an outer level than the Spring's ControllerAdvise and Exception can handle hence we have to handle these exceptions at the level which they occur.&lt;/p&gt;

&lt;p&gt;Now let's take a look at our Security configuration class which is the &lt;strong&gt;SecurityConfig&lt;/strong&gt; class. The SecurityConfig class which extends &lt;em&gt;org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter&lt;/em&gt; is what glues all the previous security components and classes we have defined so far. It determines the behaviour and roles they play in our application security implementation. The &lt;em&gt;securedEnabled, jsr250Enabled and prePostEnabled&lt;/em&gt; annotations allows us to determine what roles should have access to a particular resource. This can be configured either on the methods you want to apply these restrictions to (for example in the controllers) or append it to the &lt;em&gt;antMatchers&lt;/em&gt; as can be seen in the configure method of the SecurityConfig class. The CustomUserDetailsService class we defined earlier is injected and specified to be used as our authentication component in the overridden &lt;em&gt;public void configure(AuthenticationManagerBuilder authenticationManagerBuilder)&lt;/em&gt; method. We also configure a &lt;em&gt;PasswordEncorder&lt;/em&gt; bean to use the Spring's &lt;em&gt;BCryptPasswordEncoder&lt;/em&gt; to validate the user's password also in this method. In the overridden &lt;em&gt;protected void configure(HttpSecurity httpSecurity)&lt;/em&gt; method, we configured the Exception handlers for the unauthorized and access denied scenarios to use the injected CustomRestAuthenticationEntryPoint and CustomRestAccessDenied classes respectively. We disabled the csrf so that requests from other domains can access our endpoints and then we declare the session management to be stateless so as to conform to REST specifications. We then configure our injected JwtAuthenticationFilter class as the filter that will be called for every request to any of our secured resources. And finally we disable our security for endpoints within the /api/auth/ route as this will be called by unauthenticated users during registration and login.&lt;/p&gt;

&lt;p&gt;Let's now create the components that will allow users to be able to register and login on our application. First we create our &lt;strong&gt;User&lt;/strong&gt; class entity that will map to our &lt;em&gt;users&lt;/em&gt; table in the database. We also create the &lt;strong&gt;Role&lt;/strong&gt; class entity as well that will map to the &lt;em&gt;roles&lt;/em&gt; table. We then insert into the roles table the following roles: ROLE_USER and ROLE_ADMIN. Then we create the &lt;strong&gt;UserRepository&lt;/strong&gt; and &lt;strong&gt;UserService&lt;/strong&gt; classes for managing our User entity and the &lt;strong&gt;RoleRepository&lt;/strong&gt; and &lt;strong&gt;RoleService&lt;/strong&gt; classes to manage our Role entity. For integrity, we create a &lt;strong&gt;RoleType&lt;/strong&gt; enum that maps to the roles we just created in our roles table. We then create our &lt;strong&gt;AuthController&lt;/strong&gt; class to handle registration and login. As you can see, the registration endpoint  is pretty straightforward. We create a user with the assigned roles and store in the database. For the login endpoint, you supply a registered username and password and if authentication by the Spring Security framework is successful, a valid secuity context for the user is set using the Spring's &lt;em&gt;Authencation&lt;/em&gt; object. The &lt;em&gt;generateToken&lt;/em&gt; method of the JwtManager then takes in the authentication as a parameter and sets a Claims object's subject with the username and puts the authorities gotten from the Principal which were all gotten from the authentication object as roles into the Claims object. A token is then generated using the constructed Claims object and setting the expiry date, time it was issued and finally signed with our token secret key. &lt;/p&gt;

&lt;h3&gt;
  
  
  Test Run
&lt;/h3&gt;

&lt;p&gt;All is now set so we can launch our spring application using mvn spring-boot:run and then we try to register by hitting the endpoint using our &lt;strong&gt;SignUpRequest&lt;/strong&gt; dto class structure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    POST    http://localhost:8080/api/auth/register
    {

    "name":"user1",
    "username":"username1",
    "email":"username1@email.com",
    "password":"password1"
    }

       Response:
    {
        "status": 0,
        "message": "User registered successfully",
        "result": null
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Repeat the above for another user to create and admin&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    POST    http://localhost:8080/api/auth/register/admin
    {

    "name":"user2",
    "username":"username2",
    "email":"username2@email.com",
    "password":"password2"
    }

        Response:
    {
        "status": 0,
        "message": "Admin registered successfully",
        "result": null
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Login with both users using our &lt;strong&gt;LoginRequest&lt;/strong&gt; dto class structure and get the respective tokens that will be returned for both users&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    POST http://localhost:8080/api/auth/login

    {
    "username":"username1",
    "password":"password1"
    }

        Response:
    {
        "status": 0,
        "message": "Token generated successfully",
        "result": {
        "accessToken": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VybmFtZTEiLCJyb2xlcyI6WyJST0xFX0FETUlOIl0sImlhdCI6MTU2MDk4MDU1MywiZXhwIjoxNTYwOTgyMzUzfQ.boqHQh3gLPgNWBP0GiATBGg-25bwMfg33-zn5BFK9AiFuhYcWcmSSFp_isjlhL_xJ9WxMW6A7UWaVOXMdx94ng"
        }
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Calling any of our endpoints without a token or an invalid or expired token will give you a response triggered by our CustomRestAuthenticationEntryPoint handler with a HTTP 401 status code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    {
        "timestamp": "2019-06-19T22:51:37.189",
        "message": "Unauthorized user",
        "status": 401
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;While calling an endpoint with an unauthorized role say&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;http://localhost:8080/card-scheme/stats?start=1&amp;amp;limit=10&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;with the user1 generated token will give a response triggered by our CustomRestAccessDenied handler with HTTP 403 status code because only Admin roles can access it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    {
        "timestamp": "2019-06-19T22:51:57.213",
        "message": "Access Denied",
        "status": 403
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;
  
  
  Unit Testing
&lt;/h3&gt;

&lt;p&gt;Let's now look at how we will setup writing our tests. Because we are concerned about Authentication and Authorization, we will be restricting our test scopes to not go beyond the controller layer as this is where these restrictions are placed. To achieve this I created the &lt;strong&gt;SecurityTest&lt;/strong&gt; class and annotated it with the &lt;em&gt;@WebMvcTest&lt;/em&gt; annotation. Then I mocked every dependencies that are needed at the controller layer except for JwtManager which I spied. The reason being that I will actually be calling the real methods in the JwtManager class in our test for token generation and validation. Then I created &lt;strong&gt;AppTestConfig&lt;/strong&gt; configuration class and set the base package scanning at the controller layer. However I had to create an &lt;em&gt;EntityManagerFactory&lt;/em&gt; bean that will be using an in-memory H2 database for startup and bootstrapping. In my setUp method, I then added the JwtAuthenticationFilter instance as a filter for validating the token. And finally I enabled Spring security with &lt;em&gt;.apply(springSecurity())&lt;/em&gt;. Running the tests will give us the expected outcomes as defined in our test class.&lt;/p&gt;

&lt;p&gt;Before we conclude on this article, let's talk about other aspects of securing our application.&lt;/p&gt;

&lt;h3&gt;
  
  
  Data Encryption
&lt;/h3&gt;

&lt;p&gt;Data Encryption has been around for as long as the ability for humans to communicate came into being. I will not go into historical accounts of these evidences but data encryption is almost just as important as the exchange of information between individuals or parties. Data Encryption is simply the act of making information useless or cryptic to unintended recipients except for the intended recipient(s).&lt;/p&gt;

&lt;p&gt;In today's world, Data Encryption is based on two different forms of cryptography:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Symmetric key &lt;/li&gt;
&lt;li&gt;Asymmetric key.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The symmetric key form which uses the &lt;em&gt;AES&lt;/em&gt; algorithm, uses a single key both for encryption and decryption and is shared by parties involved. On the other hand, asymmetric key which uses the &lt;em&gt;RSA&lt;/em&gt; algorithm involves two keys, public and private keys. The public key can be shared with anyone, but the private key must remain a secret. Both can be used to encrypt a message, and the opposite key from the one originally used to encrypt that message is then used to decode it. Also there is the concept of signing the encrypted data which is very useful for &lt;em&gt;Non-repudiation&lt;/em&gt;. This invloves using the private key to sign the encrypted and the public key is then used to verify the signature. &lt;/p&gt;

&lt;p&gt;Although there was really no use case to implement any of these encryption forms in our application, you can take a look at the &lt;strong&gt;RSAEncryption&lt;/strong&gt;, &lt;strong&gt;AESEncryption&lt;/strong&gt; and &lt;strong&gt;EncryptionAndSignTest&lt;/strong&gt; classes I created to see the available utility methods and how they are used to perform various operations. Notice how in the RSAEncryption class how you can either generate keys dynamically by calling the &lt;em&gt;generateKeyPair&lt;/em&gt; method or load from a keystore file by calling the &lt;em&gt;getKeyPairFromKeyStore&lt;/em&gt; method. The keystore file can be generated using the Java keytool utility. One guiding rule in determining which form to use (RSA or AES) is the size of the data to encrypt. For large amounts of data, it is advised to use the AES form as it's faster and less computationally intensive while the RSA can be used for smaller amounts of data.&lt;/p&gt;

&lt;p&gt;Data encryption can be done both at rest and in motion.&lt;/p&gt;

&lt;p&gt;A common example of data at motion encryption is the use of the HTTPS protocol. What happens here is that when the browser makes a request to a SSL server, it gets the public key and generates a random based key. It then uses the public key to encrypt the generated key and sends it back to the server. The server then uses the private key to decrypt and retrieve the generated key. It is this generated key that both the server and the browser use for encryption and decryption when exchanging information. The advantage of this is that only the browser session and the server knows the generated key used for exchange of information. &lt;/p&gt;

&lt;p&gt;For non browser applications, we can simulate the above scenario as well whereby key pairs are generated (public and private keys using the encryption classes I just mentioned above). The involved applications then exchange their public keys and is/are used to encrypt and verify signatures while the private keys are used to decrypt and sign the data.&lt;/p&gt;

&lt;p&gt;So in our case here, we can equally achieve data encryption for data in motion by leveraging our application on the HTTPS protocol. Hence our solution will be more of an architectural implementation rather than a coding one.&lt;/p&gt;

&lt;p&gt;In the case of data encryption at rest, this usually involves protecting data within our data storage components or systems such as our databases (be it RDBMS, NOSQL or even our caching systems) and even our configuration file values. In other words, using the encryption utility classes I created earlier, we can store our data in an encrypted format and only decrypt when it is about to be used within the application. This approach will make the data in our datastore cryptic and unreadable should it fall into the wrong hands. We can also choose to encrypt our data without expecting to decrypt it back so long as we know the algorithm we used in encrypting it in the first place. This is a lot safer than encryption and it is known as &lt;em&gt;Hashing&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;A classic example of hashing here is the storage of users' passwords in our database (Recently there was an outcry of Facebook storing passwords of Instagram users in plain text). We achieved it here using the hashing implementation which is unidirectional. In otherwords unlike the encryption technique discussed earlier, it can't be decrypted (or impossible in practicality) after it's been hashed. The principle here is that hashing a particular sequence of string with a particular algorithm will always produce the same encrypted string (except in the case of Salting which I will discuss shortly). Here we used the BCryptPasswordEncoder &lt;em&gt;encode&lt;/em&gt; method to achieve this as can be seen in our SecurityConfig class where it is being used as our PasswordEncoder and used when creating our users during the registration process.&lt;/p&gt;

&lt;p&gt;Merely hashing our passwords isn't just enough to secure them. The availability of Rainbow tables has proven this to be so. The online availability of these tools have made cracking passwords a hobby for hackers especially the very simple and common ones such as popular words, sequential alphabets and numbers, and even personal information such as names, dates etc. This has led to the concept known as &lt;em&gt;Salting&lt;/em&gt;. Salting is a technique whereby random sequence of characters are added as part of the parameters required for password hashing. It makes using rainbow tables very difficult to use as even the simple password instances mentioned above will no longer have entries in these tables as a result of salting.&lt;/p&gt;

&lt;p&gt;In older implementations, Spring provided the &lt;em&gt;MessageDigestPasswordEncoder&lt;/em&gt; class which allowed us to provide our own salt string for hashing our password. An efficient usage of this was to provide a different salt string for every password string to be hashed (e.g time in milliseconds at point of registration). However this has been deprecated in favour of the BCryptPasswordEncoder which we are currently using in our application. The BCryptPasswordEncoder not only hashes our password but internally generates a random salt string for us in the process as can be seen when looked at its internal implementation. This implementation unburdens us with the overhead of managing the generation of salt strings as this crucial in the integrity of our passwords. As a result of this, a different hashed string produced everytime you hash the same password string. Now the question arises how do we determine compare and match the passwords? The BCryptPasswordEncoder implementation breaks down the hashed string into the salt string, cost parameter and the hashed value all of which can be obtained from the hashed string and since the salt determines the generated hash, it can be used to determine whether the supplied passwords match or not with what we have in store.&lt;/p&gt;

&lt;p&gt;And finally, I'd like to talk about securing our application configuration file which is usually either named as &lt;strong&gt;application.properties&lt;/strong&gt; file or &lt;strong&gt;application.yaml&lt;/strong&gt; as in our case. Although in our case you will notice that sensitive information like the database credentials are currently being retrieved from environment variables, I've seen cases where these details are stored as plain text within the file. Even though the use of environment variables mitigates to an extent the risk of having them as plain text in the file, another approach will be the use of &lt;em&gt;Jasypt Spring boot starter module&lt;/em&gt;. This module allows us to store values in its encrypted form and then decrypted for use at runtime.&lt;/p&gt;

&lt;p&gt;To implement this in our application, we first need to add the &lt;em&gt;jasypt-spring-boot-starter&lt;/em&gt; to our &lt;strong&gt;pom.xml&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;com.github.ulisesbocchio&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;jasypt-spring-boot-starter&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;2.1.1&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Then we run the command below&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;java -cp $M2_REPO/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar  org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="yourpassword" password=jasypt_password algorithm=PBEWithMD5AndDES
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;where &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;$M2_REPO&lt;/em&gt; is your maven repoistory directory&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;input&lt;/em&gt; argument is the password u need to encrypt say for example your database password&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;password&lt;/em&gt; argument is the Jasypt password or key for encryption you will be supplying when starting up your application&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;algorithm&lt;/em&gt; is the Password Based Encryption (PBE) algorithm of your choice provided by Jasypt (&lt;em&gt;PBEWITHMD5ANDDES, PBEWITHMD5ANDTRIPLEDES, PBEWITHSHA1ANDDESEDE, PBEWITHSHA1ANDRC2_40&lt;/em&gt;)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The above command will produce an encrypted value of the input argument password value you provided. You can repeat the command for any other values you may wish to encrypt in the application.properties or yaml file.&lt;/p&gt;

&lt;p&gt;You then set the properties or environment variable value(s) with these encrypted value in this format &lt;em&gt;ENC(encrypted_value)&lt;/em&gt; for example in our yaml you can change the password value like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.
.
.
spring:
  profiles: development
  application:
    name: binList
  datasource:
     password: ENC(encrypted_password_from_jasypt_operation)
     .
     .
     .

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;or you simply leave the yaml file as is and set the SPRING_DATASOURCE_PASSWORD environment variable with it&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export SPRING_DATASOURCE_PASSWORD=ENC(encrypted_password_from_jasypt_operation)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Then you either start your application like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mvn -Djasypt.encryptor.password=jasypt_password spring-boot:run
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;or you export the JASYPT_ENCRYPTOR_PASSWORD environment variable and simply just run mvn spring-boot:run&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export JASYPT_ENCRYPTOR_PASSWORD=jasypt_password
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;To further tighten security on our application server, you can do the following steps sequentially&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Export and set all the environment variables mentioned earlier using a batch script (.sh or .bat depending on your OS)&lt;/li&gt;
&lt;li&gt;Start up the application as a background service like this mvn spring-boot:run &amp;amp; or as a Windows Service&lt;/li&gt;
&lt;li&gt;unset all the environment variables using a batch script since these values are only requested for once on application start up.&lt;/li&gt;
&lt;li&gt;Delete the batch script(s) so long as you have a copy elsewhere.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The reason for these steps is to prevent users querying your application server using the ps and history commands to view the passwords or environment variables from previously ran commands.&lt;/p&gt;

&lt;p&gt;So there you have it. We have secured our application although as we all know security can never be total but it should slow down and require more effort for someone to maliciously use our application. There are other security strategies I have left out here especially at Data Access Object layer such as query input parameterization for SQL injection due to lack of SQL or JQL implementations in our application. You can access the updated source code for this article &lt;a href="https://github.com/charles1303/binlistImpl"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In my next article if time permits me I will be demonstrating how to achieve &lt;em&gt;Scalability&lt;/em&gt; and &lt;em&gt;Availability&lt;/em&gt; with our application using &lt;em&gt;Docker&lt;/em&gt; and some code refactorings. Also I hope to recover the &lt;em&gt;Laravel and Node(NestJs)&lt;/em&gt; implementations of what we have done so far from my laptop crash and share it. That's all folks! Happy Coding.&lt;/p&gt;

</description>
      <category>java</category>
      <category>spring</category>
      <category>jwt</category>
      <category>security</category>
    </item>
    <item>
      <title>Exception Handling and Logging</title>
      <dc:creator>charles1303</dc:creator>
      <pubDate>Mon, 01 Apr 2019 19:59:37 +0000</pubDate>
      <link>https://dev.to/charles1303/exception-handling-and-logging-2okh</link>
      <guid>https://dev.to/charles1303/exception-handling-and-logging-2okh</guid>
      <description>

&lt;h4&gt;
  
  
  Introduction
&lt;/h4&gt;

&lt;p&gt;In my last article &lt;a href="https://dev.to/charles1303/a-use-case-implementation-for-external-api-integration-eoj"&gt;here&lt;/a&gt;, We discussed the implementations and steps that were taken to integrate our application to an external API. We highlighted the design patterns and strategies used to carry out the task. They were divided into the following sections.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Design patterns&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Performance&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Testing&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this article, I will be building on what we did in the last article on how to implement the following requirements:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Exception handling&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Logging&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Exception Handling
&lt;/h4&gt;

&lt;p&gt;Exception handling can be seen as a way of providing &lt;em&gt;Resilience&lt;/em&gt; to our application. It allows the application to continue to behave normally even when things go wrong but at the same time report what went wrong. Imagine we get a 404 HttpException when trying to access the external API due to its unavailability at some point or we get a database connection exception which will mostly likely lead to a 500 HttpException. We wouldn't want our application to become unusable or behave unxepectedly due to this scenarios. It should still function properly by giving a predfined response adhering to the expected response format or structure of the application. And this is a good practice because a system being down should not mean that every other system or feature in our deployment infrastructure should be down or inaccessible. Rather our application should still be accessible and respond normally but report that something went wrong in a presentable manner and behaviour. We can think of exception handling as a sort of prescriptive analytics in the Big Data world.&lt;/p&gt;

&lt;p&gt;In our Spring Implementation, we create a class and annotate it with &lt;em&gt;ControllerAdvice&lt;/em&gt; as seen in the &lt;strong&gt;CardDetailControllerAdvise class&lt;/strong&gt;. Then we define methods to handle the exception scenarios. Ensure that in your controllers that you throw the appropriate anticipated exceptions as seen in the &lt;strong&gt;CardDetailController class&lt;/strong&gt;. I have also introduced two new classes &lt;strong&gt;RecordNotFoundException&lt;/strong&gt; and &lt;strong&gt;GeneralException&lt;/strong&gt; that are used in my business use cases. I also introduced the &lt;strong&gt;HttpStatusCodeException class&lt;/strong&gt; in the CardDetailControllerAdvise class to cater for HTTP level exceptions (in this case our 404 and 500). Of course you can extend or decorate the &lt;strong&gt;getHttpExceptionDetails&lt;/strong&gt; method in the advice class to add other HTTP Exceptions.&lt;/p&gt;

&lt;p&gt;On a side note, when implementing Exception handling, a clean approach is to avoid using Exceptions in your decision making. For example rather than do this:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight java"&gt;&lt;code&gt;    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;execute&lt;/span&gt; &lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Code to execute&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
     &lt;span class="o"&gt;}&lt;/span&gt;&lt;span class="k"&gt;catch&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Exception&lt;/span&gt; &lt;span class="n"&gt;ex&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
       &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;either do this&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight java"&gt;&lt;code&gt;    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;execute&lt;/span&gt; &lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;//Code to execute&lt;/span&gt;
            &lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;&lt;span class="k"&gt;catch&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;FileNotFoundException&lt;/span&gt; &lt;span class="n"&gt;ex&lt;/span&gt; &lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
          &lt;span class="c1"&gt;//Log exception details&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;or you simply throw the exception like this so it propagates to the caller of the method who then decides how to proceed as in our case&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight java"&gt;&lt;code&gt;    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;execute&lt;/span&gt; &lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="kd"&gt;throws&lt;/span&gt; &lt;span class="n"&gt;CustomException&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;//Code to execute&lt;/span&gt;
            &lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;&lt;span class="k"&gt;catch&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;FileNotFoundException&lt;/span&gt; &lt;span class="n"&gt;ex&lt;/span&gt; &lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
          &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;CustomException&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Could not access file resource."&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Here we are wrapping our exception in a CustomException class that is thrown when this exception scenario occurs. We simply override the constructor of the java.lang.Exception class that takes in a message (which is the message we would like to present to the client) and a Throwable object (in this case the Exception object that is thrown).&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight java"&gt;&lt;code&gt;    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CustomException&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="n"&gt;Exception&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;  
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;CustomException&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt; &lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;Exception&lt;/span&gt; &lt;span class="n"&gt;ex&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;super&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;ex&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The above implementation can be seen in the &lt;strong&gt;getCardRequestLogsCountGroupedByCard&lt;/strong&gt; method of the &lt;strong&gt;CardDetailService class&lt;/strong&gt;. This gives a response format consistent with the application's predefined response format and also allows you to control the exception message content using a more centralized approach with the help of the &lt;strong&gt;CardDetailControllerAdvise class&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;Now Guess what! Our &lt;strong&gt;CacheIntegrationTest class&lt;/strong&gt; is now failing because it is now throwing an Exception based on the above implementation. In this case, because our &lt;strong&gt;CardDetailRequestLogRepository class&lt;/strong&gt; is actually being mocked, its &lt;strong&gt;getCardRequestLogsCountGroupedByCardNumber&lt;/strong&gt; method will return null resulting in throwing the GeneralException class. So we need to create an &lt;em&gt;ExpectedException&lt;/em&gt; rule in the CacheIntegrationTest class and test for the GeneralException that is expected to be thrown.&lt;/p&gt;

&lt;p&gt;It is good practice to wrap our API exceptions so that one can localize the source and cause of the exception at a high level of analysis and investigation.&lt;/p&gt;

&lt;p&gt;Also due to the inherent increased I/O operation when writing to logs and memory usage which occurs as a result of throwing exceptions, we should either log the exception or throw it but not both as shown earlier. Doing this can lead to what is commonly referred to as the &lt;em&gt;Hot Potato&lt;/em&gt; anti pattern design. This creates a scenario whereby a lot of CPU intensive work is done with relatively little valuable output leading to application spikes in CPU usage and memory consumption. Throwing and logging an exception will also result in a bunch of log messages which aren't really needed. Hence amount of text will reduce the visibility of the logs.&lt;/p&gt;

&lt;p&gt;Apart from the above approach of handling exceptions, people do employ the strategy of caching data responses from an external API into a data store. These data responses are then accessed from the cached system when the external API is unavailable or something went wrong. This strategy is a design pattern known as the &lt;em&gt;Circuit Breaker&lt;/em&gt;. The fault tolerance library &lt;em&gt;Hystrix&lt;/em&gt; is a common implementation of this pattern as I will show you in a bit. &lt;/p&gt;

&lt;p&gt;First of all we include the spring-cloud-starter-netflix-hystrix dependency in our project.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight xml"&gt;&lt;code&gt;    &lt;span class="nt"&gt;&amp;lt;dependency&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;groupId&amp;gt;&lt;/span&gt;org.springframework.cloud&lt;span class="nt"&gt;&amp;lt;/groupId&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;artifactId&amp;gt;&lt;/span&gt;spring-cloud-starter-netflix-hystrix&lt;span class="nt"&gt;&amp;lt;/artifactId&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;version&amp;gt;&lt;/span&gt;2.1.1.RELEASE&lt;span class="nt"&gt;&amp;lt;/version&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;/dependency&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Then we create a method &lt;strong&gt;verifyCardDetailHystrix&lt;/strong&gt; in the &lt;strong&gt;CardDetailService class&lt;/strong&gt; and annotate it with the &lt;em&gt;HystrixCommand&lt;/em&gt; and setting the necessary &lt;em&gt;HystrixProperty&lt;/em&gt; values. Then we create a fallback method &lt;strong&gt;defaultCardDetailDto&lt;/strong&gt; that will be called when the API is unreacheable after a period so as to return our cached or default data. Finally we enable the circuit breaker by annotating our &lt;strong&gt;Application class&lt;/strong&gt; with &lt;em&gt;EnableCircuitBreaker&lt;/em&gt;. And that's it. The defaultCardDetailDto method would be called whenever the API is unavailable. Apart from the ones I used, there are a number of other HystrixProperties you can tweak to suit your application specification.&lt;/p&gt;

&lt;h4&gt;
  
  
  Logging
&lt;/h4&gt;

&lt;p&gt;We have talked about how to keep track of application activities, present default or cached data and notify users of the application state when something goes wrong. What if we also want to keep track of application states when all goes well without any exceptions (i.e the Happy Path)? The advantage of this that we will then have a holistic view of all the activities that have taken place in the application. It can also help us to replay all the activities of an application between any given points in time during the lifecycle of the application. &lt;/p&gt;

&lt;p&gt;Even though we introduced the concept of logging in our pseudo codes earlier, we will talk in depth as to ways and strategies of implementing application logging for auditing.&lt;/p&gt;

&lt;p&gt;Logging is a means of auditing or keeping track of every activity that has taken place in the application or system. This is crucial as this can tell us the activities that took place at any particular point in time during the lifecycle of the application. There are quite a number of approaches to implementing this but I will highlight on two common approaches.&lt;/p&gt;

&lt;p&gt;In the first approach, we can sprinkle our codes with logging information using standard libraries such as &lt;em&gt;Log4j&lt;/em&gt; or &lt;em&gt;Sl4j&lt;/em&gt; implementations. Here we add these libraries as dependencies in our projects and then call the methods that prints out whatever we want printed. To avoid unnecessary I/O operations, we can call these methods at the beginning and at the end of a method body.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight java"&gt;&lt;code&gt;    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CardDetailService&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;Logger&lt;/span&gt; &lt;span class="n"&gt;logger&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;LoggerFactory&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getLogger&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;CardDetailService&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;execute&lt;/span&gt; &lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="kd"&gt;throws&lt;/span&gt; &lt;span class="n"&gt;CustomException&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

           &lt;span class="n"&gt;logger&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;debug&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"execute method started"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

            &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

            &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                &lt;span class="c1"&gt;//Code to execute&lt;/span&gt;
                &lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
            &lt;span class="o"&gt;}&lt;/span&gt;&lt;span class="k"&gt;catch&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;FileNotFoundException&lt;/span&gt; &lt;span class="n"&gt;ex&lt;/span&gt; &lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
              &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;CustomException&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Could not access file resource."&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="o"&gt;}&lt;/span&gt;
              &lt;span class="n"&gt;logger&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;debug&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"execute method ended"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;em&gt;(For those in the PHP Laravel world, there is a shipped in Log facade that has the same signature call as in above i.e Log::debug('An informational message.');)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This approach tells us the activities/operations that took place in the application at a given point time. The downside to this is that it doesn't tell us the states of objects being acted upon during that period. Note however that with the above implementation, if an exception is thrown, it will be logged as well.&lt;/p&gt;

&lt;p&gt;We can also control the logging level to reduce the amount of logging information hence I/O operations. This can be done either using the &lt;strong&gt;application.yml&lt;/strong&gt; and &lt;strong&gt;logback-spring.xml&lt;/strong&gt; files in our project or at the container/application server level. Notice how I set the logging levels in the application.yml file based on java packages to &lt;em&gt;ERROR&lt;/em&gt; level based on our earlier recommendation. We also set the output pattern of every log event that will be written to our log files such that it prints the log time and level, class where the logs is being triggered and the message to print. In the logback-spring.xml file, we set the &lt;em&gt;RollingFileAppender&lt;/em&gt; properties to control the name and size of each log file that will be generated, the maximum number and size of total log files to be kept on the server.&lt;/p&gt;

&lt;p&gt;The other approach of logging uses a very common design pattern known as &lt;em&gt;Event Sourcing&lt;/em&gt;. Here we store all the events/activities and the corresponding changes made of objects or models in our application. Then, to retrieve an object's or model's state we then read the different events/activities related to it and apply them one by one. It ensures that all changes to application state are stored as a sequence of events. This is quite similar to &lt;em&gt;JPA Hibernate Envers&lt;/em&gt; implementation (where we annotate the JPA entities with &lt;em&gt;@Audited&lt;/em&gt; leading to mirror images of model states being created in the database) except that in Event Sourcing, these changes are tied to the actual end-user activity that led to these model state changes.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;In the Laravel world, this is implemented by adding the either the EventSauce or prooph dependency. You create your models, then define the Events, create the Projector and handle side effects such as notifications using Reactors. For sake of scope of this article and the framework we are using, I will not go into details on this but the concept is the same and this pattern can be applied on other technology stacks as well.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In our case here, using the Spring framework, I will show a high level and basic implementation. &lt;/p&gt;

&lt;p&gt;First we bring in the dependency like below into our &lt;strong&gt;pom.xml&lt;/strong&gt; file :&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight xml"&gt;&lt;code&gt;        &lt;span class="nt"&gt;&amp;lt;dependency&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;groupId&amp;gt;&lt;/span&gt;org.axonframework&lt;span class="nt"&gt;&amp;lt;/groupId&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;artifactId&amp;gt;&lt;/span&gt;axon-spring-boot-starter&lt;span class="nt"&gt;&amp;lt;/artifactId&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;version&amp;gt;&lt;/span&gt;4.1&lt;span class="nt"&gt;&amp;lt;/version&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;/dependency&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;dependency&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;groupId&amp;gt;&lt;/span&gt;org.axonframework&lt;span class="nt"&gt;&amp;lt;/groupId&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;artifactId&amp;gt;&lt;/span&gt;axon-test&lt;span class="nt"&gt;&amp;lt;/artifactId&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;version&amp;gt;&lt;/span&gt;4.0.3&lt;span class="nt"&gt;&amp;lt;/version&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;scope&amp;gt;&lt;/span&gt;test&lt;span class="nt"&gt;&amp;lt;/scope&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;/dependency&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Then download the axon server, extract to a folder of your choice. This is what we will be using as our &lt;em&gt;EventStore&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;We go ahead and create the Aggregate &lt;strong&gt;(CardDetailRequestAggregate)&lt;/strong&gt;, Event &lt;strong&gt;(CardDetailRequestCreatedEvent)&lt;/strong&gt; and Command &lt;strong&gt;(CreateCardDetailRequestCommand)&lt;/strong&gt; classes. Then we create the command and event handler methods in the &lt;strong&gt;CardDetailRequestAggregate&lt;/strong&gt; for the CardDetailRequestCreatedEvent and CreateCardDetailRequestCommand classes. In very simple terms, the command class and the method annotated with &lt;em&gt;CommandHandler&lt;/em&gt; are responsible for determining which action or event was triggered based on a user input  via the &lt;em&gt;CommandGateway&lt;/em&gt; interface. It's similar to the &lt;em&gt;Command&lt;/em&gt; design pattern in implementation. While the Event class and the corresponding annotated &lt;em&gt;EventSourcingHandler&lt;/em&gt; methods are responsible via the &lt;em&gt;EventStore&lt;/em&gt; interface for the side effect that occurred as a result of the event or action that was triggered. The event components are also responsible for retrieval from and persistence of the Aggregate models also via the EventStore interface. The usage of the CommandGateway interface and the EventStore interface can be seen in the &lt;strong&gt;CardDetailCommandComponent class&lt;/strong&gt;. The method &lt;strong&gt;logCardDetailRequest&lt;/strong&gt; which was our existing function in the &lt;strong&gt;CardDetailService class&lt;/strong&gt; earlier in our last article is overloaded to accept the CardDetailRequestCreatedEvent object and annotated with the &lt;em&gt;EventHandler&lt;/em&gt;. The EventHandler annotation will trigger the logCardDetailRequest method when we send our command object via the CommandGateway as can be seen in the &lt;strong&gt;createCardDetalRequestLog&lt;/strong&gt; method of the CardDetailCommandComponent class.&lt;/p&gt;

&lt;p&gt;We can now start up our axon server using &lt;em&gt;java -jar axonserver.jar&lt;/em&gt; command and the spring boot application. When we hit the endpoint, our function will be called as expected. If you go to the Axon Server dashboard, you will see an entry having the CardDetailRequestCreatedEvent event that was triggered with the value of the cardNumber and date you made a request with. The beauty of this approach is that we no longer burden the &lt;strong&gt;verifyCardDetailHystrix&lt;/strong&gt; method in the CardDetailService class with the responsibility of logging as in the previous implementation whereby we called the logCardDetailRequest method. Hence we have in a way applied the &lt;em&gt;Single Responsibility&lt;/em&gt; principle to that method which is one of the tenets of clean coding (&lt;em&gt;S.O.L.I.D&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;Because logging is more or less a non-functional requirement, one crucial factor to consider here is to ensure that the logging process does not impact on the application performance hence user experience. For this reason, it is advisable to make the logging process asynchronous as can be seen the reason why I am using the CompletableFuture in the service class for the return object which of course is the default implementation of the Axon framework. Another point of consideration if you have the resources, is to point your Event Sourcing implementation to a different datastore from the primary application database as its event store. In our case, this is being handled by the Axon Server we are running locally. The Axon implementation can also be configured to use other data stores such as RDBMS or NOSql databases as its event store. This way you can have a sort of backed up data to replay your application lifecycle and restore previously generated data should something go wrong with the primary application database.&lt;/p&gt;

&lt;p&gt;So there you have it, our application now has resilience, tolerance as well as best practices for exception handling and logging which are requirements for a well architected system. And not to worry, I have updated our repo &lt;a href="https://github.com/charles1303/binlistImpl"&gt;here&lt;/a&gt; to include all the implementations discussed in this article. In my next article, I will be highlighting on &lt;strong&gt;Security&lt;/strong&gt;, a very crucial requirement for building applications and how to achieve &lt;strong&gt;Scalability&lt;/strong&gt; and &lt;strong&gt;Availability&lt;/strong&gt; with our application using &lt;em&gt;Docker&lt;/em&gt; as the virtualization technology. Happy Coding!&lt;/p&gt;


</description>
      <category>exceptions</category>
      <category>logging</category>
      <category>designpatterns</category>
      <category>apiintegration</category>
    </item>
    <item>
      <title>A Use Case Implementation for External API Integration</title>
      <dc:creator>charles1303</dc:creator>
      <pubDate>Mon, 18 Feb 2019 17:14:18 +0000</pubDate>
      <link>https://dev.to/charles1303/a-use-case-implementation-for-external-api-integration-eoj</link>
      <guid>https://dev.to/charles1303/a-use-case-implementation-for-external-api-integration-eoj</guid>
      <description>

&lt;h4&gt;
  
  
  Introduction
&lt;/h4&gt;

&lt;p&gt;Phew finally! This will be my first post on this community and I hope to get better using them markdowns as I post more articles here. So here it goes...&lt;/p&gt;

&lt;p&gt;I did a simple task of integrating with the &lt;a href="https://lookup.binlist.net"&gt;Bin List API&lt;/a&gt; and returning an expected client response different from the response gotten from the Bin List API. I will like to point out some of the basics in designing and building a system for such a task. &lt;br&gt;
 The BinList API is a public API that is used to fetch payment card details. It can be accessed via here &lt;a href="https://lookup.binlist.net"&gt;Bin List API&lt;/a&gt;. It exposes an endpoint where you provide the first eight (8) digits of the card number and it returns the card details. For example below is a request and corresponding response made to the API:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="err"&gt;GET&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;https&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="err"&gt;//lookup.binlist.net/&lt;/span&gt;&lt;span class="mi"&gt;45717260&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"number"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"length"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"luhn"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"scheme"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"visa"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"debit"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"brand"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"Visa/Dankort"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"prepaid"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"country"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"numeric"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"208"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"alpha2"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"DK"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"Denmark"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"emoji"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"🇩🇰"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"currency"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"DKK"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"latitude"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;56&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"longitude"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"bank"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"Djurslands Bank"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="s2"&gt;"url"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"www.djurslandsbank.dk"&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;I won't be doing much of code screen shots but you can access every class and method names and signatures highlighted boldly in &lt;a href="https://github.com/charles1303/binlistImpl"&gt;my github repo&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I will place emphasis on the following areas for sake of time and space. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Design pattern implementations (DTO, Service Facade, Repository, Cacheless Cow)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Performance(Caching)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Testing(Unit and Integration)&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  Tools/Platform used
&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Spring Boot 2.1.2 RELEASE&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Maven 3.5.3&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Java 8 &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Mysql 5.7.25&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Ubuntu 16.04&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  Design Pattern Implementation
&lt;/h4&gt;

&lt;p&gt;Because I was doing an integration which required data transfer and operations, these design patterns stood out immediately as to the strategies to be employed&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Data Transfer Object (DTO) pattern&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Service Facade pattern&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Repository pattern&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Cacheless Cow anti pattern&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The &lt;strong&gt;Data Transfer Object(DTO) pattern&lt;/strong&gt; is used when you want to transfer data across services or domains in a well structured format. It also allows for data structure transformation between domains. It's expected that the DTOs should be serializable. So while the &lt;strong&gt;BinListResponse class&lt;/strong&gt; encapsulated the data retrieved from the BinList API (whose url I have configured in the &lt;strong&gt;application.yml&lt;/strong&gt;), the &lt;strong&gt;CardDetailDto class&lt;/strong&gt; contained the transformed data format that will be understood by the client. The transformation is done in the &lt;strong&gt;convertToCardDetailDto(BinListResponse binListResponse) method&lt;/strong&gt; of the &lt;strong&gt;CardDetailService class&lt;/strong&gt;. An advantage of this approach is that either the BinList API response or the client's expectation can be changed internally without affecting either. Also this will prevent breakage of the BinList API interface should the data format decide to change. This approach also makes use of Encapsulation in Object Oriented Programming (OOP) paradigm. All DTOs employed in the application can be located in the &lt;strong&gt;com.projects.binlist.dto.responses package&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Service Facade or simply Facade&lt;/strong&gt; is a strategy allows you to encapsulate and hide the complexities of carrying out an operation thereby exposing a simple interface to the client or caller of the method. This interface with this characteristics is sometimes referred to as being coarse. For example the &lt;strong&gt;getCardRequestLogsCountGroupedByCard(Pageable pageable)&lt;/strong&gt; in the &lt;strong&gt;CardDetailService class&lt;/strong&gt; does a bunch of things before returning the data to the client, i.e check the cache store, call the repository and transform the data retrieved to suit the client's expectation. The advantage of this is that it exposes a neat and simple interface and encapsulates related and seemingly linked operations that depend on one another as a single unit of operation thereby maintaining the integrity of the system's operation and output to the client. The client also has an advantage in that these operations are clearly transparent and they do not need to know the implementation of retrieving the data. (I like to keep my controllers thin and simple).&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Repository pattern&lt;/strong&gt; as we all know allows for easy interchange of the &lt;strong&gt;Data Access Layer&lt;/strong&gt; implementation. It's usually made up of interfaces implemented by the &lt;strong&gt;Data Access Object (DAO)&lt;/strong&gt; (&lt;em&gt;DAO which is another design pattern&lt;/em&gt;) classes. Spring provides different Repository interfaces which can be extended and implemented depending on our data storage engine (&lt;strong&gt;Mysql&lt;/strong&gt;, &lt;strong&gt;MongoDB&lt;/strong&gt; etc). As you can see, my repository domain is just a bunch of generics interfaces with the entity it's acting on as the type parameter as seen in the &lt;strong&gt;CardDetailRequestLogRepository class&lt;/strong&gt;. The Repository pattern allows for loose coupling and easy testing as we will see in a bit. Also I have the advantage of writing customized queries and I can easily change them depending on either the data storage engine or the ORM implementation being used.&lt;/p&gt;

&lt;p&gt;I will be talking about the &lt;strong&gt;Cacheless Cow anti pattern&lt;/strong&gt; in the next section.&lt;/p&gt;

&lt;h4&gt;
  
  
  Performance(Caching)
&lt;/h4&gt;

&lt;p&gt;Remember when I said in the last section concerning the Service Facade about how it exposes a simple interface to call by encapsulating a bunch of operations as a single unit of operation to produce the expected data output? Well this comes at a cost in terms of time it will take to produce that output for every call. However we can eliminate this cost by storing the data output and retrieving it whenever we need that output without going through the steps of reprocessing it provided we have some sort of identifier or key that we can do a lookup for that maps to that particular data we want to retrieve. This is similar to &lt;strong&gt;Dynamic Programming&lt;/strong&gt; when we implement &lt;strong&gt;Recursion Algorithm&lt;/strong&gt; by storing a previously computed value with a key in a data structure (&lt;strong&gt;Array or Map&lt;/strong&gt;) and retrieving it without having to make a recursive call for that value so as to reduce time complexities.&lt;/p&gt;

&lt;p&gt;In our application, we used a cache implementation to store that value so we don't have to make expensive database calls and data transformations for every service call. Caching in this context simply means &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Get me that data as is if you have it without reprocessing or recomputing it&lt;/em&gt;. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is how we handle what we normally term the &lt;strong&gt;Cacheless Cow anti pattern&lt;/strong&gt; I referred to earlier.&lt;/p&gt;

&lt;p&gt;To implement this in our code, we configure a Spring Cache manager bean in one of our configuration classes, the &lt;strong&gt;CacheConfig class&lt;/strong&gt; using the &lt;strong&gt;ConcurrentMapCacheManager&lt;/strong&gt; implementation (we could have also easily used the &lt;strong&gt;EhCache&lt;/strong&gt; implementation as well). Then we annotate the service method &lt;strong&gt;getCardRequestLogsCountGroupedByCard(Pageable pageable)&lt;/strong&gt; in our &lt;strong&gt;CardDetailService class&lt;/strong&gt; with &lt;strong&gt;@Cacheable&lt;/strong&gt; providing the necessary values (the value represents the cache name in our configuration file  while the key is the key naming strategy we are using). Here in the key naming strategy, we concatenate the method name with the &lt;em&gt;pageNumber&lt;/em&gt; attribute value of the &lt;em&gt;Pageable&lt;/em&gt; parameter we are sending to generate a key and store the returned data with that key. So the first request will go through the processing steps to retrieve the data and then store it in the cache using the generated key. This took about &lt;strong&gt;276ms&lt;/strong&gt; for a 20 record table. Subsequent requests will ignore the processing steps and just fetch the stored data from the cache taking about &lt;strong&gt;5-10ms&lt;/strong&gt; (&lt;em&gt;Wow!&lt;/em&gt;). The reprocessing of the data will occur only when you send a different &lt;em&gt;pageNumber&lt;/em&gt; attribute value of the &lt;em&gt;Pageable&lt;/em&gt; parameter that was not previously sent. A warning here however is to find a way to clear the data from the cache if the data from the backend has changed to prevent stale data being returned. Hence when the logs are updated in the database in the &lt;strong&gt;logCardDetailRequest(String iinStart) method&lt;/strong&gt;, the &lt;strong&gt;@CacheEvict&lt;/strong&gt; annotation on it clears the cache so it will force the method call to &lt;strong&gt;getCardRequestLogsCountGroupedByCard(Pageable pageable)&lt;/strong&gt; to actually fetch the data from the database as it will no longer be in the cache. I will show you in a bit how we can verify this in our test class.&lt;/p&gt;

&lt;h4&gt;
  
  
  Testing
&lt;/h4&gt;

&lt;p&gt;Writing tests can never be over emphasized during application development. Writing tests against your functionalities guarantees integrity and raises red flags if any new code change breaks your application. Before I continue, I would like to ask a rhetorical question here:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Why do you write tests or why are you writing that test?&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For those of us who thought &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;I want to verify that my functionalities or endpoints works properly.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;, chances are that you may be inclined to write your tests around what we refer to as &lt;strong&gt;Integration (or Functional) tests&lt;/strong&gt;. For others who thought &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;I want to verify that my method works properly.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;,chances are that you will end up writing &lt;strong&gt;Unit tests&lt;/strong&gt;. There is nothing wrong in having both tests in your test suite but you need to consider the following when you decide which one to implement or even implement both.&lt;/p&gt;

&lt;p&gt;Integration tests are normally environment dependent such that one that was written and passed successfully on your local machine might fail on another machine due to different data states in the different database instances or unavailability of a resource dependency due to network failure. Such a scenario can be seen when you try to run the &lt;strong&gt;CardDetailControllerITTest&lt;/strong&gt; or the &lt;strong&gt;CardDetailControllerTest&lt;/strong&gt; classes. These test classes expect the following in any environment it's running to be true&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;That the Bin List API is accessible&lt;/li&gt;
&lt;li&gt;That the database is available and accessible&lt;/li&gt;
&lt;li&gt;That the datasets in the databases of any of the environment must be the same.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Despite these constraints, a clear advantage of integration test is that you get to actually see how your dependencies behave in a real deployed scenario in the production environment. For example, the &lt;strong&gt;CacheIntegrationTest&lt;/strong&gt; test class asserts that the responses gotten in both service calls are the same (i.e the cached response created in the first call is returned in the second call). It also verifies that the repository layer was only accessed once after both calls indicating that the second call didn't go to the database but retrieved the object from cache.&lt;/p&gt;

&lt;p&gt;On the other hand, Unit tests are independent of the data states of the environment and will yield the same results regardless of the environment it's being run in. The reason for this is that the dependencies, resources, outputs and data are mocked, hence are not required to be available or accessible. Only pure logic and component method behaviours are tested here. For example, in the &lt;strong&gt;CardDetailServiceTest&lt;/strong&gt; class, the &lt;em&gt;RestTemplate&lt;/em&gt; dependency which is used to access the Bin List API is mocked along with the response. (This is like using the &lt;em&gt;Guzzle MockHandler&lt;/em&gt; in the &lt;em&gt;PHP&lt;/em&gt; or &lt;em&gt;nock&lt;/em&gt; in the &lt;em&gt;Node&lt;/em&gt; worlds). Also you will observe that &lt;strong&gt;logCardDetailRequest(String iinStart)&lt;/strong&gt; method behaviour of the &lt;strong&gt;CardDetailService&lt;/strong&gt; class is equally mocked by instructing it to do nothing as this interacts with the database (Thanks to the @Spy annotation). In the end, all we are testing is our DTO pattern implementation (i.e &lt;strong&gt;convertToCardDetailDto(BinListResponse binListResponse)&lt;/strong&gt; method), to ensure the mocked &lt;strong&gt;BinListResponse&lt;/strong&gt; object state that will be gotten from the Bin List API is transformed to the appropriate mocked &lt;strong&gt;CardDetailDto&lt;/strong&gt; object state and returned to the client or method caller.&lt;/p&gt;

&lt;p&gt;Can you guess the downside of this approach of testing? Yeah that's right, it doesn't simulate the true behaviours of your dependencies when they are deployed in production environment. Choosing which tests(unit or integration) to implement in your code is a function of the coding review requirements, use case or business requirements and the strategy employed in the deployment pipeline.&lt;/p&gt;

&lt;p&gt;I have left out other features such as &lt;strong&gt;Security, Exception handling and Logging&lt;/strong&gt; in this task as they were not necessarily a fundamental requirement. I hope I can get to share my insights on this as well sometime soon. This approach outlined in executing this task is by no means cast in stone as I welcome comments and other better ways or approaches in implementing such a task. Please feel free to pull the project &lt;a href="https://github.com/charles1303/binlistImpl"&gt;here&lt;/a&gt; and review. Afterall this is a community, Ain't That Right or should I say Ain't It? :) . Happy coding!&lt;/p&gt;


</description>
      <category>performance</category>
      <category>testing</category>
      <category>designpatterns</category>
      <category>apiintegration</category>
    </item>
  </channel>
</rss>
