Pages

Thursday, April 9, 2015

JAXB @XmlAccessorType to cinfigure field or property access.

1.@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
Causes jaxb implementation to create binding for fields,annotated fields and property.
2.@XmlAccessorType(XmlAccessType.PROPERTY)
Causes Jaxb implementations to create bindings for property and annotated fields.
3.@XmlAccessorType(XmlAccessType.FIELD)
cause JAXB implementations to create bindings for fields and annotated property only

http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html

@XmlType(propOrder={"ID", "firstName", "lastName"})

Wednesday, March 20, 2013

Rules





Quick Search


Browse
Pages Blog Labels Attachments Bookmarks Mail Advanced Confluence Gadgets Log In Dashboard
ATS Common Services
…Home
Development Tools
Quality Control
PMD Rules

ATS 3.0 Entitlement Framework Drools Conversion Design DB2 Migration Impact analysis Development Tools Common Services Local Setup - Master Common Services Local Workshop Setup(Draft) Quality Control PMD Rules Subversion Workshop Plug-in Unit Test Relative Performance User Guide Knowledge Exchange Proces and Methodology Proof of Concept Technical Design Tools and Utils


Tools

Attachments (0) Page History E-mail Restrictions Info Link to this Page… View in Hierarchy View Wiki Markup PMD Rules







Skip to end of metadata Page restrictions apply Added by VISAR GASHI, last edited by VISAR GASHI on Dec 02, 2010 (view change) Comment:

Go to start of metadata

•Basic Rules
•Braces Rules
•Clone Rules
•Coupling Rules
•Design Rules
•Finalizer Rules
•Import Rules
•J2EE Rules
•Java Bean Rules
•Jakarta Logging Rules
•Java Logging Rules
•Optimization Rules
•Strict Exception Rules
•String Rules
•Type Resolution Rules
•Controversial Rules
Basic Rules
Rule Name Description Priority
EmptyCatchBlock Empty Catch Block finds instances where an exception is caught, but nothing is done. In most circumstances, this swallows an exception which should either be acted on or reported.
High
EmptyIfStmt Empty If Statement finds instances where a condition is checked but nothing is done about it.
Low
EmptyWhileStmt Empty While Statement finds all instances where a while statement does nothing. If it is a timing loop, then you should use Thread.sleep() for it; if it's a while loop that does a lot in the exit expression, rewrite it to make it clearer. Low
EmptyTryBlock : Avoid empty try blocks Low
EmptyFinallyBlock Avoid empty finally blocks - these can be deleted.
Medium
EmptySwitchStatements Avoid empty switch statements. Low
JumbledIncrementer Avoid jumbled loop incrementers - it's usually a mistake, and it's confusing even if it's what's intended Medium
ForLoopShouldBeWhileLoop Some for loops can be simplified to while loops - this makes them more concise. Medium
UnnecessaryConversionTemporary Avoid unnecessary temporaries when converting primitives to Strings High
OverrideBothEqualsAndHashcode : Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or override neither. Even if you are inheriting a hashCode() from a parent class, consider implementing hashCode and explicitly delegating to your superclass.
High
DoubleCheckedLocking Partially created objects can be returned by the Double Checked Locking pattern when used in Java. An optimizing JRE may assign a reference to the baz variable before it creates the object the reference is intended to point to. For more details see http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html.
High
ReturnFromFinallyBlock Avoid returning from a finally block - this can discard exceptions High
EmptySynchronizedBlock Avoid empty synchronized blocks - they're useless Low
UnnecessaryReturn Avoid unnecessary return statements Low
EmptyStaticInitializer An empty static initializer was found. Low
UnconditionalIfStatement Do not use "if" statements that are always true or always false Medium
EmptyStatementNotInLoop An empty statement (aka a semicolon by itself) that is not used as the sole body of a for loop or while loop is probably a bug. It could also be a double semicolon, which is useless and should be removed Low
BooleanInstantiation Avoid instantiating Boolean objects; you can reference Boolean.TRUE, Boolean.FALSE, or call Boolean.valueOf() instead. High
UnnecessaryFinalModifier When a class has the final modifier, all the methods are automatically final Low
CollapsibleIfStatements :Sometimes two 'if' statements can be consolidated by separating their conditions with a boolean short-circuit operator.
Medium
UselessOverridingMethod The overriding method merely calls the same method defined in a superclass Medium
ClassCastExceptionWithToArray If you need to get an array of a class from your Collection, you should pass an array of the desired class as the parameter of the toArray method. Otherwise you will get a ClassCastException.
High
AvoidDecimalLiteralsInBigDecimalConstructor : One might assume that "new BigDecimal(.1)" is exactly equal to .1, but it is actually equal to .1000000000000000055511151231257827021181583404541015625. This is so because .1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the long value that is being passed in to the constructor is not exactly equal to .1, appearances notwithstanding. The (String) constructor, on the other hand, is perfectly predictable: 'new BigDecimal(".1")' is exactly equal to .1, as one would expect. Therefore, it is generally recommended that the (String) constructor be used in preference to this one.
Low
UselessOperationOnImmutable An operation on an Immutable object (String, BigDecimal or BigInteger) won't change the object itself. The result of the operation is a new object. Therefore, ignoring the operation result is an error.
Low
MisplacedNullCheck The null check here is misplaced. if the variable is null you'll get a NullPointerException. Either the check is useless (the variable will never be "null") or it's incorrect.
High
UnusedNullCheckInEquals After checking an object reference for null, you should invoke equals() on that object rather than passing it to another object's equals() method.
Medium
AvoidThreadGroup Avoid using ThreadGroup; although it is intended to be used in a threaded environment it contains methods that are not thread safe Low
BrokenNullCheck The null check is broken since it will throw a NullPointerException itself. It is likely that you used || instead of && or vice versa. High

