Tuesday, June 17, 2014

Implement PMD and CPD (Copy paste detector) using ANT

You can implement automated PMD and CPD analysis on your java source code using ant.

Why PMD?


PMD is a static code analyser tool. It can be used to check common programming mistakes like class naming, variable naming, cyclomatic complexity, unused variables, unused imports etc. and many more.

Examples:
– Empty try/catch blocks

– Over-complicated expressions

– Using .equals() instead of ‘==’

– Unused variables and imports

– Unnecessary loops and if statements

– Enforce naming conventions

Additionally, PMD comes with a copy-paste detector to find blocks of copied and pasted code. Best of all, you can customize the rules. PMD includes a set of built-in rules and supports the ability to write custom rules. The custom rules can be written in two ways:

1- Using XPath

2- Using Java classes

Here i have used XPath wherever rules are customized.

Why CPD?

The Copy/Paste Detector (CPD) is an add-on to PMD that uses the Rabin–Karp string search algorithm to find duplicated code.
After running this tool against your source code you will be able to find the duplicate code and you can create a utility class or method in some common class and re-use it, instead.


So, Here we go>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Prerequisites jar files for PMD/CPD:

ant-1.8.1.jar
ant-launcher-1.8.1.jar
ant-testutil-1.7.1.jar
asm-3.2.jar
commons-io-2.2.jar
dom4j-1.6.1.jar
javacc-4.1.jar
jaxen-1.1.1.jar
jcommander-1.27.jar
jdom-1.0.jar
junit-4.4.jar
pmd-5.0.5.jar
rhino-1.7R3.jar
saxon-9.1.0.8-dom.jar
saxon-9.1.0.8.jar
xercesImpl-2.9.1.jar
xml-apis-1.3.02.jar
xmlParserAPIs-2.6.2.jar
xom-1.0.jar

Download PMD : http://sourceforge.net/projects/pmd/

Reference: http://pmd.sourceforge.net/

PMD Documentation:

PMD version 5.0.5
http://pmd.sourceforge.net/pmd-5.0.5/

PMD version 5.1.2
http://pmd.sourceforge.net/pmd-5.1.2/


PMD For eclipse : http://sourceforge.net/projects/pmd/files/pmd-eclipse/update-site/

Note:  I am using PMD version 5.0.5. Version 5.1.2 onwards you need to make a small change in rule set for singleton .

