Thursday, 25 February 2016

Best Practices for Writing Spring Configuration Files


Spring is a powerful Java application framework, used in a wide range of configuration options. Its best feature if that it provides enterprise services to Plain Old Java Objects (POJOs) called beans. Spring uses dependency injection (DI) to achieve simplification and increased testability. Spring beans, dependencies, and the services needed by beans are specified in xml configuration files or annotations. The XML configuration files, however, are verbose and more clean. If not planned and written correctly, it becomes very hard to manage in big projects.
In this article, I will show you 10 best practices for writing spring XML configurations. Some of them may seem more necessary practices rather than best practices, yet I have included them in here because they were highly related to the topic.

1) Add a header comment to each configuration file
2) Use consistent naming conventions
3) No version numbers in schema references
4) Prefer setter injection over constructor injection
5) Prefer type over index for constructor argument matching
6) Use shortcut forms over expanded forms
7) Reuse bean definitions as much as possible
8) Always use ids as bean identifiers
9) Try to avoid autowiring
10) Always use classpath prefix
11) Always externalize properties
12) Use dependency-check at the development phase
13) Do not abuse/overuse dependency injection
 

1) Add a header comment to each configuration file

I always put more stress on code comments. The same goes for configuration files also. It is always very helpful to add a configuration file header, which summarizes the beans/properties defined in the configuration files.
In spring configuration, you can add comments as adding xml comments or you can use the description element. For example:
<beans>
    <description>
        This configuration file will have all beans
        which may be used for controlling transactions.
    </description>
    ...
</beans>
One possible advantage of using the description tag is that some tools may pick up the description from this element to help you in other places.

2) Use consistent naming conventions

This is very important thing that you use same naming across all configuration files. Using clear, descriptive, and consistent name conventions across the project increase the readability of configuration files and make it easy for other developers to avoid some accidental bugs.
For bean ID, for example, you can follow the Java class field name convention. The bean ID for an instance of EmployeeUpdateDAO would be employeeUpdateDAO. For large projects, you can add the package name as the prefix of the bean ID. e.g. finance.employeeUpdateDAO.

3) No version numbers in schema references

I have also pointed out this feature earlier in previous post. I am again including it because it is essential and beneficial in long term specially to reduce maintainbility. To refresh your memory, specifying version number in bean configuration files for referenced schemas are not mandatory at all, and you can omit it. If fact, you should omit it all the time.
Spring automatically picks the highest version available from the project dependencies (jars). Also, as the project evolves and the Spring version will be updated, we won’t have to maintain all the XML config files to see the new features.
A sample example will be like this:

4) Prefer setter injection over constructor injection

Spring provides three types of dependency injection: constructor injection, setter injection, and method injection. Usually, we all use first two types only.
<!-- Constructor injection -->
<bean id="employeeDAO"   class="com.howtodoinjava.dao.EmployeeDAO">
    <constructor-arg ref="datasource"/>
</bean>
<!-- Setter injection -->
<bean id="employeeDAO" class="com.howtodoinjava.dao.EmployeeDAO">
    <property name="datasource"  ref="datasource">
</bean>
Constructor injection can provide the cheapest thread safety possible i.e. immutable object. Also it guarantees that object will not be handed over to other beans without complete initialization.
Setter injection provides much desired capability i.e. flexibility or maintainability. If there are multiple attributes to set in a bean, then creating a long list of parameters to constructor is not good idea. Also, if is possible that some of the attributes might be optional.
Prefer flexibility. For immutability or thread safety, follow other programming rules.


5) Prefer type over index for constructor argument matching in Constructor injection

Better to avoid constructor injection and prefer to use setter injection for dependency injection. But, if you have an absolute requirement to use constructor injection then always prefer parameter matching based on type rather than index.
<!-- Index based constructor injection -->
<bean id="employeeDAO" class="com.howtodoinjava.EmployeeDAO">
    <constructor-arg index="0" value="rest"/>
    <constructor-arg index="1" value="8080"/>
</bean>
<!-- Type based constructor injection -->
<bean id="employeeDAO" class="com.howtodoinjava.EmployeeDAO">
    <constructor-arg type="java.lang.String" value="rest"/>
    <constructor-arg type="int" value="8080"/>
</bean>
As you can see that type based argument passing is more readable and less error prone. But, anytime there is any ambiguity in type based argument passing, go to index based argument passing without hesitation.

6) Use shortcut forms over expanded forms