Braces Rules
Rule Name Description Priority
IfStmtsMustUseBraces Avoid using if statements without using curly braces High
WhileLoopsMustUseBraces Avoid using 'while' statements without using curly braces High
IfElseStmtsMustUseBraces Avoid using if..else statements without using curly braces High
ForLoopsMustUseBraces Avoid using 'for' statements without using curly braces High

Clone Rules
Rule Name Description Priority
ProperCloneImplementation Object clone() should be implemented with super.clone(). High
CloneThrowsCloneNotSupportedException The method clone() should throw a CloneNotSupportedException High
CloneMethodMustImplementCloneable The method clone() should only be implemented if the class implements the Cloneable interface with the exception of a final method that only throws CloneNotSupportedException.
High

Coupling Rules
Rule Name Description Priority
CouplingBetweenObjects This rule counts unique attributes, local variables and return types within an object. A number higher than specified threshold can indicate a high degree of coupling Medium
ExcessiveImports A high number of imports can indicate a high degree of coupling within an object. Rule counts the number of unique imports and reports a violation if the count is above the user defined threshold Medium
LooseCoupling Avoid using implementation types (i.e., HashSet); use the interface (i.e, Set) instead High

Design Rules
Rule Name Description Priority
UseSingleton If you have a class that has nothing but static methods, consider making it a Singleton. Note that this doesn't apply to abstract classes, since their subclasses may well include non-static methods. Also, if you want this class to be a Singleton, remember to add a private constructor to prevent instantiation High
SimplifyBooleanReturns Avoid unnecessary if..then..else statements when returning a boolean High
SimplifyBooleanExpressions Avoid unnecessary comparisons in boolean expressions - this complicates simple code.
High
SwitchStmtsShouldHaveDefault Switch statements should have a default label High
AvoidDeeplyNestedIfStmts Deeply nested if..then statements are hard to read High
AvoidReassigningParameters Reassigning values to parameters is a questionable practice. Use a temporary local variable instead.
High
SwitchDensity A high ratio of statements to labels in a switch statement implies that the switch statement is doing too much work. Consider moving the statements into new methods, or creating subclasses based on the switch variable High
ConstructorCallsOverridableMethod Calling overridable methods during construction poses a risk of invoking methods on an incompletely constructed object and can be difficult to discern. It may leave the sub-class unable to construct its superclass or forced to replicate the construction process completely within itself, losing the ability to call super(). If the default constructor contains a call to an overridable method, the subclass may be completely uninstantiable. Note that this includes method calls throughout the control flow graph - i.e., if a constructor Foo() calls a private method bar() that calls a public method buz(), this denotes a problem.
Medium
AccessorClassGeneration Instantiation by way of private constructors from outside of the constructor's class often causes the generation of an accessor. A factory method, or non-privatization of the constructor can eliminate this situation. The generated class file is actually an interface. It gives the accessing class the ability to invoke a new hidden package scope constructor that takes the interface as a supplementary parameter. This turns a private constructor effectively into one with package scope, and is challenging to discern. Medium
FinalFieldCouldBeStatic If a final field is assigned to a compile-time constant, it could be made static, thus saving overhead in each object at runtime High
CloseResource Ensure that resources (like Connection, Statement, and ResultSet objects) are always closed after use. High
NonStaticInitializer A nonstatic initializer block will be called any time a constructor is invoked (just prior to invoking the constructor). While this is a valid language construct, it is rarely used and is confusing.
Low
DefaultLabelNotLastInSwitchStmt By convention, the default label should be the last label in a switch statement High
NonCaseLabelInSwitchStatement A non-case label (e.g. a named break/continue label) was present in a switch statement. This legal, but confusing. It is easy to mix up the case labels and the non-case labels.
Medium
OptimizableToArrayCall A call to Collection.toArray can use the Collection's size vs an empty Array of the desired type. High
BadComparison Avoid equality comparisons with Double.NaN - these are likely to be logic errors Medium
EqualsNull Inexperienced programmers sometimes confuse comparison concepts and use equals() to compare to null High
ConfusingTernary In an "if" expression with an "else" clause, avoid negation in the test. For example, rephrase: if (x != y) diff(); else same(); as: if (x == y) same(); else diff(); Most "if (x != y)" cases without an "else" are often return cases, so consistent use of this rule makes the code easier to read. Also, this resolves trivial ordering problems, such as "does the error case go first?" or "does the common case go first?". Medium
InstantiationToGetClass Avoid instantiating an object just to call getClass() on it; use the .class public member instead.
High
IdempotentOperations Avoid idempotent operations - they are have no effect Medium
SimpleDateFormatNeedsLocale Be sure to specify a Locale when creating a new instance of SimpleDateFormat.
High
ImmutableField Identifies private fields whose values never change once they are initialized either in the declaration of the field or by a constructor. This aids in converting existing classes to immutable classes. High
UseLocaleWithCaseConversions When doing a String.toLowerCase()/toUpperCase() call, use a Locale. This avoids problems with certain locales, i.e. Turkish High
AvoidProtectedFieldInFinalClass Do not use protected fields in final classes since they cannot be subclassed. Clarify your intent by using private or package access modifiers instead High
AssignmentToNonFinalStatic Identify a possible unsafe usage of a static field. Low
MissingStaticMethodInNonInstantiatableClass A class that has private constructors and does not have any static methods or fields cannot be used High
AvoidSynchronizedAtMethodLevel Method level synchronization can backfire when new code is added to the method. Block-level synchronization helps to ensure that only the code that needs synchronization gets it.
High
MissingBreakInSwitch A switch statement without an enclosed break statement may be a bug. High
UseNotifyAllInsteadOfNotify Thread.notify() awakens a thread monitoring the object. If more than one thread is monitoring, then only one is chosen. The thread chosen is arbitrary; thus it's usually safer to call notifyAll() instead Medium
AvoidInstanceofChecksInCatchClause Each caught exception type should be handled in its own catch clause High
AbstractClassWithoutAbstractMethod The abstract class does not contain any abstract methods. An abstract class suggests an incomplete implementation, which is to be completed by subclasses implementing the abstract methods. If the class is intended to be used as a base class only (not to be instantiated directly) a protected constructor can be provided prevent direct instantiation Medium
SimplifyConditional No need to check for null before an instanceof; the instanceof keyword returns false when given a null argument Medium
CompareObjectsWithEquals Use equals() to compare object references; avoid comparing them with ==. High
PositionLiteralsFirstInComparisons Position literals first in String comparisons - that way if the String is null you won't get a NullPointerException, it'll just return false.
High
UnnecessaryLocalBeforeReturn Avoid unnecessarily creating local variables High
NonThreadSafeSingleton Non-thread safe singletons can result in bad state changes. Eliminate static singletons if possible by instantiating the object directly. Static singletons are usually not needed as only a single instance exists anyway. Other possible fixes are to synchronize the entire method or to use an initialize-on-demand holder class (do not use the double-check idiom). See Effective Java, item 48.
High
UncommentedEmptyMethod Uncommented Empty Method finds instances where a method does not contain statements, but there is no comment. By explicitly commenting empty methods it is easier to distinguish between intentional (commented) and unintentional empty methods Low
UncommentedEmptyConstructor Uncommented Empty Constructor finds instances where a constructor does not contain statements, but there is no comment. By explicitly commenting empty constructors it is easier to distinguish between intentional (commented) and unintentional empty constructors.
Low
AvoidConstantsInterface An interface should be used only to model a behaviour of a class: using an interface as a container of constants is a poor usage pattern High
UnsynchronizedStaticDateFormatter SimpleDateFormat is not synchronized. Sun recommends separate format instances for each thread. If multiple threads must access a static formatter, the formatter must be synchronized either on method or block level. High
PreserveStackTrace Throwing a new exception from a catch block without passing the original exception into the new exception will cause the true stack trace to be lost, and can make it difficult to debug effectively High
UseCollectionIsEmpty The isEmpty() method on java.util.Collection is provided to see if a collection has any elements. Comparing the value of size() to 0 merely duplicates existing behavior High
ClassWithOnlyPrivateConstructorsShouldBeFinal A class with only private constructors should be final, unless the private constructor is called by a inner class. High
EmptyMethodInAbstractClassShouldBeAbstract An empty method in an abstract class should be abstract instead, as developer may rely on this empty implementation rather than code the appropriate one Medium
SingularField This field is used in only one method and the first usage is assigning a value to the field. This probably means that the field can be changed to a local variable Low
ReturnEmptyArrayRatherThanNull For any method that returns an array, it's a better behavior to return an empty array rather than a null reference High
AbstractClassWithoutAnyMethod :If the abstract class does not provides any methods, it may be just a data container that is not to be instantiated. In this case, it's probably better to use a private or a protected constructor in order to prevent instantiation than make the class misleadingly abstract. Medium
TooFewBranchesForASwitchStatement Switches are designed complex branches, and allow branches to share treatment. Using a switch for only a few branches is ill advised, as switches are not as easy to understand as if. In this case, it's most likely is a good idea to use a if statement instead, at least to increase code readability Low