RuleSet XML File (pmdrulesets.xml):

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ruleset xmlns="http://pmd.sf.net/ruleset/1.0.0" name=""
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd"
       xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd">
       <description>
             PMD Plugin preferences rule set
             Priority means: 1 – error, high priority, 2 – error,
             normal priority, 3 – warning, high priority, 4 – warning,
             normal priority and 5 – information.
       </description>
       <rule ref="rulesets/java/typeresolution.xml/LooseCoupling">
             <priority>3</priority>
       </rule>
       <rule
             ref="rulesets/java/typeresolution.xml/CloneMethodMustImplementCloneable">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/typeresolution.xml/UnusedImports">
             <priority>4</priority>
       </rule>
       <rule
             ref="rulesets/java/typeresolution.xml/SignatureDeclareThrowsException">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/braces.xml/ForLoopsMustUseBraces">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/braces.xml">
             <exclude name="IfStmtsMustUseBraces" />
             <exclude name="IfElseStmtsMustUseBraces" />
             <exclude name="WhileLoopsMustUseBraces" />
       </rule>
       <rule ref="rulesets/java/naming.xml/ShortVariable">
             <priority>1</priority>
             <properties>
                    <property name="xpath">
                           <value>
                                 //VariableDeclaratorId[string-length(@Image) &lt; 3]
                           </value>
                    </property>
             </properties>
       </rule>
       <rule ref="rulesets/java/naming.xml/LongVariable">
             <priority>4</priority>
             <properties>
                    <property name="xpath">
                           <value>
                                 //VariableDeclaratorId[string-length(@Image) > 40]
                           </value>
                    </property>
             </properties>
       </rule>
       <rule ref="rulesets/java/naming.xml/ShortMethodName">
             <priority>4</priority>
             <properties>
                    <property name="xpath">
                           <value>
                                 //MethodDeclarator[string-length(@Image) &lt; 2]
                           </value>
                    </property>
             </properties>
       </rule>
       <rule ref="rulesets/java/naming.xml/VariableNamingConventions">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/MethodNamingConventions">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/ClassNamingConventions">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/AbstractNaming">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/AvoidDollarSigns">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/MethodWithSameNameAsEnclosingClass">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/SuspiciousHashcodeMethodName">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/SuspiciousConstantFieldName">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/SuspiciousEqualsMethodName">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/AvoidFieldNameMatchingTypeName">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/AvoidFieldNameMatchingMethodName">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/NoPackage">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/PackageCase">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/MisleadingVariableName">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/naming.xml/BooleanGetMethodName">
             <priority>1</priority>
       </rule>

       <rule ref="rulesets/java/design.xml/UseUtilityClass">
             <priority>1</priority>
       </rule>

       <rule ref="rulesets/java/design.xml/SimplifyBooleanReturns">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/SimplifyBooleanExpressions">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/SwitchStmtsShouldHaveDefault">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AvoidDeeplyNestedIfStmts">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AvoidReassigningParameters">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/SwitchDensity">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/ConstructorCallsOverridableMethod">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AccessorClassGeneration">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/FinalFieldCouldBeStatic">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/CloseResource">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/NonStaticInitializer">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/DefaultLabelNotLastInSwitchStmt">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/NonCaseLabelInSwitchStatement">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/OptimizableToArrayCall">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/BadComparison">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/EqualsNull">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/InstantiationToGetClass">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/IdempotentOperations">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/SimpleDateFormatNeedsLocale">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/ImmutableField">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/UseLocaleWithCaseConversions">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AvoidProtectedFieldInFinalClass">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AssignmentToNonFinalStatic">
             <priority>1</priority>
       </rule>
       <rule
              ref="rulesets/java/design.xml/MissingStaticMethodInNonInstantiatableClass">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AvoidSynchronizedAtMethodLevel">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/MissingBreakInSwitch">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/UseNotifyAllInsteadOfNotify">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AvoidInstanceofChecksInCatchClause">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AbstractClassWithoutAbstractMethod">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/SimplifyConditional">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/CompareObjectsWithEquals">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/PositionLiteralsFirstInComparisons">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/UnnecessaryLocalBeforeReturn">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/NonThreadSafeSingleton">
             <priority>3</priority>
       </rule>

       <rule ref="rulesets/java/design.xml/UncommentedEmptyMethodBody">
             <priority>1</priority>
       </rule>

       <rule ref="rulesets/java/design.xml/UncommentedEmptyConstructor">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AvoidConstantsInterface">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/UnsynchronizedStaticDateFormatter">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/design.xml">
             <exclude name="ConfusingTernary" />
       </rule>
       <rule ref="rulesets/java/design.xml/UseCollectionIsEmpty">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/PreserveStackTrace">
             <priority>1</priority>
       </rule>

       <rule
              ref="rulesets/java/design.xml/ClassWithOnlyPrivateConstructorsShouldBeFinal">
             <priority>1</priority>
       </rule>

       <rule
              ref="rulesets/java/design.xml/EmptyMethodInAbstractClassShouldBeAbstract">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/SingularField">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/ReturnEmptyArrayRatherThanNull">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/AbstractClassWithoutAnyMethod">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/design.xml/TooFewBranchesForASwitchStatement">
             <priority>1</priority>
       </rule>
       <rule
             ref="rulesets/java/design.xml/FieldDeclarationsShouldBeAtStartOfClass">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strictexception.xml/AvoidCatchingThrowable">
             <priority>1</priority>
       </rule>
       <rule
             ref="rulesets/java/strictexception.xml/SignatureDeclareThrowsException">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/strictexception.xml/ExceptionAsFlowControl">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/strictexception.xml/AvoidCatchingNPE">
             <priority>3</priority>
       </rule>
       <rule
             ref="rulesets/java/strictexception.xml/AvoidThrowingRawExceptionTypes">
             <priority>1</priority>
       </rule>
       <rule
              ref="rulesets/java/strictexception.xml/AvoidThrowingNullPointerException">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strictexception.xml/AvoidRethrowingException">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strictexception.xml/DoNotExtendJavaLangError">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strictexception.xml/DoNotThrowExceptionInFinally">
             <priority>3</priority>
       </rule>
       <rule
              ref="rulesets/java/strictexception.xml/AvoidThrowingNewInstanceOfSameException">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strictexception.xml/AvoidCatchingGenericException">
             <priority>2</priority>
       </rule>
       <rule
             ref="rulesets/java/strictexception.xml/AvoidLosingExceptionInformation">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/unusedcode.xml/UnusedPrivateField">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/unusedcode.xml/UnusedLocalVariable">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/unusedcode.xml/UnusedPrivateMethod">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/unusedcode.xml/UnusedFormalParameter">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/logging-java.xml/MoreThanOneLogger">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/logging-java.xml/LoggerIsNotStaticFinal">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/logging-java.xml/SystemPrintln">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/logging-java.xml/AvoidPrintStackTrace">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/AvoidDuplicateLiterals">
             <priority>1</priority>
             <properties>
                    <property name="skipAnnotations">
                           <value>true</value>
                    </property>
                    <property name="maxDuplicateLiterals">
                           <value>4</value>
                    </property>
             </properties>
       </rule>
       <rule ref="rulesets/java/strings.xml/StringInstantiation">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/StringToString">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/InefficientStringBuffering">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/UnnecessaryCaseChange">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/UseStringBufferLength">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/AppendCharacterWithChar">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/ConsecutiveAppendsShouldReuse">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/ConsecutiveLiteralAppends">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/UseIndexOfChar">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/InefficientEmptyStringCheck">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/InsufficientStringBufferDeclaration">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/UselessStringValueOf">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/StringBufferInstantiationWithChar">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/UseEqualsToCompareStrings">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/strings.xml/AvoidStringBufferField">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/ReplaceVectorWithList">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/ReplaceHashtableWithMap">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/ReplaceEnumerationWithIterator">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/AvoidEnumAsIdentifier">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/AvoidAssertAsIdentifier">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/IntegerInstantiation">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/ByteInstantiation">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/ShortInstantiation">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/LongInstantiation">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/JUnit4TestShouldUseBeforeAnnotation">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/JUnit4TestShouldUseAfterAnnotation">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/JUnit4TestShouldUseTestAnnotation">
             <priority>3</priority>
       </rule>
       <rule
             ref="rulesets/java/migrating.xml/JUnit4SuitesShouldUseSuiteAnnotation">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/migrating.xml/JUnitUseExpected">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/UseProperClassLoader">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/MDBAndSessionBeanNamingConvention">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/RemoteSessionInterfaceNamingConvention">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/LocalInterfaceSessionNamingConvention">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/LocalHomeNamingConvention">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/RemoteInterfaceNamingConvention">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/DoNotCallSystemExit">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/StaticEJBFieldShouldBeFinal">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/j2ee.xml/DoNotUseThreads">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/MethodArgumentCouldBeFinal">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/LocalVariableCouldBeFinal">
             <priority>1</priority>
       </rule>
       <rule
             ref="rulesets/java/optimizations.xml/AvoidInstantiatingObjectsInLoops">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/UseArrayListInsteadOfVector">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/SimplifyStartsWith">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/UseStringBufferForStringAppends">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/UseArraysAsList">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/AvoidArrayLoops">
             <priority>2</priority>
       </rule>
       <rule
             ref="rulesets/java/optimizations.xml/UnnecessaryWrapperObjectCreation">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/AddEmptyString">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/RedundantFieldInitializer">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/optimizations.xml/PrematureDeclaration">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptyCatchBlock">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptyIfStmt">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptyWhileStmt">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptyTryBlock">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptyFinallyBlock">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptySwitchStatements">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptySynchronizedBlock">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptyStaticInitializer">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptyStatementNotInLoop">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/empty.xml/EmptyInitializer">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/unnecessary.xml/UnnecessaryConversionTemporary">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/unnecessary.xml/UnnecessaryReturn">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/unnecessary.xml/UnnecessaryFinalModifier">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/unnecessary.xml/UselessOverridingMethod">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/unnecessary.xml/UselessOperationOnImmutable">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/unnecessary.xml/UnusedNullCheckInEquals">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/JumbledIncrementer">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/ForLoopShouldBeWhileLoop">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/OverrideBothEqualsAndHashcode">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/DoubleCheckedLocking">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/ReturnFromFinallyBlock">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/UnconditionalIfStatement">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/BooleanInstantiation">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/CollapsibleIfStatements">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/ClassCastExceptionWithToArray">
             <priority>3</priority>
       </rule>
       <rule
              ref="rulesets/java/basic.xml/AvoidDecimalLiteralsInBigDecimalConstructor">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/MisplacedNullCheck">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/AvoidThreadGroup">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/BrokenNullCheck">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/BigIntegerInstantiation">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/AvoidUsingOctalValues">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/AvoidUsingHardCodedIP">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/CheckResultSet">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/AvoidMultipleUnaryOperators">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/ExtendsObject">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/CheckSkipResult">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/AvoidBranchingStatementAsLastInLoop">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/DontCallThreadRun">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/basic.xml/DontUseFloatTypeForLoopIndices">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/sunsecure.xml/MethodReturnsInternalArray">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/sunsecure.xml/ArrayIsStoredDirectly">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/coupling.xml/CouplingBetweenObjects">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/coupling.xml/ExcessiveImports">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/coupling.xml/LooseCoupling">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/imports.xml/DuplicateImports">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/imports.xml/DontImportJavaLang">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/imports.xml/UnusedImports">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/imports.xml/ImportFromSamePackage">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/imports.xml/UnnecessaryFullyQualifiedName">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/imports.xml/TooManyStaticImports">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/JUnitStaticSuite">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/JUnitSpelling">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/JUnitAssertionsShouldIncludeMessage">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/JUnitTestsShouldIncludeAssert">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/TestClassWithoutTestCases">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/UnnecessaryBooleanAssertion">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/UseAssertEqualsInsteadOfAssertTrue">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/UseAssertSameInsteadOfAssertTrue">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/UseAssertNullInsteadOfAssertTrue">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/junit.xml/SimplifyBooleanAssertion">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/NullAssignment">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/OnlyOneReturn">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/AssignmentInOperand">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/AtLeastOneConstructor">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/DontImportSun">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/SuspiciousOctalEscape">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/CallSuperInConstructor">
             <priority>4</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/UnnecessaryParentheses">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/DefaultPackage">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/BooleanInversion">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/AvoidUsingShortType">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/AvoidUsingVolatile">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/AvoidUsingNativeCode">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml/AvoidAccessibilityAlteration">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/controversial.xml">
             <exclude name="DataflowAnomalyAnalysis" />
             <exclude name="UnnecessaryConstructor" />
             <exclude name="AvoidFinalLocalVariable" />
       </rule>
       <rule
              ref="rulesets/java/controversial.xml/DoNotCallGarbageCollectionExplicitly">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/NPathComplexity">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/ExcessiveMethodLength">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/ExcessiveParameterList">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/ExcessiveClassLength">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/CyclomaticComplexity">
             <priority>4</priority>
             <properties>
                    <property name="reportLevel">
                           <value>9</value>
                    </property>
                    <property name="showClassesComplexity">
                           <value>true</value>
                    </property>
                    <property name="showMethodsComplexity">
                           <value>true</value>
                    </property>
             </properties>
       </rule>
       <rule ref="rulesets/java/codesize.xml/ExcessivePublicCount">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/TooManyFields">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/NcssMethodCount">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/NcssTypeCount">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/NcssConstructorCount">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/codesize.xml/TooManyMethods">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/finalizers.xml/EmptyFinalizer">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/finalizers.xml/FinalizeOnlyCallsSuperFinalize">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/finalizers.xml/FinalizeOverloaded">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/finalizers.xml/FinalizeDoesNotCallSuperFinalize">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/finalizers.xml/FinalizeShouldBeProtected">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/finalizers.xml/AvoidCallingFinalize">
             <priority>3</priority>
       </rule>
       <rule
             ref="rulesets/java/logging-jakarta-commons.xml/UseCorrectExceptionLogging">
             <priority>1</priority>
       </rule>
       <rule ref="rulesets/java/logging-jakarta-commons.xml/ProperLogger">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/javabeans.xml/BeanMembersShouldSerialize">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/javabeans.xml/MissingSerialVersionUID">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/clone.xml/ProperCloneImplementation">
             <priority>2</priority>
       </rule>
       <rule ref="rulesets/java/clone.xml/CloneThrowsCloneNotSupportedException">
             <priority>3</priority>
       </rule>
       <rule ref="rulesets/java/clone.xml/CloneMethodMustImplementCloneable">
             <priority>3</priority>
       </rule>
