Thursday, May 24, 2018

How to install & configure the AWS CLI on Windows system

One can easily use AWS Management Console to manage their AWS services but if one wants to access & manage their AWS services programmatically then one could install & configure AWS CLI. Today we would be discussing, how to install & configure AWS CLI in Windows systems.
Table Of Content:
1. Introductions
2. Installing the AWS CLI
3. Configuring the AWS CLI
4. Conclusion

Wednesday, May 23, 2018

JBoss Deployment Error: java.lang.LinkageError: loader constraint violation

Getting deployment errors are inevitable. One can't escape from it. Recently I have got a deployment error i.e. java.lang.LinkageError: loader constraint violation while deploying my Maven based application in JBoss. Good news is, I have solved this issue. Along with the root cause of the issue and it's solutions, today we would also discuss the approach that I have used to solve this issue because using similar approach one could troubleshoot many other similar issues.

Let me share the technology stack and deployment logs first before getting in much details. Also one information, I haven't got any Maven error while building the application.

1. Technology Stack


- JDK 7
- Apache Maven 3.5.2
- JBoss-6.1.0.Final

2. Deployment Logs

16:06:22,202 INFO  [TomcatDeployment] deploy, ctxPath=/QuartzScheduler
16:06:22,249 INFO  [[/QuartzScheduler]] QuartzInitializer: Quartz Initializer Servlet loaded, initializing Scheduler...
16:06:22,249 ERROR [[/QuartzScheduler]] StandardWrapper.Throwable: java.lang.LinkageError: loader constraint violation: when resolving method "org.slf4j.impl.StaticLoggerBinder.getLoggerFactory(
)Lorg/slf4j/ILoggerFactory;" the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) of the current class, org/slf4j/LoggerFactory, and the class loader (instance of org/jboss/cl
assloader/spi/base/BaseClassLoader) for resolved class, org/slf4j/impl/StaticLoggerBinder, have different Class objects for the type taticLoggerBinder.getLoggerFactory()Lorg/slf4j/ILoggerFactory; used
 in the signature
        at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:299) [:1.6.6]
        at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:269) [:1.6.6]
        at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:281) [:1.6.6]
        at org.quartz.impl.StdSchedulerFactory.(StdSchedulerFactory.java:303) [:]
        at org.quartz.ee.servlet.QuartzInitializerServlet.getSchedulerFactory(QuartzInitializerServlet.java:251) [:]
        at org.quartz.ee.servlet.QuartzInitializerServlet.init(QuartzInitializerServlet.java:183) [:]
        at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1208) [:6.1.0.Final]
        at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1108) [:6.1.0.Final]
        at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3628) [:6.1.0.Final]
        at org.apache.catalina.core.StandardContext.start(StandardContext.java:3851) [:6.1.0.Final]
        at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:294) [:6.1.0.Final]
        at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:146) [:6.1.0.Final]
        at org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:476) [:6.1.0.Final]
        at org.jboss.web.deployers.WebModule.startModule(WebModule.java:118) [:6.1.0.Final]
        at org.jboss.web.deployers.WebModule.start(WebModule.java:95) [:6.1.0.Final]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [:1.7.0]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [:1.7.0]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [:1.7.0]
        at java.lang.reflect.Method.invoke(Method.java:601) [:1.7.0]
        at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157) [:6.0.0.GA]
        at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96) [:6.0.0.GA]
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:88) [:6.0.0.GA]
        at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:271) [:6.0.0.GA]
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:670) [:6.0.0.GA]
        at org.jboss.system.microcontainer.ServiceProxy.invoke(ServiceProxy.java:206) [:2.2.0.SP2]
        at $Proxy41.start(Unknown Source)  

3. Analyzing the Logs


Logs are true saviour for any developer. If one could analyze the logs properly more then more than half of the job is already done. See the highlighted part of the above logs, we have got some useful information about the error:
- the error was due to method resolution as the class loader of the current class and the class loader for the resolved class have different class objects.
- also the error was related to slf4j jar

But wait, have I used slf4j related jar as my dependency in POM.xml? 
The answer would No. Although I have used log4j as my direct dependency in POM.xml but I haven't used slf4j related any jar as my direct dependency in POM.xml.

Then again two questions arises if we though about the cause of the error,
Q1: My application must be getting slf4j related jar as indirect dependency from somewhere which is conflicting with JBoss libraries at run time. Is it so or not?
Q2: Is it because of two libraries i.e. log4j & slf4j, JBoss is throwing Linkage error at run time? 

Therefore if we have to find the exact jar from the application which has slf4j related jar as its indirect dependency and exclude it from that jar then problem should get solved. Let's try out this.

