Sunday 27 April 2014

Hibernate learning made easy by sample code snippet

If you wish to quickly get started with Hibernate, then this post is to provide you the sample code snippet for learning Hibernate. Hibernate is a ORM (Object / Relational Mapping) framework and provides implementation of JPA (Java Persistence API) specification. So first of all, let's start with what is ORM!

About ORM?

ORM tool serves as bridge between application  in object oriented language (e.g. Java) and relational database (e.g. MySQL). ORM works by transforming data from one representation to other i.e. from programming language’s application objects to database table rows & vice versa. With help of conventional relational database management system, ORM provides virtual object database. It maps,
  • Classes                     ->     Database Tables
  • Properties/fields        ->    Table Columns
  • Runtime  Objects      ->    Table Rows

Advantage of ORM:
  • Can reduce the amount of code you need to write  (30% then JDBC)
  • Corresponding boost in productivity (can be drastic)
  • Can make your application maintainable because of fewer LOC
  • Can often combine second level catch to improve the performance
  • Vendor independence (switching from one RDBMS to other becomes seamless, as it just requires negligible configuration change in application code)

Disadvantage of ORM:
  • May be difficult to tune query
  • Performance of tool may affect your application performance, if not used appropriately

In a nutshell, with ORM gain is so great in typical application that you can’t ignore it. ORM works well in 90-95% of cases. Next, how to get started with learning Hibernate!

Hibernate Quick Start Guide

What are learning objectives of Hibernate?
  1. Hibernate tooling and project setup
  2. Establishing connection between Java application and RDBMS using Hibernate Configuration (hibernate.cfg.xml), SessionFactory and Session
  3. Different Hibernate mapping options between Java Entities and RDBMS tables
  4. Load, Get or Query records of database in the form of Java objects by using Hibernate
  5. Perform Save, Update, Delete operations in database using Hibernate Transactions
  6. Learn to use Hibernate annotations instead of xml configuration
  7. Learn advance topics in Hibernate - caching, batch processing…
  8. Leverage code further using Spring framework and Hibernate integration
How to get started with Hibernate learning?
  1. Download sample code snippet for hibernate learning made easy, which is available @ https://github.com/tirthalpatel/Learning-Hibernate
  2. Follow instructions of "README.md" file for project setup.
  3. Now run and explore code of - Hello World tutorial.
  4. In the similar fashion, learn more hibernate fundamentals - O/R mapping (mapping component, collections, entity relationships, inheritance...), Querying, Annotations...

Hibernate Best Practices
  • Mark all the associations as lazy by default
  • Use JOIN fetch mode for loading lazy associations, rather than calling getter method of association
  • Use <component> or @Embedded for better performance in OneToOne relationship
  • Use transactions for save or update operations only
  • Always close the session in finally block
  • Use detached objects in multi-tiered applications
  • Consider abstracting business logic from hibernate, use Dao pattern and Factory pattern
  • Use Spring or EJB3 compliant application server for declarative transaction demarcation
  • More best practices…


Also Refer

Sunday 13 April 2014

Static Code Analyzers - OWSAP LAPSE+, Codepro AnalytiX, FindSecurityBugs - How those help developers to prevent security problems in J2EE web applications code?

I hope, you have already read "Preface" of my static code analyzers series.

Recently reported Heartbleed Bug is a serious vulnerability in the implementation of popular OpenSSL cryptographic software library, which is already being called one of the biggest security threats the Internet has ever seen. Because the bug has affected many popular websites and services - ones you might use every day, like Gmail, Yahoo and Facebook - and could have quietly exposed your sensitive account information (such as passwords and credit card numbers) over the past two years!

Yeah, "Security" is one of the most critical parameters of non-functional requirements in most of applications.

So in this post, I would like to encourage developers for understanding critical web vulnerabilities and leveraging application code by adopting security auditing tools. Besides that I have shared my evaluation feedback about Codepro Analytix, Find Security Bugs, OWSAP LAPSE+ and VisualCodeGrepper tools for reviewing vulnerable J2EE web applications code.