Spring bean configuration semantics allow two forms for specifying property values and other bean references. One is expanded and other is shorter form. Prefer shorter version.
<!-- Expanded version -->
<bean id="employeeDAO" class="com.howtodoinjava.dao.EmployeeDAO">
    <property name="datasource">
        <ref bean="datasource"></ref>
        <value>datasource</value>
     </property>
</bean>
<!-- Shorter/shortcut version -->
<bean id="employeeDAO" class="com.howtodoinjava.dao.EmployeeDAO">
    <property name="datasource"  ref="datasource" value="datasource">
</bean>

7) Reuse bean definitions as much as possible

Spring provides a very useful capability which you should use extensively in your project and i.e. bean definition re-usability. Here I am not talking about bean references for setter injection. Rather I am pointing out the bean definition re-use in constructing other beans.
Take an example of datasource definition:
<bean id="abstractDataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close"
    p:driverClassName="${jdbc.driverClassName}"
    p:username="${jdbc.username}"
    p:password="${jdbc.password}" />
<bean id="concreteDataSourceOne"
    parent="abstractDataSource"
    p:url="${jdbc.databaseurlOne}"/>
  
<bean id="concreteDataSourceTwo"
    parent="abstractDataSource"
    p:url="${jdbc.databaseurlTwo}"/>

8) Always use ids as bean identifiers

Spring allows two types of identifiers for a bean. Using attribute “id” or by “name”. You should always choose attribute id over name. Usually it does neither increase readability nor benefit any performance scenario. It is just industry standard practice which all fellow developers are following worldwide and even in your team.
Just don’t be odd man out here.

9) Try to avoid autowiring

Autowiring is a great feature if you can manage it in long term. Usually it is beneficial if you project is having very few beans and you can almost remember them all in your memory as well.
As soon as project gets bigger, autowiring starts creating trouble in identifying correct dependency to use. The main drawback, I find is not to have a overview of whole system binded together. This is where spring configuration files win. They can represent the whole system to any new guy in couple of minutes.
Also, when you start debugging some complex issues then all information present in one place in configuration files, actually helps a lot. Autowiring makes debugging harder.


10) Always use classpath prefix

When importing resources, XML config, properties, etc. Always use the classpath: or classpath*: prefix. This provides consistency and clarity to the location of the resource. Not every feature of Spring behaves the same, classpath: guarantees consistency.
The classpath is determined by the build tool and IDE. Usually this is src/main/java for java code, src/main/resources for non-java dependencies and for tests, src/test/java for java code and src/test/resources for non-java resources.
<!-- Always use classpath: prefix-->
<import resource="classpath:/META-INF/spring/applicationContext-security.xml"/>

11) Always externalize properties

Often there are multiple configuration parameters related to runtime of application. They are passed to bean definitions in bean configuration context file. DO not hard code them in config file. Instead externalize them to some properties file(s).
Better group them in separate files based on their usage or module i.e. all JDBC datasource related properties in jdbc.properties file.
<bean id="abstractDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close"
        p:driverClassName="${jdbc.driverClassName}"
        p:username="${jdbc.username}"
        p:password="${jdbc.password}" />
and properties file
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=password

12) Use dependency-check at the development phase

You should mostly set the dependency-check attribute on a bean definition to simple, objects, or all (default value is none i.e. no checking), so that the container can do explicit dependency validation for you. It is useful when all of the properties (or certain categories of properties) of a bean must be set explicitly, or via autowiring.
<bean id="abstractDataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close"
    p:driverClassName="${jdbc.driverClassName}"
    p:username="${jdbc.username}"
    p:password="${jdbc.password}"
    dependency-check="all" />
In above given example, the container will ensure that all properties/parameters to datasource are set in application initialization time itself.

13) Do not abuse/overuse dependency injection

Finally, please do not abuse the motive behind introducing dependency injection. Java provide “new” keyword to create new objects. Use this wonderful keyword where DI is not necessary e.g. DTO objects. Don’t try to play smarter. Just follow the basics.
Drop me a comment if you feel otherwise on any of above points.

Java Best Practices

When I'm saying "Practice", what does it mean? I would say:
  • Practice is a habit.
  • Practice is a routine.
  • Practice does not need to remember.
  • Practice comes by practicing.
  • Practice needs dedication and commitment.
    There are thousands of examples which you think about practice. I can list few for your understanding.

    Best Practice 1- Keep Reading Existing Software Source Code

    Let me ask you few basic questions before we start with one of the most important best practices required for a software developer.
  • Do you read movie magazines?
  • Do you read newspapers?
  • Do you read roadside advertisements?
  • Do you read junk written here and there?
  • Do you just read....?