</ruleset>



Build properties:

src.dir=src
project.name=TestApp
pmd.reports=pmd-reports


Ant Target Configuration:

 <!--Creating the required directories for pmd-->
<target name="pmd-init" description="Creates the required directories for pmd.">
<echo>******Cleaning the ${pmd.reports}******</echo>
<delete dir="${pmd.reports}" />
<echo>******Creating the required directories for pmd******</echo>
<mkdir dir="${pmd.reports}" />
</target>
<!-- PMD Configurations -->
<!--Provided the pmd library path, It can be taken from environment variable 
as well. -->
 <!--Put the above given jar files to the classpath, For me i am having all jar files in  D:/ProjectSofts/Java/pmd-bin-5.0.5/lib/-->

<path id="pmd.classpath">
<fileset dir="D:/ProjectSofts/Java/pmd-bin-5.0.5/lib/">
<include name="*.jar" />
</fileset>
</path>

<taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask"
classpathref="pmd.classpath" />

<target name="pmd" description="Run code analysis over code to check for standards." depends="pmd-init">
<echo>*****Performing PMD analysis on ${project.name}*****</echo>
<pmd rulesetfiles="pmdrulesets.xml">
<formatter type="net.sourceforge.pmd.renderers.HTMLRenderer"
toFile="${pmd.reports}/PMD-Reports.html" />
<formatter type="net.sourceforge.pmd.renderers.XMLRenderer"
toFile="${pmd.reports}/pmd.xml" />
<fileset dir="${src.dir}" defaultexcludes="yes">
<include name="com/**" />
<exclude name="com/**/*.properties" />
<exclude name="com/**/*.xml" />
</fileset>
</pmd>
<echo>*****PMD analysis report saved into ${pmd.reports}/PMD-Reports.html*****</echo>
</target>