As a matter of fact most of Java developers work on J2EE web application development sometime in their career, but most of might not be meticulous about understanding, exploiting and defending the application against known web vulnerabilities.

If we are working on J2EE web application development and security is one of quality attributes for the application (which would be majority time), then we must understand the known security risks for web applications and learn to write secure code by adopting "OWASP Top 10 Project" publications. Also we should use free or commercial tool to audit security problems in the code.

As per "OWASP Top 10 - 2013" project, below are the top 10 critical web application flows of the 2013 year:

Straight from the horse's mouth

Now let's know the above-mentioned tools briefly.
  • Codepro AnalytiX - A premier Java software testing tool for Eclipse developers who are concerned about improving software quality.
  • Find Security Bugs - A plugin for FindBugs that aim to help security audit on Java web application. Also work with Scala and Groovy projects.
  • OWSAP LAPSE+ - A security scanner for detecting vulnerabilities of untrusted data injection in Java EE Applications. It has been developed as a plugin for Eclipse Java Development Environment, working specifically with Eclipse Helios and Java 1.6 or higher. 
  • VisualCodeGrepper - An automated code security review tool for C++, C#, VB, PHP, Java and PL/SQL which is intended to drastically speed up the code review process by identifying bad/insecure code.

Practical Shot and My Feedback

I evaluated Codepro AnalytiX, Find Security Bugs, LAPSE+ and VisualCodeGrepper tools to review code of WebGoat vulnerable J2EE web applications to identify security related problems. The highlights are as below,

CodePro AnalytiX

If you don't know power of CodePro AnalytiX tool, then please read my another post on GoogleCodePro AnalytiX - Why is it premium eclipse plugin for java developers?

This Eclipse plugin is really awesome. It offers option to review the code for "security" rule set only (Eclipse IDE -> Select Project -> CodePro Tools -> Code Audit Using -> Only select "Security" in "Choose Audit Rule Set" ->  OK). The tool reported 1100+ issues related to security by analyzing source code of "WebGoat" project using "Security" rule set (with default configuration). It also guides the developer that how to crack particular type of problem such as "SQL Injection" in below screen. When you double click on particular issue, it would open associated source code in Java Editor.


Find Security Bugs

Ifyou don't know what is FindBugs, then first please read my another post aboutit. Once FindBugs is installed in Eclipse and then configure it to report only potential security bugs using "Find Security Bugs" plugin.

The tool reported 54 potential security bugs by analyzing compiled class files of "WebGoat" project. Some of reported issues are common in analysis results of both CodePro Analytix and Find Security bugs. Though CodePro Analytix could report many additional issues compare to Find Security Bugs, Find Security Bugs could report some additional potential bugs which CodePro AnalytiX didn't report as highlighted in below screen. When you double click on particular issue, it would open associated source code in Java Editor.


OWSAP LAPSE+

LAPSE+ has been developed as a Eclipse plugin for working specifically with Eclipse Helios and lastly updated in 2011. When I installed in Eclipse Keper, "Vulnerability Sources and Vulnerability Sinks" views worked without any issue, but somehow "Provenance Tracker" view didn't work. Also LAPSE+ tool expects that projects are properly configured in Eclipse and don't have compilation errors. Because compilation errors will prevent LAPSE+ from detecting all the potential vulnerabilities.

LAPSE+ provides three different views for the analysis of vulnerabilities and reported many issues as show next. And "Find Source" option would open associated source code in Java Editor.

Vulnerability Sources View - It shows the points of code that can be source of untrusted data injection. It detects vulnerabilities corresponds to Information Leakage, Parameter Tampering, URL Tampering, Header Manipulation and Cookie Poisoning.


Vulnerability Sinks View - It shows the points of code that can insert the untrusted data in the application, manipulating its behavior. It detects vulnerabilities corresponds to SQL Injection, Cross-site scripting, Path Traversal, Command Injection, HTTP Response Splitting, Xpath Injection, XML Injection and LDAP Injection. When "Perform backward propagation from this sink" is clicked, it would show it in "Provenance Tracker View".