Definitely your answer will be positive but if I ask you one more question in the series:

Do you read Software Source Code?

Only few software developers will have positive answer because reading and understanding an existing software source code is the most boring task. If you are one of them who feels reading software source code is a boring task, then you are missing one of the most important best practices, which a software developer should have in his/her life.
If you want to become a novelist, can you just start writing novels? I would say 100% no!!, you definitely need to read hundreds of novels before you start writing GOOD novels. If you want to become a movie script writer, can you start writing good movie scripts until you have gone through various good movie scripts?, again my answer would be no!!
So, if you want to write a good software code, then how it will be possible for you to write a good source code without reading tons of source codes? Even if you will write something, then how would you and know which the best is?
Reading source code written by others gives you opportunity to criticize the mistakes done in writing that code. You will be able to identify the mistakes other software developers have done in their source code which you should not repeat.
There are many attributes of software codes (indentation, comments, history header, function structure, etc.), which you will learn by reading existing code, specially, a code written by well-experienced software developers. Spend some time in reading others' source code and I'm sure you would be able to write BEAUTIFUL source code in few days or few weeks and you will be able to fix the mistakes, which you were doing so far in writing the source code.
One thing to experiment, just go in the past and check the code you had written few years ago, you will definitely laugh....because you are always improving by doing practice.

Best Practice 2 - Complete your documents before next step

I had passed out my masters in Computer & Application and I was so passionate to write source code even without completely understanding and documenting the requirements. Design document and test cases documentation were nowhere in the software development life cycle ....there was direct jump to the coding.
At later stages I found myself in big trouble and soon I realized Documentation is the Key to become successful software developer, tester or architect.
Computer Documentation Before you start developing small or big software, you should have answer for the following questions:
  • Where is the Requirements Specification?
  • Where is the Impact Analysis Document?
  • Where is the Design Document?
  • Have you documented all the assumptions, limitations properly?
  • Have you done review of all the documents?
  • Did you get sign off on all the documents from all the stakeholders?
Once you have positive answers for all the above questions, you are safe and ready to proceed for the coding. Many organizations would have strict rules to be followed, but others would not have. Best practice is to complete all the required documentation and take appropriate approvals before proceeding for the software coding.

What you learn today, prepares you for tomorrow!

So, again it is one of the best practices to have documentation as much as possible. Few important documents, which will prepare you for future are:
  • Design Approaches
  • Tips and Tricks
  • Special functions, commands and instructions
  • Lessons learnt
  • Peculiar situations
  • Debugging methods
  • Best Practices
  • Anything which can help you in future
Keeping documents electronically does not cost you. So let's start maintaining required documentation.

Best Practice 3 - Follow the defined standards, don't create it

Most of the standard software organizations maintain their coding standards. These standards would have been set up by well-experienced software developers after spending years with software development. This is equivalent to following footsteps of great people left behind them.
Follow the Standards If your organization does not have any standard, then I would suggest to search on internet for coding standards off different programming languages and you will find many. A coding standard would fix the rules about various important attributes of the code, few are listed below:
  • File Naming convention
  • Function & Module Naming convention
  • Variable Naming convention
  • History, Indentation, Comments
  • Readability guidelines
  • List of do's and don'ts
But once defined, start following the defined standard instead of creating or changing them every day. I would definitely say:

Source code is your BABY!

So keep it clean, consistent and beautiful. When I say beautiful, it really means beautiful. If your code looks beautiful, then it would be easy for others to read and understand it. If you will keep changing coding rules everyday, then after few days you, yourself would not be able to read and understand the code written by you.

Best Practice 4 - Code should be written to be reviewed

While writing your software code, keep in mind that someone is going to review your code and you will have to face criticism about one or more of the following points but not limited to:
  • Bad coding
  • Not following standard
  • Not keeping performance in mind
  • History, Indentation, Comments are not appropriate.
  • Readability is poor
  • Open files are not closed
  • Allocated memory has not been released
  • Too many global variables.
  • Too much hard coding.
  • Poor error handling.
  • No modularity.
  • Repeated code.
Keep all the above-mentioned points in your mind while coding and stop them before they jump in your source code. Once you are done with your coding, go for a self-review atleast once. I'm sure, a self-review would help you in removing 90% problems yourself.
Once you are completely done with your coding and self review, request your peer for a code review. I would strongly recommend to accept review comments happily and should be thankful to your code reviewers about the comments. Same time, it is never good to criticize any source code written by someone else. If you never did it, try it once and check the coder's expression.