<!--Creating the required directories for cpd-->
<target name="-cpd-init" description="Creates the required directories for cpd.">
 <echo>******Cleaning the ${basedir}/cpd-reports******</echo>
 <delete dir="${basedir}/cpd-reports" />
 <echo>******Creating the required directories for cpd******</echo>
 <mkdir dir="${basedir}/cpd-reports" />
</target>

Implementing CPD (Copy Paste Detector):

<target name="cpd" depends="-cpd-init">
 <echo>*****Performing Copy Paste Detector (CPD) analysis on ${project.name} to find the duplicate codes*****</echo>
 <taskdef name="cpd" classname="net.sourceforge.pmd.cpd.CPDTask" classpathref="pmd.classpath" />
 <cpd minimumTokenCount="100" outputFile="${basedir}/cpd-reports/cpd.xml" format="xml"
 ignoreliterals="true" ignoreIdentifiers="true">
<fileset dir="${src.dir}" defaultexcludes="yes">
  <include name="com/**" />
  <exclude name="com/**/*.properties" />
  <exclude name="com/**/*.xml" />
</fileset>
  </cpd>
  <echo>*****Copy Paste Detector (CPD) analysis report saved into ${basedir}/cpd-reports/cpd.xml*****</echo>
</target>

Note: Here ${pmd.reports} , ${src.dir} , ${project.name}, are configured in build.properties file.