Provenance Tracker View - This view traces the backward propagation tree from a vulnerability sink in order to check if it reaches a vulnerability source. If this happens we have a vulnerability in our code. When this occurs, ProvenanceTracker View shows the matches in red. On the other hand, if it reaches a safe source it shows it in blue.


VisualCodeGrepper

This standalone tool could find some of bad/insecure issues, but I didn't find it capable enough like LAPSE+, CodePro Analytix, etc.  Also it got closed due to errors randomly while performing some of operations.




My Final Thoughts

CodePro Analytix, Find Security Bugs and OWSAP LAPSE+ are Eclipse plugins. Though you would see some duplicate findings in reported issues by all three, each has some unique abilities too. So if you use Eclipse IDE for J2EE web applications development, then these tools would be highly helpful to perform code review for vulnerability issues.

If you are not using Eclipse IDE, you should explore most suitable plugin/tool for security code auditing in your given situation. For example, you may consider a standalone VisualCodeGrepper tool which can help at some extent. Though I tried for only Java, it claims to be an automated code security review tool for C++, C#, VB, PHP and PL/SQL too.

Free code security review tool vs. Commercial security solution offering
  • CodePro Analytix, Find Security Bugs, LAPSE+, VisualCodeGrepper - such free tools are not intended as a comprehensive solution for Web Application Security, but rather as an aid in the code review process. Instead of any of one of those, you may consider using multiple tools for taking optimum possible benefits.
  • If you are looking for more comprehensive solutions to identify and fix vulnerabilities in web and mobile applications, then you should look at some of the commercial offerings such as IBM Security AppScan Source, HP Software Security Solutions - Fortify Static Code Analyzer, etc.

What's next?


Disclaimer
I don't aim to exploit code of any open source project or sample application, while I share my evaluation feedback of given tool on selected publicly available code. Also I am not biased to particular free or commercial tools, rather my objective is about sharing my own experience on set of tools.

Also Refer


Sunday 6 April 2014

OOP Design - Part 2 - Class principles - SOLID

I hope, you have already read "Preface" of this post.  Also  don't miss to refer corresponding example java code (not for production, illustrative purposes only) to understand theory of each principle.

SOLID Principles

The principles of SOLID are guidelines that can be applied while working on software to remove code smells by causing the programmer to refactor the software's source code until it is both legible and extensible. It is typically used with test-driven development, and is part of an overall strategy of agile and adaptive programming.
  • S = SRP = Single responsibility principle
  • O = OCP = Open/closed principle
  • L = LSP = Liskov substitution principle
  • I = ISP = Interface segregation principle
  • D = DIP = Dependency inversion principle

Single responsibility principle
  • Definition of SRP?
    • Every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. (Wikipedia)
    • There should never be more than one reason for a class to change. (Robert C. "Uncle Bob" Martin)
  • Rules of Thumb?
    • If you cannot come up with meaningful name for your class focused to single responsibility, then it's probably doing too much.
    • Ensure you don't design and implement God class (a class that knows too much or does too much, which is example of an anti-pattern).
    • Remember more classes != more complexity
  • Don't mix-up many different responsibilities in a single class (known as God class), instead come up different classes and each should be focused to single responsibility. Example of responsibilities?
    • Validation (PasswordValidation, EmailValidation…)
    • Notification (EmailNotification, SMSNotification…)
    • Parsing (XMLParser, CSVParser...)
    • Formatting
    • Error Handling
    • Persistence
  • Understand theory from Example java code snippet