4. Solution

  • Find out the dependency tree of the application
    One could use mvn dependency:tree command to get the dependency tree of any Maven projects. Let's run it and see the output. See, quartz related jar has slf4j-api jar as it's indirect dependency.
    mvn dependency:tree
    
    Output:
    
    ------------------------------------------------------------------------
    Building QuartzScheduler_Maven 1.0-SNAPSHOT
    ------------------------------------------------------------------------
    [dependency:tree]
    com.anshulsblog:QuartzScheduler_Maven:war:1.0-SNAPSHOT
    +- javax.transaction:javax.transaction-api:jar:1.2:provided
    +- org.quartz-scheduler:quartz:jar:2.2.1:compile
    |  +- c3p0:c3p0:jar:0.9.1.1:compile
    |  \- org.slf4j:slf4j-api:jar:1.6.6:compile
    +- log4j:log4j:jar:1.2.17:compile
    \- junit:junit:jar:4.10:test
       \- org.hamcrest:hamcrest-core:jar:1.1:test
    ------------------------------------------------------------------------
    BUILD SUCCESS
    ------------------------------------------------------------------------
    Total time: 2.181 s
    Finished at: 2018-05-22T16:41:58+05:30
    Final Memory: 9M/22M
    ------------------------------------------------------------------------
  • Dependency Exclusion in Maven
    Let's exclude slf4j-api jar from quartz then again build & deploy the application and see whether it solves the issue.
    <dependency>
     <groupId>org.quartz-scheduler</groupId>
     <artifactId>quartz</artifactId>
     <version>2.2.1</version>
            <exclusions>
      <exclusion>
         <groupId>org.slf4j</groupId>
                       <artifactId>slf4j-api</artifactId>
                    </exclusion> 
            </exclusions>
    </dependency>
    
    Built and deployed the application again, it worked and now the deployment logs are clean. 

5. Conclusion


Even though, if one doesn't get any kind of Maven errors while building the application, it doesn't imply that the application would be successfully deployed always. One could get many deployment errors either due to multiple versions of the same jars(direct & indirect dependencies) or due to multiple jars conflict or due to jar conflict between the container's jar and compile time provided jar. In all such instances, it's better to go through the dependency tree of the project (use  mvn dependency:tree command) and if any conflicts found then exclude it. Happy Learning!!



Tuesday, May 15, 2018

How to check embedded Tomcat server properties in spring boot?

Hello Friends!! Today we would be discussing how to check the embedded Tomcat server properties in Spring Boot. You must be thinking why would we ever want to check the Tomcat properties because we are the one who has set these properties  using Spring Boot's configuration file i. e.  application.yml / application.properties. But let me first tell you the reason behind it, why I have travelled this extra mile and then we would see how to check the properties?

Q1. Why are we even interested in checking the Spring Boot's embedded Tomcat server properties ?


Recently, I have came across the requirement for setting up the maxSwallowSize property in the embedded Tomcat server of my Spring Boot application which I did it successfully by using Java configuration because as of now while writing this post, this property can't be configured using Spring Boot's configuration file i. e.  application.yml / application.properties.

For configuring maxSwallowSize property,  I have used TomcatConnectorCustomizer interface and then associated it with the TomcatEmbeddedServletContainerFactory class that means manually registered TomcatEmbeddedServletContainerFactory bean in the main Spring Boot class. For more details on this, have a look at this write-up.

Now one question crossed our mind,
Does the manually configured Tomcat server honours the bootstrap. yml file containing some of the configured Tomcat server properties if not then do we have to set all the required properties like maxSwallowSize ?
Logically it should but we can't leave it as granted, we must be sure. That's why we find ourselves in first place to look out a way to check embedded Tomcat server properties.

For reference, bootstrap. yml file,
spring:
  application:
    name: anshuls-blog
      
# EMBEDDED SERVER CONFIGURATION  
server:
  port: 8081
  tomcat:
    max-threads: 1000 # Maximum number of worker threads
    min-spare-threads: 40 # Minimum number of worker threads
    uri-encoding: UTF-8 # Character encoding to use to decode the URI

2. How to check  embedded Tomcat server properties in spring boot?


There are two ways for finding out the configured server properties of a embedded Tomcat server. Both involves, getting the required bean from application context and look out for the desired properties in debug mode.

2.1 Get TomcatEmbeddedServletContainerFactory  bean from Application Context 

Look out the properties inside the TomcatConnectorCustomizer.


2.2 Get ServerProperties bean from Application Context 

ServerProperties.java class contains all the supported embedded servers in Spring Boot as the static inner class i.e. Tomcat, Jetty, Undertow [1]. That's why inspecting it in debug mode shows the Tomcat properties.