Finalizer Rules
Rule Name Description Priority
EmptyFinalizer If the finalize() method is empty, then it does not need to exist High
FinalizeOnlyCallsSuperFinalize If the finalize() is implemented, it should do something besides just calling super.finalize(). High
FinalizeOverloaded Methods named finalize() should not have parameters. It is confusing and probably a bug to overload finalize(). It will not be called by the VM High
FinalizeDoesNotCallSuperFinalize the finalize() is implemented, its last action should be to call super.finalize. High
FinalizeShouldBeProtected If you override finalize(), make it protected. If you make it public, other classes may call it.
High
AvoidCallingFinalize Object.finalize() is called by the garbage collector on an object when garbage collection determines that there are no more references to the object High

Import Rules
Rule Name Description Priority
DuplicateImports Avoid duplicate import statements High
DontImportJavaLang Avoid importing anything from the package 'java.lang'. These classes are automatically imported (JLS 7.5.3). High
UnusedImports Avoid unused import statements High
ImportFromSamePackage No need to import a type that lives in the same package.
High
TooManyStaticImports If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from (Sun 1.5 Language Guide).
High

J2EE Rules
Rule Name Description Priority
UseProperClassLoader In J2EE getClassLoader() might not work as expected. Use Thread.currentThread().getContextClassLoader() instead High
MDBAndSessionBeanNamingConvention The EJB Specification state that any MessageDrivenBean or SessionBean should be suffixed by Bean. Low
RemoteSessionInterfaceNamingConvention Remote Home interface of a Session EJB should be suffixed by 'Home'.
Low
LocalInterfaceSessionNamingConvention The Local Interface of a Session EJB should be suffixed by 'Local' Low
LocalHomeNamingConvention The Local Home interface of a Session EJB should be suffixed by 'LocalHome' Low
RemoteInterfaceNamingConvention Remote Interface of a Session EJB should NOT be suffixed Low
DoNotCallSystemExit Web applications should not call System.exit(), since only the web container or the application server should stop the JVM. High
StaticEJBFieldShouldBeFinal : According to the J2EE specification (p.494), an EJB should not have any static fields with write access. However, static read only fields are allowed. This ensures proper behavior especially when instances are distributed by the container on several JREs.
Low
DoNotUseThreads The J2EE specification explicitly forbid use of threads Medium