Accept criticism but don't criticize

Poorly written source code teaches you to write good source code provided you take it positively and learn a lesson from it.
Bug Free Code Your target should be to stop the bugs at first place and create a BUG-FREE code. Think like a tester, so that you should have a challenge for the testers.

Best Practice 5 - Testing to be followed like a religion

Testing is mandatory after every small or big change no matter how tight schedule you have or you just changed a small comment inside the code, you have testing due for the changed code.
There is nothing like trust while developing software, no matter how expert or how senior you are in writing source code, you would have to perform testing for each and every change you did in the code.
  • Tight schedule, no compromise.
  • Changed just a comment, still you have to test it.
  • Changed just a variable name, testing has to be done.
  • If you feel lazy...it's too dangerous.

If you don't want to follow it? You will be in trouble!

Software Testing

Celebrate every bug you find

Yes, you should not feel unhappy if you or another tester finds a bug in your software source code. Following are the enough reasons to celebrate this important discovery:
  • Bugs are your enemies, so you have killed one.
  • Now your software is having one bug less.
  • Mistakes are good as long as they are not repeating.
  • What you learn today, prepares you for tomorrow
Same time, do not criticize any developer in case any bug arises in his/her code because so far at least I do not know any programmer, who can write bug-free source code in the world, second this is one of the reasons we have a separate phase in SDLC (Software Development Life Cycle) which we call post production support (or support & maintenance).

Best Practice 6 - Keep your Code and Documents Safe

A smart developer keeps habit of taking daily backup of the produced artifacts, otherwise machine crash can crash you as well. You should keep your artifacts at your local machine as well as another secure machine, so that in case of machine crash, you can continue with the saved copy of the source code or documents.
If you have the habit of taking daily backup then in worst scenario you may lose at most one-day effort, but if you take weekly or monthly backup, then there is a risk of losing whole-week or whole-month effort, and you will face biggest disappointment you ever had.
Disappointed Programmer

Multiple copies create confusion

This is true that having backup is one of the most important best practices, but it should be maintained in well managed way as you can use tags like name, date and time of the backup, version, etc. If you have multiple copies of the same source code or document, then it will create confusion and it would be difficult to identify latest code or document.
It is strongly recommended to use proper source code version control system. There are many source code version control software applications available for free (like SCCS, CVS, Subversion etc.) which you can use to store different versions of the software. But while using a source code control system, follow the rules below:
  • Always take source code from the version control system.
  • Always assign a new version to every change.
  • Always put source code back into control system.

Password sharing is strictly prohibited

Password Sharing
  • Love, affection, friendship and relationship are on top of everything, but never embrace anybody asking for password.
  • If you are sticking to first point, then why you would share your password with anyone if you are not asking from anybody.
  • Keep changing it on a frequent basis and it's good if you have some logic to drive your passwords, otherwise during your long vacation, you will forget them.

Best Practice 7 - Keep your Tools & Techniques Handy

I remember an instance when I wanted to find out debug keyword in all the C++ files available in various directories and sub-directories, it took me 30 minutes to find the command, but finally, I kept a note of the command, and whenever I'm in need, I use it without wasting a second.
$find . -name \*.cpp -exec grep -q "debug" '{}' \; -print
So, I made it one of the best practices to keep such commands and tools handy so that they can be used anytime without doing any R&D and to save valuable time. Better to maintain a text file having all such frequently used commands and create its link at desktop.
IT Tools & Techniques

Few Essential Tools

It depends on what type of programming, coding you are doing but following are few of the essential tools, which should be readily available with a software developer:
  • A good text editor to write and edit the program.
  • A nice debugger to debug the program.
  • A memory detector in case you are using dynamic memory allocation.
  • Putty to connect to a remote machine.
  • WinSCP or FileZilla to ftp files on a remote machine.
  • IDE ( Integrated Development Environment) for rapid development.

Always keep adding new tools & techniques in your box

Tool Box Make sure you keep applying latest patches of your tools and utilities and same time I will suggest to clean unwanted software from your computer as they unnecessarily make your computer slow and you never know if any one of them is having a security hole, which can expose your computer to the outside world.

Best Practice 8 -Leave the ego behind, Be eager to learn