For reference, code snippet 
public void getEmbeddedTomcatInfoInSpringBoot() {
  
 TomcatEmbeddedServletContainerFactory tomcatServletContainerFactory = context.getBean(TomcatEmbeddedServletContainerFactory.class);
 Collection<TomcatConnectorCustomizer> tomcatConnectorCustomizers = tomcatServletContainerFactory.getTomcatConnectorCustomizers();
  
 logger.info("URU Encoding:>>>>>>>>>" + tomcatServletContainerFactory.getUriEncoding());
 logger.info("Port:>>>>>>>>>" + tomcatServletContainerFactory.getPort());
  
 ServerProperties serverProperties = context.getBean(ServerProperties.class);
  
 logger.info("MaxThreads Property:>>>>>>>>>" + serverProperties.getTomcat().getMaxThreads());
 logger.info("MinSpareThreads Property:>>>" + serverProperties.getTomcat().getMinSpareThreads());
 logger.info("MinSpareThreads Property:>>>>>" + serverProperties.getTomcat().getUriEncoding());
   
}
Thank you for your time and see you in the next post. Happy Learning!!

Appendix:
[1]: ServerProperties.java

Thursday, May 10, 2018

Thymeleaf: jQuery/JavaScript function call with or without parameters (Examples)

While developing our web application, it's very common use case to execute JavaScript functions on an account of any event like onblur, onchange, onclick, onkeydown, onmouseover etc [1]. These calls may be with or without parameters depending upon the business requirement.
             Today, we would see some examples to understand how to properly call JavaScript functions from Thymeleaf. But before that, we would also see used tech stack, Thymeleaf dependencies in the POM file and how we have added page fragments containing our CSS &  JS files in the target HTML page where we would be making the JavaScript function calls.



1. Tech Stack:


- Spring Boot 1.5.10.RELEASE
- Maven 3.3.9
- Thymeleaf 3.0.3.RELEASE

2. Thymeleaf Dependencies in Maven POM file

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
 <groupId>org.thymeleaf</groupId>
 <artifactId>thymeleaf</artifactId>
 <version>3.0.3.RELEASE</version>
</dependency>
<dependency>
 <groupId>org.thymeleaf</groupId>
 <artifactId>thymeleaf-spring4</artifactId>
 <version>3.0.3.RELEASE</version>
</dependency>
<dependency>
 <groupId>nz.net.ultraq.thymeleaf</groupId>
 <artifactId>thymeleaf-layout-dialect</artifactId>
 <version>2.1.2</version>
</dependency>

3. Add external JavaScript file to the HTML page


For cleanliness and better maintainability, I have kept almost all of my JavaScript functions in a separate JS file which is located at <project_name>/src/main/resources/public/js/main.js and then added the fragment containing CSS & JS in HTML file using th:replace attribute.

3.1 The Fragment 

## <project_name>/src/main/resources/templates/fragments/header.html
<head th:fragment="cssandjs">
 <title>Anshul's Blog</title>
 <link rel="stylesheet" type="text/css" th:href="@{/css/screen.css}"/>
 
 <script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
 <script type="text/javascript" th:src="@{/js/main.js}" src="/js/main.js"></script>
</head>

3.2 The Target HTML page 


This is the file where we have added the cssandjs fragment using th:replace attribute and will be making JavaScript calls using Thymeleaf. For more details on th:replace attribute, have a look at this write-up.
## <project_name>/src/main/resources/templates/target.html
<head th:replace="fragments/header :: cssandjs">

4. jQuery / JavaScript Function Calls


Apart from function calls, we would also see situations where we may avoid writing JavaScript functions. One might confuse while making function calls as when to directly use events like onclick, onchange etc or use Thymeleaf's attributes like  th:onclick or th:onchange etc. Therefore, just follow the golden rule i.e. use Thymeleaf's attributes only when, we need to pass some dynamic values in the functions otherwise stick with normal HTML event attributes. Now we ready to fly, everything is in place.

4.1 Function call without parameter

<button onclick="addItemToKart()">Add Item</button>
<div class="close"><span id="x" onclick="closeItemDetailsInModelWindow()">&#9747;</span></div>
<select th:name="${#strings.listSplit(stream.key,',')[1]}" 
  th:onchange="${#strings.listSplit(stream.key,',')[1] == 'Science'} ? 'populateScienceOrCommerceDropdown()' : ''">

4.2  Function call with parameters

## ${item.id} is of type Integer
<input type="button" value="Select" th:onclick="|showItemDetailsInModelWindow(${item.id})|"/>

## ${author.id} is of type Integer & ${author.name} is of type String
<input type="button" value="Show books by author" th:onclick="|showBooksByAuthor(${author.id}, '${author.name}')|"/>