Open/closed principle
  • Definition of OCP?
    • Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. That is, such an entity can allow its behavior to be modified without altering its source code. This is especially valuable in a production environment, where changes to source code may necessitate code reviews, unit tests, and other such procedures to qualify it for use in a product: code obeying the principle doesn't change when it is extended, and therefore needs no such effort. (Wikipedia)
  • Rules of Thumb?
    • Open to extension =  you should design your classes so that new functionality can be added as new requirements are generated.
    • Closed for modification = Once you have developed a class you should never modify it, except to correct bugs.
    • Design and code should be done in a way that new functionality should be added with minimum or no changes in the existing code
    • When needs to extend functionality - avoid tight coupling, don't use if-else/switch-case logic, do code refactoring as required...
    • Techniques to achieve - Inheritance, Polymorphism, Generics
    • Pattern to apply – Strategy Pattern, Template Method
  • Example
    • File Parser  with initially supported Text and XML parsing functionality. Now extend it to support new functionality of CSV parsing and then support even more types of parting...
  • Understand theory from Example java code snippet

    Liskov substitution principle
    • Definition of LSP?
      • Derived classes must be substitutable for their base classes. That means, functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it. (Robert C. "Uncle Bob" Martin)
    • Rules of Thumb?
      • This principle applies to inheritance hierarchies and is just an extension of the Open Close Principle.
      • It means that we must make sure that new derived classes are extending the base classes without changing their original behavior. Basically, derived classes should never do less than their base class.
      • If a subtype of the supertype does something that the client of the supertype does not expect, then this is in violation of LSP. Imagine a derived class throwing an exception that the superclass does not throw, or if a derived class has some unexpected side effects. One has to consider that how the client programs are using the class hierarchy. Sometimes code refactoring is required to fix identified LSP violations.
    • Example
      • Media Player is super class having ability of playing audio and video both. Now VLC and DIV Media Players are the subtypes of Media Player and inheriting the original behavior of Media player; and are substitutable for their base class Media player in the client program code. Now there is need of launching new Winamp Media Player, but with  audio support only. So one could extend Media Player class and override original behavior of Media Player's playVideo() method  for doing nothing or may be throw UnSupportedException (in short Winamp media player is doing less that its super class Media player). So this can be considered as LSP violation, as it may cause unpredictable behavior when Media Player is substituted with Winamp Media Player in client code.
    • Understand theory from Example java code snippet
    Interface segregation principle
    • Definition of ISP?
      • Make fine grained interfaces that are client specific.  That means, clients should not be forced to depend upon interfaces that they do not use. (Robert C. "Uncle Bob" Martin)
    • Rules of Thumb?
      • Don’t depend on things you don’t need. Interfaces containing methods that are not specific to it are called polluted or fat interfaces. We should avoid them.
      • Many client-specific interfaces are better than one general-purpose interface. When we have non-cohesive interfaces, the ISP guides us to create multiple, smaller, cohesive interfaces.
    • Example
      • Consider Order Service interface having responsibilities like createOrder, amendOrder, submitOrder and processOrder. Now there are two clients end users and backend order processor job, who depend on Order Service interface. But processOrder() is not of use for end user client, still client is forced to depend as per design. Similarly backend order process job is only interested in processOrder() service, still forced to depend on other services too. So ISP is violated.
    • Understand theory from Example java code snippet

    Dependency inversion principle
    • Definition of DIP?
      • Depend on abstractions, not on concretions.  (A) High-level modules should not depend on low-level modules. Both should depend on abstractions. (B) Abstractions should not depend on details. Details should depend on abstractions. (Robert C. "Uncle Bob" Martin)
    • Rules of Thumb?
      • Design by contract.
      • Every dependency in the design should target an interface, or an abstract class. No dependency should target a concrete class.
      • Factories and Abstract Factories can be used as dependency frameworks, but there are specialized frameworks for that such as Spring IOC (Inversion of Control Container).
    • Example
      • LoginManager depends on implementation class SimpleAuthenticator to authenticate user from database. In future to change it to authenticate by LDAPAuthenticator, LoginManager and its test case would change. This can be avoided by following Dependency Inversion Principle.
      • The refactored code can be - LoginManager depends on Authenticator interface only. Authenticator interface will be implemented by SimpleAuthenticator and LDAPAuthenticator implementation classes. The client of LoginManager may inject dependency on implementation class or dependency frameworks may be used for it.
    • Understand theory from Example java code snippet


    Also Refer