Java Bean Rules
Rule Name Description Priority
BeanMembersShouldSerialize If a class is a bean, or is referenced by a bean directly or indirectly it needs to be serializable. Member variables need to be marked as transient, static, or have accessor methods in the class. Marking variables as transient is the safest and easiest modification. Accessor methods should follow the Java naming conventions, i.e.if you have a variable foo, you should provide getFoo and setFoo methods.
High
MissingSerialVersionUID Classes that are serializable should provide a serialVersionUID field High

Jakarta Logging Rules
Rule Name Description Priority
UseCorrectExceptionLogging To make sure the full stacktrace is printed out, use the logging statement with 2 arguments: a String and a Throwable High
ProperLogger A logger should normally be defined private static final and have the correct class. Private final Log log; is also allowed for rare cases where loggers need to be passed around, with the restriction that the logger needs to be passed into the constructor High

Java Logging Rules
Rule Name Description Priority
MoreThanOneLogger Normally only one logger is used in each class High
LoggerIsNotStaticFinal In most cases, the Logger can be declared static and final High
SystemPrintln System.(out | err).print is used, consider using a logger. High
AvoidPrintStackTrace Avoid printStackTrace(); use a logger call instead High

Optimization Rules
Rule Name Description Priority
LocalVariableCouldBeFinal A local variable assigned only once can be declared final.
High
MethodArgumentCouldBeFinal A method argument that is never assigned can be declared final.
High
AvoidInstantiatingObjectsInLoops Detects when a new object is created inside a loop High
UseArrayListInsteadOfVector ArrayList is a much better Collection implementation than Vector High
SimplifyStartsWith Since it passes in a literal of length 1, this call to String.startsWith can be rewritten using String.charAt(0) to save some time Medium
UseStringBufferForStringAppends Finds usages of += for appending strings High
UseArraysAsList The java.util.Arrays class has a "asList" method that should be used when you want to create a new List from an array of objects. It is faster than executing a loop to copy all the elements of the array one by one
High
AvoidArrayLoops Instead of copying data between two arrays, use System.arraycopy method High
UnnecessaryWrapperObjectCreation Parsing method should be called directly instead High
AddEmptyString Finds empty string literals which are being added. This is an inefficient way to convert any type to a String High