Leave your comments/suggestions below, Otherwise the next time:)

Definition of equals and hashCode

Definition of equals and hashCode :

hashCode() :-

public native int hashCode();
Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by java.util.HashMap.
The general contract of hashCode is:
·         Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
·         If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
·         It is not required that if two objects are unequal according to the java.lang.Object.equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java TM programming language.) 

Equals(Object obj):-

Default Implementation in Object class:
public boolean equals(Object obj) {
        return (this == obj);
}
Indicates whether some other object is "equal to" this one. true if this object is the same as the obj argument; false otherwise.
The equals method implements an equivalence relation on non-null object references:
·         It is reflexive: for any non-null reference value x, x.equals(x) should return true.
·         It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
·         It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
·         It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
·         For any non-null reference value x, x.equals(null) should return false.
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Monday, May 26, 2014

Creating a sample dynamic web project without IDE

Creating a dynamic web project without IDE:

Step 1:

"WebProjectGenerator.bat"
Copy the below given code to notepad and save it as a batch file (WebProjectGenerator.bat )
----------------------------------------------------------------------------------------------------------------------------------
@ECHO OFF
::%USERNAME will pick the system user name.
ECHO ############################## Welcome %USERNAME% ##############################

::ECHO. will print a new line here.
ECHO.
::Get the project name from user as an input, declaring a 'Create' function
:Create
SET /P projectName=Please enter a new project name:
ECHO.

::Check if user provided project name is blank or not.If blank then error else create the project.
::Note- In batch programming we can use only 'IF' statement, it does'nt support 'IF-ELSE' statements.
IF "%projectName%"=="" ECHO You did not enter a project name! & GOTO Error
ECHO Hello, you have entered new project name as: '%projectName%'
ECHO.

::Check if user provided project name already exists or not.If exist then ask to provide the project name again
@ECHO off
IF EXIST %projectName% ECHO The name of project ('%projectName%') you have entered is already exists! & GOTO CreateAgain

SET metainf="META-INF"
SET webinf="WEB-INF"
SET indexjsp="index.jsp"
SET indexhtml="index.html"
SET webxml="web.xml"
SET lib="lib"
SET classes="classes"


ECHO Creating %projectName% ...
MKDIR %projectName%
CHDIR %projectName%

ECHO Creating %metainf% ...
MKDIR %metainf%

ECHO Creating %webinf% ...
MKDIR %webinf%

::^ Character is used to ignore checking of '<' and '>' symbols by batch compiler.
ECHO Creating %indexjsp% ...
ECHO ^<html^>^<head^>^<title^>Write your title of the page here^</title^>^</head^>^<body^>Write your code here...^</body^>^</html^> >> %indexjsp%

::^ Character is used to ignore checking of '<' and '>' symbols by batch compiler.
ECHO Creating %indexhtml% ...
ECHO  ^<html^>^<head^>^<title^>Write your title of the page here^</title^>^</head^>^<body^>Write your code here...^</body^>^</html^> >> %indexhtml%

CHDIR %webinf%

ECHO Creating %lib% ...
MKDIR %lib%

ECHO Creating %classes% ...
MKDIR %classes%

ECHO Creating %webxml% ...
ECHO ^<web-app^>^<display-name^>Name of your project^</display-name^>^<description^>Description about your project^</description^>^<welcome-file-list^>^<welcome-file^>index.html^</welcome-file^>^<welcome-file^>index.jsp^</welcome-file^>^</welcome-file-list^>^</web-app^> >> %webxml%

CD ../../

ECHO Copying ServletCompilerHelper file ...
COPY ServletCompilerHelper.bat %projectName%\%webinf%\%classes%\

GOTO Success

::Declaring a 'Error' function
:Error
ECHO.
SET /P flag=Do you want to create new project (Y/N)? or type 'exit' to exit from here:
::These multiple if statements represents OR conditions, In batch programming this is the way to check "OR" condition.
IF "%flag%"=="exit" ECHO. & GOTO EXIT 
IF "%flag%"=="EXIT" ECHO. & GOTO EXIT   
IF "%flag%"=="" ECHO Entered option is invalid! & GOTO End  
IF "%flag%"=="Y" ECHO. & GOTO Create   
IF "%flag%"=="y" ECHO. & GOTO Create  
IF "%flag%"=="N" ECHO. & GOTO End  
IF "%flag%"=="n" ECHO. & GOTO End  
IF NOT "%flag%"=="Y" ECHO Entered option is invalid, Please select (Y/N)! & GOTO Error 
IF NOT "%flag%"=="y" ECHO Entered option is invalid, Please select (Y/N)! & GOTO Error   
IF NOT "%flag%"=="N" ECHO Entered option is invalid, Please select (Y/N)! & GOTO Error  
IF NOT "%flag%"=="n" ECHO Entered option is invalid, Please select (Y/N)! & GOTO Error   