## ${titleModel.isbn} is of type String & ${book.bookId} is of type Integer
<a th:onclick="|bookDetails('${titleModel.isbn}',${book.bookId})|" style="cursor: pointer;">Book Details</a> 

4.3 Avoid writing JavaScript functions


In some situations, one could avoid writing JavaScript functions like when one have to simply call a particular controller's method or when one have to show the popup box [Alert box, Confirm box, and Prompt box] etc.
<button th:onclick="'javascript: document.location=\'/chapterdetails?isbn=' + ${bookModel.isbn} + '&amp;page=1\''"></button>  
<input type="submit" value="Approve" onclick="return ( prompt('You must type APPROVED to continue') == 'APPROVED' )" /> 

5. Conclusion 


Now we know how to make JavaScript function calls in Thymeleaf. We have also seen how to keep function calls in a separate file for better maintainability and then use th:replace attribute to add the fragments containing these CSS & JS files. Happy Learning!!

Appendix:
[1] : Some examples of event attribute and their corresponding event actions:
  • onclick Event:
    onclick of a button, invoke a controller method with or without parameter
    - onclick of a button, open a model window to either show some information to user or to take user's input
  • onchange Event:
    dynamically showing different select box on selecting different values from a select box 

Friday, May 4, 2018

Spring Boot: 'Why' & 'How to' Configure maxSwallowSize property for embedded Tomcat

Hello Friends! Today we would be discussing why in first place, anyone needs to configure maxSwallowSize property and what are the steps that needs to be followed in order to configure this property. Can this property be directly configured by Spring Boot's application.yml / application.properties file or any Java configuration is required for this?



Table Of Content
1. Introduction
2. Why configure maxSwallowSize property
3. How to configure maxSwallowSize property
4. Conclusion

Thursday, May 3, 2018

Difference between Thymeleaf attribute th:replace, th:insert and th:include

Similar to JSP includes, Thymeleaf offers page fragment inclusion but with some important improvements. One could include parts of other pages as fragments (whereas JSP only includes complete pages ) using th:replace or th:insert or th:include. Although the job of all these three attributes are same but how they actually include parts of pages as fragment in the target page is little bit different. It's very important to understand the back-end processing of this attribute otherwise one would get surprising results. That's why, today we would be discussing difference between these attributes.


Functionality


Before describing the attributes functionalities, be familiar with term like:
Host Tag:  tag containing th:replace, th:insert or th:include attribute [would be present in the target page where one would like to add the fragment]
Fragment Tag: tag containing th:fragment attribute [would be present in any page depending upon the design of the page but generally one would store their fragments in modular fashion like header.html or fragments.html]

th:replace - It will actually substitute the host tag by the fragment’s. That means, It will remove the host tag and in place of host tag, it will add the specified fragment including the fragment tag.

th:insert - It will simply insert the specified fragment as the body of its host tag including the fragment tag.

th:include - It will also insert the specified fragment as the body of its host tag but excluding the fragment tag.

Implementation


We have already provided the functionality overview of each of the attributes but it would be more clear after going through this example. We would be adding the the fragment and see the HTML output that's generated by each of the attribute.

Step 1: Add the fragment in the target page
<div id="tagWithReplaceAttribute" th:replace="fragments/header :: targetFragmentToIncludeInOurPage"></div>
<div id="tagWithInsertAttribute" th:insert="fragments/header :: targetFragmentToIncludeInOurPage"></div>
<div id="tagWithIncludeAttribute" th:include="fragments/header :: targetFragmentToIncludeInOurPage"></div>
where,
fragments/header = a template name that one are referencing to. This can be a file or it can reference to the same file either by using the this keyword (e.g. this :: header) or without any keyword (e.g. :: header).
targetFragmentToIncludeInOurPage = expression after double colon is a fragment selector (either fragment name or Markup Selector)

Step 2: Create the fragment to add

Adding it to [/<project_name>/src/main/resources/templates/fragments/header.html]
<div th:fragment="targetFragmentToIncludeInOurPage" id="tagWithFragmentAttribute">
 <div id="contentGoesHere"></div>
</div>
Step 3: The Output
<div id="tagWithFragmentAttribute">
 <div id="contentGoesHere"></div>
</div>

<div id="tagWithInsertAttribute">
 <div id="tagWithFragmentAttribute">
  <div id="contentGoesHere"></div>
 </div>
</div>

<div id="tagWithIncludeAttribute">
 <div id="contentGoesHere"></div>
</div>
Look at the output, now we know which attribute generates which kind of HTML code after processing. Therefore don't confuse with these attributes and use attributes judiciously depending upon the requirements. Happy Learning!!