Strict Exception Rules
Rule Name Description Priority
avoidCatchingThrowable This is dangerous because it casts too wide a net; it can catch things like OutOfMemoryError High
SignatureDeclareThrowsException It is unclear which exceptions that can be thrown from the methods. It might be difficult to document and understand the vague interfaces. Use either a class derived from RuntimeException or a checked exception.
Medium
ExceptionAsFlowControl Using Exceptions as flow control leads to GOTOish code and obscures true exceptions when debugging High
AvoidCatchingNPE Code should never throw NPE under normal circumstances. A catch block may hide the original error, causing other more subtle errors in its wake. High
AvoidThrowingRawExceptionTypes Avoid throwing certain exception types. Rather than throw a raw RuntimeException, Throwable, Exception, or Error, use a subclassed exception or error instead High
AvoidThrowingNullPointerException Avoid throwing a NullPointerException - it's confusing because most people will assume that the virtual machine threw it. Consider using an IllegalArgumentException instead; this will be clearly seen as a programmer-initiated exception High
AvoidRethrowingException Catch blocks that merely rethrow a caught exception only add to code size and runtime complexity High
DoNotExtendJavaLangError Errors are system exceptions. Do not extend them High
DoNotThrowExceptionInFinally Throwing exception in a finally block is confusing. It may mask exception or a defect of the code, it also render code cleanup uninstable.