::Declaring a 'CreateAgain' function
:CreateAgain
ECHO.
SET /P createflag=Do you want to create new project (Y/N)? or type 'exit' to exit from here:
::These multiple if statements represents OR conditions, In batch programming this is the way to check "OR" condition.
IF "%createflag%"=="exit" ECHO. & GOTO EXIT 
IF "%createflag%"=="EXIT" ECHO. & GOTO EXIT   
IF "%createflag%"=="" ECHO Entered option is invalid! & GOTO End  
IF "%createflag%"=="Y" ECHO. & GOTO Create  
IF "%createflag%"=="y" ECHO. & GOTO Create  
IF "%createflag%"=="N" ECHO. & GOTO End  
IF "%createflag%"=="n" ECHO. & GOTO End  
IF NOT "%createflag%"=="Y" ECHO Entered option is invalid, Please select (Y/N)! & GOTO Error 
IF NOT "%createflag%"=="y" ECHO Entered option is invalid, Please select (Y/N)! & GOTO Error   
IF NOT "%createflag%"=="N" ECHO Entered option is invalid, Please select (Y/N)! & GOTO Error  
IF NOT "%createflag%"=="n" ECHO Entered option is invalid, Please select (Y/N)! & GOTO Error

::Declaring a 'Success' function
:Success
ECHO.
ECHO Directory structure of your project is ready,configure it as per your need, Thanks!!

::Declaring a 'End' function
:End
ECHO.
ECHO Bye Bye!!

::Declaring a 'EXIT' function
:EXIT
ECHO.
ECHO Exiting the command prompt, Bye Bye!!

EXIT
----------------------------------------------------------------------------------------------------------------------------------
Step 2:

"ServletCompilerHelper.bat"

Copy the below given code to notepad and save it as a batch file (ServletCompilerHelper.bat )

---------------------------------------------------------------------------------------------------------------------------------
@echo off
echo ############################### Welcome, %USERNAME% ###############################

:: Command to insert a line break on the screen is>> 'echo.'
echo.

echo Setting java path...
:: Command to set the bin path of jdk set in environment variables is>> 'set PATH=%JAVA_HOME%\bin;%PATH%'
set PATH=%JAVA_HOME%\bin;%PATH%
echo Java path is set successfully!
echo.
echo Below is the version of jdk installed in your machine:::::::
:: Command to display java version installed in your machine>> 'java -version'
java -version
echo.

:CompileJavaCode
SET /P flag=Do you want to compile java source code (Y/N)?
::These multiple if statements represents OR conditions, In batch programming this is the way to check "OR" condition.
IF "%flag%"=="" ECHO. & GOTO End   
IF "%flag%"=="Y" ECHO. & GOTO Compile  
IF "%flag%"=="y" ECHO. & GOTO Compile  
IF "%flag%"=="N" ECHO. & GOTO End  
IF "%flag%"=="n" ECHO. & GOTO End  
IF NOT "%flag%"=="Y" ECHO Entered option is invalid & GOTO End 
IF NOT "%flag%"=="y" ECHO Entered option is invalid & GOTO End
IF NOT "%flag%"=="N" ECHO Entered option is invalid & GOTO End
IF NOT "%flag%"=="n" ECHO Entered option is invalid & GOTO End

::Declaring a 'Compile' function
:Compile
javac -classpath %CATALINA_HOME%\lib\servlet-api.jar *.java

::Declaring a 'End' function
:End
ECHO.

ECHO Bye Bye!! 

*********************************************************************************

Step 3:

Put WebProjectGenerator.bat and ServletCompilerHelper.bat files in webapps directory/folder of Apache tomcat.

Step 4:
Run WebProjectGenerator.bat file and follow the instructions. It will create the sample web project based on the given inputs.

Step 4:
To compile the class files i.e. Java Servlets use ServletCompilerHelper.bat file. It will compile all the servlet source files into class files.

Saturday, May 17, 2014

Integrating tomcat plug-in with Eclipse [Debug web applications without restarting the server]

Installing tomcat plug-in>>


Benefit: >>  Web projects can be debugged without restarting the server. 
If  Eclipse version is grater than  4.2 (Eclipse Luna)>>> then use following plugin:



"Uqbar Tomcat XT Eclipse Plug-in"

If tomcat version is below 4.2 then use "tomcatPluginV33">>>>>>>>>>>>>>>
  1. Download the plugin from "http://www.eclipsetotale.com/tomcatPlugin.html"
  2. Unzip the tomcatPluginV33.zip in dropins or plugin folder of eclipse.



  1.  Start eclipse
  2.  Go to Window>Preferences>Tomcat
-          Set the path of tomcat server.

-          In Advance section, Unmark "Launch tomcat using security manager"