We always learn from books and nowadays from internet. But IT is such a field, where we learn a lot from our colleagues. They are our best references, but there are software developers, who either feel shy in asking their doubts or are not thankful to others, so ultimately when they ask next time, they get zero answer.
IT is vast and nobody can have complete knowledge on any subject. Everyday, we come across different problems. So Ask...Don't feel shy if you don't know X.
I'm not suggesting you to bother someone unreasonably and asking for spoon feeding to learn anything. NO, be polite, thankful, directly come to the point, understand and support others.

New technologies are coming everyday

Eager to Learn If you want to sustain in the market, then you would have to keep yourself updated with latest IT tools, and technologies. Following are the few sources:
  • Technical Forums over the internet.
  • Technical magazines on various IT subjects.
  • Technical Bulletin Boards
  • Conferences, Training and Workshops
  • Latest versions of old tools and packages, languages, etc.





Wednesday, 24 February 2016

How SSL, HTTPS and Certificates works in Java web applications

How SSL, HTTPS and Certificates works in Java web applications
SSL as implemented by the JSSE (Java Secure Socket Extension)

SSE provides an SSL toolkit for Java applications. In addition to the necessary classes and interfaces, JSSE provides a handy command-line debugging switch that you can use to watch the SSL protocol in action. In addition to providing useful information for debugging a recalcitrant application, playing with the toolkit is a great way to get your feet wet with SSL and JSSE.


How to configure Tomcat to support SSL or https

1. Generate Keystore

First, uses “keytool” command to create a self-signed certificate. During the keystore creation process, you need to assign a password and fill in the certificate’s detail.
C:\Program Files\Java\jdk1.7.0_45\bin>keytool -g
Enter keystore password:
Re-enter new password:
What is your first and last name?
  [Unknown]:  Prakash Gaikwad
What is the name of your organizational unit?
  [Unknown]:  Prash Infosoft Pvt Ltd
What is the name of your organization?
  [Unknown]:  Prash Infosoft Pvt Ltd
What is the name of your City or Locality?
  [Unknown]:  Pune
What is the name of your State or Province?
  [Unknown]:  Maharashtra
What is the two-letter country code for this uni
  [Unknown]:  IN
Is CN=Prakash Gaikwad, OU=Prash Infosoft Pvt Ltd
ne, ST=Maharashtra, C=IN correct?
  [no]:  y

Enter key password for <tomcat>
        (RETURN if same as keystore password):

Here, you just created a certificate named “prash.keystore“, which locate at “C:\Users\prash“.
Certificate Details
You can use same “keytool” command to list the existing certificate’s detail



2. Connector in server.xml

Next, locate your Tomcat’s server configuration file at $Tomcat\conf\server.xml, modify it by adding a connector element to support for SSL or https connection.
File : $Tomcat\conf\server.xml
//...
<!-- Define a SSL HTTP/1.1 Connector on port 8443
        This connector uses the JSSE configuration, when using APR, the        connector should be using the OpenSSL style configuration        described in the APR documentation --> <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"              maxThreads="150" scheme="https" secure="true"              clientAuth="false" sslProtocol="TLS"                keystoreFile="c:\mkyongkeystore"                keystorePass="password" />
 //...
Note
keystorePass="password" is the password you assigned to your keystore via “keytool” command.

3. Done

Saved it and restart Tomcat, access to https://localhost:8443/
tomcat-ssl-configuration
In Google Chrome to access the Tomcat configured SSL site, and you may notice a crossed icon appear before the https protocol :), this is caused by the self-signed certificate and Google chrome just do not trust it.
In production environment, you should consider buy a signed certificate from trusted SSL service provider or sign it with your own CA server

Reference

  1. Tomcat 6 : SSL configuration HOW-TO

2 – Configuring Tomcat for using the keystore file – SSL config

Open your Tomcat installation directory and open the conf folder. Inside this folder, you will find the server.xml file. Open it.
Find the following declaration:

3 – Let’s test it!

Start tomcat service and try to access https://localhost:8443. You will see Tomcat’s local home page.
Note if you try to access the default 8080 port it will be working too: http://localhost:8080

4 – BONUS - Configuring your app to work with SSL (access through 

https://localhost:8443/yourApp)

To force your web application to work with SSL, you simply need to add the following code to your web.xml file (before web-app tag ends):
        
<security-constraint>
    <web-resource-collection>
        <web-resource-name>securedapp</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>
The url pattern is set to /* so any page/resource from your application is secure (it can be only accessed with https). The transport-guarantee tag is set to CONFIDENTIAL to make sure your app will work on SSL.
If you want to turn off the SSL, you don’t need to delete the code above from web.xml, simply change CONFIDENTIAL to NONE.