String Rules
Rule Name Description Priority
AvoidDuplicateLiterals Code containing duplicate String literals can usually be improved by declaring the String as a constant field. High
StringInstantiation Avoid instantiating String objects; this is usually unnecessary. High
StringToString Avoid calling toString() on String objects; this is unnecessary High
InefficientStringBuffering Avoid concatenating non literals in a StringBuffer constructor or append().
High
UnnecessaryCaseChange Using equalsIgnoreCase() is faster than using toUpperCase/toLowerCase().equals()
High
UseStringBufferLength :Use StringBuffer.length() to determine StringBuffer length rather than using StringBuffer.toString().equals("") or StringBuffer.toString().length() ==. High
AppendCharacterWithChar Avoid concatenating characters as strings in StringBuffer.append High
ConsecutiveLiteralAppends Consecutively calling StringBuffer.append with String literals High
UseIndexOfChar Use String.indexOf(char) when checking for the index of a single character; it executes faster High
InefficientEmptyStringCheck String.trim().length() is an inefficient way to check if a String is really empty, as it creates a new String object just to check its size. Consider creating a static function that loops through a string, checking Character.isWhitespace() on each character and returning false if a non-whitespace character is found. High
InsufficientStringBufferDeclaration Failing to pre-size a StringBuffer properly could cause it to re-size many times during runtime. This rule checks the characters that are actually passed into StringBuffer.append(), but represents a best guess "worst case" scenario. An empty StringBuffer constructor initializes the object to 16 characters. This default is assumed if the length of the constructor can not be determined High
UselessStringValueOf No need to call String.valueOf to append to a string; just use the valueOf() argument directly. High
StringBufferInstantiationWithChar StringBuffer sb = new StringBuffer('c'); The char will be converted into int to intialize StringBuffer size Medium
UseEqualsToCompareStrings Using '==' or '!=' to compare strings only works if intern version is used on both sides
AvoidStringBufferField StringBuffers can grow quite a lot, and so may become a source of memory leak (if the owning class has a long life time).

Type Resolution Rules
Rule Name Description Priority
LooseCoupling Avoid using implementation types (i.e., HashSet); use the interface (i.e, Set) instead High
CloneMethodMustImplementCloneable The method clone() should only be implemented if the class implements the Cloneable interface with the exception of a final method that only throws CloneNotSupportedException. This version uses PMD's type resolution facilities, and can detect if the class implements or extends a Cloneable class High
UnusedImports Avoid unused import statements. This rule will find unused on demand imports, i.e. import com.foo.*. High
SignatureDeclareThrowsException It is unclear which exceptions that can be thrown from the methods. It might be difficult to document and understand the vague interfaces. Use either a class derived from RuntimeException or a checked exception. Junit classes are excluded High

Controversial Rules
Rule Name Description Priority
UnnecessaryConstructor This rule detects when a constructor is not necessary; i.e., when there's only one constructor, it's public, has an empty body, and takes no arguments.
Low
NullAssignment Assigning a "null" to a variable (outside of its declaration) is usually bad form. Some times, the assignment is an indication that the programmer doesn't completely understand what is going on in the code. NOTE: This sort of assignment may in rare cases be useful to encourage garbage collection Medium
OnlyOneReturn A method should have only one exit point, and that should be the last statement in the method.
High
UnusedModifier Fields in interfaces are automatically public static final, and methods are public abstract. Classes or interfaces nested in an interface are automatically public and static (all nested interfaces are automatically static). For historical reasons, modifiers which are implied by the context are accepted by the compiler, but are superfluous Low
AssignmentInOperand Avoid assignments in operands; this can make code more complicated and harder to read.
Low
AtLeastOneConstructor Each class should declare at least one constructor High
DontImportSun Avoid importing anything from the 'sun.*' packages. These packages are not portable and are likely to change High
CallSuperInConstructor It is a good practice to call super() in a constructor. If super() is not called but another constructor (such as an overloaded constructor) is called, this rule will not report it.
High
UnnecessaryParentheses Sometimes expressions are wrapped in unnecessary parentheses, making them look like a function call High
DefaultPackage Use explicit scoping instead of the default package private level.
High
BooleanInversion Use bitwise inversion to invert boolean values - it's the fastest way to do this. See http://www.javaspecialists.co.za/archive/newsletter.do?issue=042&locale=en_US for specific details
High
DataflowAnomalyAnalysis The dataflow analysis tracks local definitions, undefinitions and references to variables on different paths on the data flow. From those informations there can be found various problems. 1. UR - Anomaly: There is a reference to a variable that was not defined before. This is a bug and leads to an error. 2. DU - Anomaly: A recently defined variable is undefined. These anomalies may appear in normal source text. 3. DD - Anomaly: A recently defined variable is redefined. This is ominous but don't have to be a bug.
Low
AvoidFinalLocalVariable Avoid using final local variables, turn them into fields. High
AvoidUsingShortType Java uses the 'short' type to reduce memory usage, not to optimize calculation. In fact, the jvm does not have any arithmetic capabilities for the short type: the jvm must convert the short into an int, do the proper caculation and convert the int back to a short. So, the use of the 'short' type may have a greater impact than memory usage.
High
AvoidUsingVolatile Use of the keyword 'volatile' is general used to fine tune a Java application, and therefore, requires a good expertise of the Java Memory Model. Moreover, its range of action is somewhat misknown. Therefore, the volatile keyword should not be used for maintenance purpose and portability High
AvoidUsingNativeCode As JVM and Java language offer already many help in creating application, it should be very rare to have to rely on non-java code. Even though, it is rare to actually have to use Java Native Interface (JNI). As the use of JNI make application less portable, and harder to maintain, it is not recommended Medium
AvoidAccessibilityAlteration Methods such as getDeclaredConstructors(), getDeclaredConstructor(Class[]) and setAccessible(), as the interface PrivilegedAction, allow to alter, at runtime, the visilibilty of variable, classes, or methods, even if they are private. Obviously, no one should do so, as such behavior is against everything encapsulation principal stands for Medium
DoNotCallGarbageCollectionExplicitly Calls to System.gc(), Runtime.getRuntime().gc(), and System.runFinalization() are not advised. Code should have the same behavior whether the garbage collection is disabled using the option -Xdisableexplicitgc or not. Moreover, "modern" jvms do a very good job handling garbage collections. If memory usage issues unrelated to memory leaks develop within an application, it should be dealt with JVM options rather than within the code itself.
High