-          In JVM Settings section, Check JVM Settings are in place or not?
    


-          In Source path section, Check "Automatically compute source path"
      


-          In Tomcat manager app section, 
          ManagerApp url: http://localhost:8080/manager
          ManagerApp username: admin
          ManagerApp password:  admin

          
       

5. Click 'Apply' button.
6. Click 'Ok' button.

Integrating WebProject with tomcat>>

1      1.  Create a web project e.g. DemoServletProject
-       Directory structure of project should be like this (same should be provided in context setting below):


-       .classpath file should have following properties.

 <?xml version="1.0" encoding="UTF-8"?>
<classpath>
           <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
           <classpathentry kind="var" path="TOMCAT_HOME/lib/servlet-api.jar"/>
           <classpathentry kind="var" path="TOMCAT_HOME/lib/jasper.jar"/>
           <classpathentry kind="var" path="TOMCAT_HOME/lib/jsp-api.jar"/>
           <classpathentry kind="var" path="TOMCAT_HOME/lib/el-api.jar"/>
           <classpathentry kind="var" path="TOMCAT_HOME/lib/annotations-api.jar"/>
           <classpathentry kind="src" path="webapps/WEB-INF/src"/>
           <classpathentry kind="output" path="webapps/WEB-INF/classes"/>
</classpath>

1    2. Put the following mapping in the server.xml under <Host> element of TOMCAT_HOME.

<Context path="/DemoServletProject" reloadable="true" docBase="D:\Personal\Study\MyStuffs\Dropbox\EclipseWorkSpace\DemoServletProject\webapps"/>

2    3.  
Start tomcat from eclipse. Now you can easily debug without restarting the server.





Leave your comments/suggestions below, Otherwise the next time:)







JDBC Connection pooling with Tomcat configuration

STEPS for configuring pool....

PREREQUSITE:
Ø  APACHE-COMMONS-DBCP.JAR
Ø  APACHE-COMMONS-CONNECTION-POOL.JAR

STEP 1:  Configure DataSource

We can configure DataSource in Context.xml or Server.xml

Configuration for Context.xml

<context>
<resource auth="Container" driverclassname="com.mysql.jdbc.Driver" maxactive="20" maxidle="30" maxwait="-1" name="jdbc/mysqldb" password="root" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/users?autoReconnect=true" username="root">
</resource>
</context>

OR Configuration for Server.xml

<host>
<context docbase="Struts2SpringDemo" path="/Struts2SpringDemo" reloadable="true" source="org.eclipse.jst.jee.server:Struts2SpringDemo">
<resource auth="Container" driverclassname="com.mysql.jdbc.Driver" maxactive="20" maxidle="30" maxwait="-1" name="jdbc/mysqldb" password="root" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/users?autoReconnect=true" username="root">
</resource>
</context>
</host>

Configuration for Web.xml

<resource-ref>
<description>MySQL Connection Pool</description>
<res-ref-name>jdbc/mysqldb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>



#####################################################################
STEP 2: GETTING CONNECTION

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.naming.NamingException;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Class ConnectionManager.
 */
public class ConnectionManager {

/** The LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionManager.class);

/** The context, kept for better performance */
private static javax.naming.Context ctx;

/**
* Constructs the singleton, also obtaining the context.
*/
private static void init() throws NamingException {
ctx = new javax.naming.InitialContext();
}

/**
* Gets the connection from pool.
*
* @param dataSourceName the data source name
* @return the connection from pool
* @throws NamingException the naming exception
* @throws SQLException the SQL exception
*/
public static Connection getConnectionFromPool(String dataSourceName)
throws NamingException, SQLException {
if (dataSourceName== null) {
return null;
}

if (ctx == null) {
init();
}

final DataSource dataSrc = (DataSource) ctx.lookup("java:comp/env/"+dataSourceName);
return dataSrc.getConnection();
}

/**
* Gets the mysql connection via pool.
*
* @return the connection via pool
* @throws NamingException the naming exception
* @throws SQLException the sQL exception
*/
public static Connection getMySqlConnectionViaPool()
               throws NamingException, SQLException{
return getConnectionFromPool("jdbc/mysqldb");
}

/**
* De register database drivers.
*/
public static void deRegisterDatabaseDrivers(){
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver driver = drivers.nextElement();
try {           
DriverManager.deregisterDriver(driver); 
LOGGER.info(String.format("Deregistering jdbc driver: %s", driver));
} catch (SQLException e) {         
LOGGER.info(String.format("Error deregistering driver %s", driver), e);
}     
}
}
}

*********************************************************************************
STEP 3: USING CONNECTION

final Connection con= ConnectionManager.getConnection();
final PreparedStatement preStmt= con.prepareStatement("select * from user_profile");

final ResultSet rs=preStmt.executeQuery();

if(rs.next()){
   for(int i=1;i<=rsm.getColumnCount();i++){
       System.out.println("RECORDS: "+rsm.getColumnName(i).toLowerCase()+" |        "+rs.getString(rsm.getColumnName(i)));
    }
}