Labels parameters

LabelsEnter labels to add to this page: Looking for a label? Just start typing.




Powered by Atlassian Confluence 3.3.3, the Enterprise Wiki
Printed by Atlassian Confluence 3.3.3, the Enterprise Wiki.
| Report a bug | Atlassian NewsLink to this PageLink to this PageLink:Tiny Link:Wiki Markup:Close

Wednesday, April 4, 2012

NumberFormatException : hibernrate fingByNamedQuery

HIBERNATE : Unable to Iterate through a list and leading to NumberFormatException in JSTL.
oops was struggling for an hour....finally got resolved
Debug Steps
1.Checked the DAOImpl ..
batchList = this.hibernateTemplate.findByNamedQuery("getMspBatchMstrList");
it was getting the object,but the was not the type of what I need."i.e com.chase.mortgage.pojo.MspBatchMstr"
2. Tried to iterate in DAOImpl this time got the exception."ClassCastException."
Realized it is somthing to do in the mapping file.
3.Added

it did the trick...





SELECT client as CLIENT,lk.msp_transaction as TRANS_ID,msp.msp_batch_number as MSP_BATCH_NUMBER, msp.batch_seq_num as BATCH_SEQ_NUM, msp.status as STATUS
FROM TRACKER.msp_batch_mstr msp, TRACKER.transaction_lkup lk
WHERE msp.trans_id=lk.trans_id
]]>

Wednesday, February 8, 2012

Internationalization support using Spring MVC application

To make Spring MVC application supports the internationalization, register two beans :
1.SessionLocaleResolver
If you don't register the localeResolver the default AcceptHeaderLocaleResolver will be used
to resolve locale by checking the "accept-language" header from the incomming HTTP request.
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">


Note :
If there is a repated need of locale resolution add the above code else we may
get the below exception.
java.lang.UnsupportedOperationException: Cannot change HTTP accept header - use a different locale resolution strategy

2.LocaleChangeInterceptor
Register this to support multiple languages.Property paramName is used to set the locale.

class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">









Friday, September 9, 2011

Cobertura -- Code Coverage Tool

public interface Instrumentation:
This class provides services needed to instrument Java programming language code. Instrumentation is the addition of byte-codes to methods for the purpose of gathering data to be utilized by tools. Since the changes are purely additive, these tools do not modify application state or behavior. Examples of such benign tools include monitoring agents, profilers, coverage analyzers, and event loggers.

coverage analysers fall into three categories:
Insert instrumentation into the source code
Add instrumentation to the Java byte-code
Run the code in a modified JVM.

"Cobertura" add instrumentation to the java byte code.
using Maven 2:


YET TO ADD