How to configure 'shared' loader directory in TOMCAT 6.x/7.x/8.x

Follow the below given steps to configure the 'shared' directory in TOMCAT 6.x/7.x/8.x :::

Shared loader config can be found in: <TomcatHome>\conf\catalina.properties. Follow the steps given below to update and configure shared loader.

Follow the steps given below:

1- Create 'shared' directory in tomcat parallel to webapps, bin, logs, conf. etc. directories.

2- Create 'classes' & 'lib' directories inside 'shared' directory.

3- Go to 'conf' directory and open 'catalina.properties' file and modify the value of 'shared.loader' to below given value.

   shared.loader=${catalina.base}/shared/classes,${catalina.base}/shared/lib/*.jar

4- Shared directory is ready to use, no you can directly add your jar files in 'lib' directory and     properties files, configs etc in 'classes' directory.

It will be automatically loaded to the classpath when server will run.

If you are using tomcat within eclipse or any other IDE, then you need to update the 'catalina.properties' found in the eclipse under "Servers" project. See the screen shot below:












Update the "shared.loader" value with full path in the "catalina.properties". See example below:

shared.loader=C:/Personal/EclipseWorkspace/Servers/Tomcat v8.0 Server at localhost-config/shared/classes,C:/Personal/EclipseWorkspace/Servers/Tomcat v8.0 Server at localhost-config/shared/lib/*.jar

Once you are done with above step then created the directories as mentioned above and place the config files which you want to load in classpath. See screen shot below:




Wednesday, April 30, 2014

Using Apache commons beanutils


Using apache-commons-beanutils to copy object state to another object:

Dependencies: 
1- commons-beanutils-1.8.0 or higher
2- commons-logging-1.1 or higher

TestBeanUtil.java

package usingBeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

import org.apache.commons.beanutils.BeanUtils;

public class TestBeanUtil {

public static void main(String[] args) throws IllegalAccessException,
InvocationTargetException {
UserModel m = new UserModel();
UserForm f = new UserForm();

m.setAddress("noida");
m.setAge(25);
m.setEmail("abhinav@gmail.com");
m.setfName("abhinav");
m.setlName("mishra");
m.setRole("admin");
m.setSalary(20000);

ArrayList<String> hobbies = new ArrayList<String>();
hobbies.add("cricket");
hobbies.add("photography");
m.setHobbies(hobbies);

ArrayList<String> depts = new ArrayList<String>();
depts.add("IT");
depts.add("admin");
m.setDepts(depts);

ArrayList<String> comps = new ArrayList<String>();
comps.add("innodata");
comps.add("fiserv");
m.setComps(comps);

System.out.println(m);

BeanUtils.copyProperties(f, m);

System.out.println(f);

}

}

UserForm.java

package usingBeanUtils;

import java.util.List;

public class UserForm {
private int age;
private int salary;
private String address;
private String email;
private String fName;
private String lName;
private List<String> depts;
private List<String> comps;
private String role;
private String webpage;

public String getWebpage() {
return webpage;
}
public void setWebpage(String webpage) {
this.webpage = webpage;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}

public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public List<String> getDepts() {
return depts;
}
public void setDepts(List<String> depts) {
this.depts = depts;
}
public List<String> getComps() {
return comps;
}
public void setComps(List<String> comps) {
this.comps = comps;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return "UserForm [age=" + age + ", salary=" + salary + ", address="
+ address + ", email=" + email + ", fName=" + fName
+ ", lName=" + lName + ", depts=" + depts + ", comps=" + comps
+ ", role=" + role + ", webpage=" + webpage + "]";
}

}

UserModel.java

package usingBeanUtils;

import java.util.List;

public class UserModel {

private int age;
private int salary;
private String address;
private String email;
private String fName;
private String lName;
private List<String> depts;
private List<String> comps;
private String role;
private List<String> hobbies;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public List<String> getDepts() {
return depts;
}
public void setDepts(List<String> depts) {
this.depts = depts;
}
public List<String> getComps() {
return comps;
}
public void setComps(List<String> comps) {
this.comps = comps;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public List<String> getHobbies() {
return hobbies;
}
public void setHobbies(List<String> hobbies) {
this.hobbies = hobbies;
}
@Override
public String toString() {
return "UserModel [age=" + age + ", salary=" + salary + ", address="
+ address + ", email=" + email + ", fName=" + fName
+ ", lName=" + lName + ", depts=" + depts + ", comps=" + comps
+ ", role=" + role + ", hobbies=" + hobbies + "]";
}
}


Result:

UserModel [age=25, salary=20000, address=noida, email=abhinav@gmail.com, fName=abhinav, lName=mishra, depts=[IT, admin], comps=[innodata, fiserv], role=admin, hobbies=[cricket, photography]]

UserForm [age=25, salary=20000, address=noida, email=abhinav@gmail.com, fName=abhinav, lName=mishra, depts=[IT, admin], comps=[innodata, fiserv], role=admin, webpage=null]