Search

Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Java Performance and best coding Tips

1.        Try, catch block should not be in loop (unless specifically required).

2.     All Collection API Classes should be specifically reinitialized to null (since JVM has to specifically do it & GC spends much time in doing these functions).

3.        Release JDBC resources when done with tasks.

4.        Use inner join instead of multiple queries.

5.        Optimize SQL queries.

6.        Always use Dynamic SQL (Prepare Statement) rather than the static SQL like Statement.

7.        Try to avoid repeated DB calls to retrieve the same data. Instead of that retrieve the data from the table and keep the data in Java objects and use that in the subsequent call. (make Model class for that and use getter, setter methods)

8.        Avoid Select * instead give the names of fields to be selected in query (e.g. Select id,name from Student).
9.        Using getXX(int ColumnIndex) instead of getXX(String columnName): Depending upon the no of columns in your resultSet, a getXX field operation using column Index is two times as fast as than using Column Name.

10.     Do not use Vectors, instead of that use Collection classes like ArrayList.

11.     Avoid using method call as loop termination test. E.g. Don’t use list.size(), instead use store that in a temporary variable and then use the temporary variable for testing loop termination test.

12.     Avoid throwing Exception in normal flow of execution since try-catch-finally block is costly.

13.     Build proper WHERE clause in SQL SELECT for database indexing. (In left of Join select table with less no of records).

14.     Try using java Collection classes instead of array.

15.     String Concatenation: Check that For String concatenation use StringBuilder (JDK 1.5 has StringBuilder over StringBuffer) instead of String ‘+’ operator.

16.     Debugging Statements: Do not use System.out.println or printstackTrace(). Use log4j.debug() for debugging. In catch blocks add log4.error() wherever applicable.

17.     Prepare Statement: Use prepared statement for retrieving data when we have parameterized queries(insert, update, delete) else use statements.

18.     Avoid object instantiation inside Loop. If possible create object outside loop and reuse the same object inside the loop.

19.     Minimize object lifetimes. Keep the lifetimes of your data as short as possible. Place the declaration in the most nested block that first uses the data. If operator new is used, do the new just before the first use, and the set the reference to null just after the last use.

20.     Minimum use of Session variables in the code instead set variables in Request. Set session variables as null after use.

21.     The constants are not static we can make it final for better performance(e.g. if we have fix value for variable than make it final private void testMethod(final int id){}).

22.     Apply Transactions wherever necessary.

23.     Apply Query Caching if is required as per functionality.

24.     Minimize data conversions or Castings

25.     Try to use primitive java objects instead Wrapper classes as like Wrapper classes (i.e. Integer) allocate large data amounts in memory.

26.     Replace a long if-else-if chain by a switch if possible; this is much faster.

27.     Declaring a method as private, final, or static makes calls to it faster. Of course, you should only do this when it makes sense in the application.

28.     Do not add JavaScript directly in the JSP Code; instead include JS File and include in Jsp (e.g <script src=”include/common.js”></script>).

29.     Use STRUTS, JSTL specific UI Tag Library in JSP pages.

30.     Exceptions are taken care in the code and highest levels of Exceptions are routed to Error Page; others are properly logged using logger.


Spring Dependency Injection - An Introductory Tutorial / example

This article discusses dependency injection in a tutorial format. It covers some of the newer features of Spring DI such as annotations, improved XML configuration and more.
Dependency Injection
Dependency Injection (DI) refers to the process of supplying an external dependency to a software component. DI can help make your code architecturally pure. It aids in design by interface as well as test-driven development by providing a consistent way to inject dependencies. For example, a data access object (DAO) may depend on a database connection. Instead of looking up the database connection with JNDI, you could inject it. 

One way to think about a DI container like Spring is to think of JNDI turned inside out. Instead of an object looking up other objects that it needs to get its job done (dependencies), a DI container injects those dependent objects. This is the so-called Hollywood Principle, “Don't call us” (lookup objects), “we’ll call you” (inject objects).
 

If you have worked with CRC cards you can think of a dependency as a collaborator, i.e., an object that another object needs to perform its role.
 
Let's say that you have an automated teller machine (ATM) and it needs the ability to talk to a bank. It uses what it calls a transport object to do this. In this example, a transport object handles the low-level communication to the bank.
 

This example could be represented by either of the  two interfaces as follows:
 

AutomatedTellerMachine interface
package com.arcmind.springquickstart;

import java.math.BigDecimal;

public interface AutomatedTellerMachine {
void deposit(BigDecimal bd);
void withdraw(BigDecimal bd);
}

ATMTransport interface
package com.arcmind.springquickstart;

public interface ATMTransport {
void communicateWithBank(byte [] datapacket);
}
Now the AutomatedTellerMachine needs a transport to perform its intent, namely withdraw money and deposit money. To carry out these tasks, the AutomatedTellerMachine may depend on many objects and collaborates with its dependencies to complete the work. 

An implementation of the AutomatedTellerMachine may look like this:
AutomatedTellerMachine implementation:
package com.arcmind.springquickstart;

import java.math.BigDecimal;

public class AutomatedTellerMachineImpl implements AutomatedTellerMachine{

private ATMTransport transport;

public void deposit(BigDecimal bd) {
...
transport.communicateWithBank(...);
}

public void withdraw(BigDecimal bd) {
...
transport.communicateWithBank(...);
}

public void setTransport(ATMTransport transport) {
this.transport = transport;
}

}
The AutomatedTellerMachineImpl does not know or care how the transport withdraws and deposits money from the bank. This level of indirection allows us to replace the transport with different implementations such as in the following example:

Three example transports: SoapAtmTransport, StandardAtmTransport and SimulationAtmTransport
package com.arcmind.springquickstart;

public class SoapAtmTransport implements ATMTransport {

public void communicateWithBank(byte[] datapacket) {
...
}

}
package com.arcmind.springquickstart;

public class StandardAtmTransport implements ATMTransport {

public void communicateWithBank(byte[] datapacket) {
...
}

}
package com.arcmind.springquickstart;

public class SimulationAtmTransport implements ATMTransport {

public void communicateWithBank(byte[] datapacket) {
...
}

}

Notice the possible implementations of the ATMTransport interface. The AutomatedTellerMachineImpl does not know or care which transport it uses. Also, for testing and developing, instead of talking to a real bank, notice that you can use the SimulationAtmTransport.
Download Spring examples source code

An Introduction to Spring AOP

This article discusses Spring AOP in a tutorial format. It covers some of the newer features of Spring AOP like annotations, improved XML configuration and more. It builds on the DIIntroTutorial. It is meant as a simple introduction to AOP. Enough information so you –can use AOP on a project.
Spring x AOP 
For some, AOP seems like voodoo magic. For others, AOP seems like a cureall. For now, let's just say that AOP is a tool that you want in your developer tool box. It can make seemingly impossible things easy.
The first time that I used AOP was with Spring's transaction management support. I did not realize I was using AOP. I just knew Spring could apply EJB-style declarative transaction management to POJOs. It was probably –three to six months before I realized that I was using was Spring's AOP support. The Spring framework truly brought AOP out of the esoteric closet into the main stream light of day.
You can think of AOP as a way to apply services (called cross-cutting concerns) to objects. AOP encompasses more than this, but this is where it gets used mostly in the main stream.
I've using AOP to apply caching services, transaction management, resource management, etc. to any number of objects in an application. It is not a panacea, but it certainly fits a lot of otherwise difficult use cases.
You can think of AOP as a dynamic decorator design pattern. The decorator pattern allows additional behavior to be added to an existing class by wrapping the original class and duplicating its interface and then delegating to the original. See this articdecorator pattern Decorator Pattern for more detail about the decorator design pattern.
Sample Application Revisited
or this introduction to AOP, let's take a simple example. Let's apply security services to our Automated Teller Machine example from the first DI example from the first tutorial in this series.
Let's say when a user logs into a system that a SecurityToken is created that carries the user's credentials, and before methods on objects get invoked, we want to check to see if the user has credentials to invoke these methods.
In a web application, you could write a ServletFilter,that stored this SecurityToken in HttpSession and then on every request retrieved the token from Session and put it into a ThreadLocal variable where it could be accessed from a SecurityService that you could implement.
Perhaps the objects that needed the SecurityService could access it as follows:
public void deposit(BigDecimal bd) {
/* If the user is not logged in, don't let them use this method */
if(!securityManager.isLoggedIn()){
throw new SecurityViolationException();
}
/* Only proceed if the current user is allowed. */

if (!securityManager.isAllowed("AutomatedTellerMachine", operationName)){
throw new SecurityViolationException();
}
...

transport.communicateWithBank(...);
}
In our ATM example, the above might work out well, but imagine a system with thousands of classes that needed security. Now imagine, the way we check to see if a user is logged is changed. If we put this code into every method that needed security, then we could possibly have to change this a thousand times if we changed the way we checked to see if a user was logged in.
What we want to do instead is to use Spring to create a decorated version of the –ATM? bean. The decorated version would add the additional behavior to the atm object without changing the actual implementation of the atm.
Spring does this by creating what is called an AOP proxy. An AOP proxy is like a dynamic decorator. Underneath the covers Spring can generate a class at runtime (the AOP proxy) that has the same interface as our AutomatedTellerMachine. The AOP proxy wraps our existing atm object and provides additional behavior by delegating to a list of method interceptors. The method interceptors provide the additional behavior and are similar to ServletFilters but for methods instead of requests.
Thus, before we added Spring AOP, our atm example was like Figure

After we added AOP support, we now get an AOP proxy that applies the securityAdvice to the atm as show in figure



You can see that the AOP proxy implements the AutomatedTellerMachine interface. When the client object looks up the atm and starts invoking methods instead of executing the methods directly, it executes the method on the proxy, which then delegates the call to a series of method interceptors called “Advice,” which eventually invoke the actual atm instance (now called atmTarget).
Let's actually look at the code for this example.
For this example, we will use a simplified SecurityToken that gets stored into a ThreadLocalvariable, but one could imagine one that was populated with data from a database or an LDAP server or some other source of authentication and authorization.
Here is the SecurityToken, which gets stored into a ThreadLocal variable, for this example:
package com.arcmind.springquickstart.security;

/**
* @author Richard Hightower
*
*/
public class SecurityToken {

private boolean allowed;
private String userName;

public SecurityToken() {

}



public SecurityToken(boolean allowed, String userName) {
super();
this.allowed = allowed;
this.userName = userName;
}



public boolean isAllowed(String object, String methodName) {
return allowed;
}


/**
* @return Returns the allowed.
*/
public boolean isAllowed() {
return allowed;
}
/**
* @param allowed The allowed to set.
*/
public void setAllowed(boolean allowed) {
this.allowed = allowed;
}
/**
* @return Returns the userName.
*/
public String getUserName() {
return userName;
}
/**
* @param userName The userName to set.
*/
public void setUserName(String userName) {
this.userName = userName;
}
}
The SecurityService stores the SecurityToken into the ThreadLocal variable and then delegates to it to see if the current user has access to perform the current operation on the current object as follows:
package com.arcmind.springquickstart.security;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;


/**
* @author Richard Hightower
*
*/
@Service ("defaultSecurityService")
@Qualifier("manager")
public class SecurityService {

private static ThreadLocal<SecurityToken> currentToken = newThreadLocal<SecurityToken>();

public static void placeSecurityToken(SecurityToken token){
currentToken.set(token);
}

public void clearSecuirtyToken(){
currentToken.set(null);
}

public boolean isLoggedIn(){
SecurityToken token = currentToken.get();
return token!=null;
}

public boolean isAllowed(String object, String method){
SecurityToken token = currentToken.get();
return token.isAllowed();
}

public String getCurrentUserName(){
SecurityToken token = currentToken.get();
if (token!=null){
return token.getUserName();
}else {
return "Unknown";
}
}

}
package com.arcmind.springquickstart.security;

/**
* @author Richard Hightower
*
*/
public class SecurityViolationException extends RuntimeException {

/**
*
*/
private static final long serialVersionUID = 1L;

}
To remove the security code out of the AutomatedTellerMachineImpl class and any other class that needs security, we will write an Aspect to intercept calls and perform security checks before the method call. To do this we will create a method interceptor (known is AOP speak as an advice) and intercept method calls on the atm object.
Here is the SecurityAdvice class which will intercept calls on the AutomatedTellerMachineImpl class.
package com.arcmind.springquickstart.security;



import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
* @author Richard Hightower
*/
@Component
public class SecurityAdvice {

@Autowired(required=true)
@Qualifier ("manager")
private SecurityService securityManager;

public void checkSecurity(ProceedingJoinPoint joinPoint) throwsThrowable {

/* If the user is not logged in, don't let them use this method */
if(!securityManager.isLoggedIn()){            
throw new SecurityViolationException();
}

/* Get the name of the method being invoked. */
String operationName = joinPoint.getSignature().getName();
/* Get the name of the object being invoked. */
String objectName = joinPoint.getThis().getClass().getName();


/*
* Invoke the method or next Interceptor in the list,
* if the current user is allowed.
*/
if (!securityManager.isAllowed(objectName, operationName)){
throw new SecurityViolationException();
}

joinPoint.proceed();
}


/**
* @return Returns the manager.
*/
public SecurityService getSecurityManager() {
return securityManager;
}
/**
* @param manager The manager to set.
*/
public void setSecurityManager(SecurityService manager) {
this.securityManager = manager;
}

}
The checkSecurity method of SecurityAdvice is the method that implements the advice. You can think of advice as the decoration that we want to apply to other objects. The objects getting the decoration are called advised objects.
Notice that the SecurityService gets injected into the SecurityAdvice and the checkSecuritymethod uses the SecurityService to see if the user is logged in and the user has the rights to execute the method.
An instance of ProceedingJoinPoint, namely joinPoint, is passed as an argument tocheckSecurity. The ProceedingJoinPoint has information about the method that is being called and provides control that determines if the method on the advised object's methods gets invoked (AutomatedTellerMachineImpl.withdraw and AutomatedTellerMachineImpl.deposit). IfjoinPoint.proceed() is not called, then the wrapped method of the advised object (withdraw ordeposit) is not called. (The proceed method causes the actual decorated method to be invoked or the next interceptor in the chain.)
To apply an Advice like SecurityAdvice to an advised object, you need a pointcut. A pointcut is like a filter that picks the objects and methods that get decorated. For this example, we will configure the pointcut into the Spring application context with the aop:config, aop:aspect, aop:pointcut, andaop:around tags as follows:.
<?xml version="0" encoding="UTF-8"?>
xsi:schemaLocation="
">


<context:component-scan base-package="com.arcmind.springquickstart"/>

<aop:config>
<aop:aspect id="securityAspect" ref="securityAdvice">
<aop:pointcut id="atmLayer"  expression="bean(atm)"/>
<aop:around  pointcut-ref="atmLayer" method="checkSecurity"/>
</aop:aspect>
</aop:config>

</beans>
Because we have component scan turned on with the context:component-scan tag, theSecurityAdvice get installed in the Spring application context under the default bean name SecurityAdvice. (The default bean name is the simple name of the class). The atm bean is registered using the component scan as well as follows:
@Service ("atm")
public class AutomatedTellerMachineImpl implements AutomatedTellerMachine{

@Autowired (required=true)
@Qualifier ("default")
private ATMTransport transport;
 The aop:pointcut tag defines the pointcut rule using this AspectJ expression bean(atm), which means decorate the methods of the bean named atm. If you want to decorate all beans whose names ends in Service, you would use
bean(*Service)
To see a full description of the AspectJ pointcut language see pointcuts. Note that the bean name pointcut can take you far.
You apply this pointcut and advice around the atm methods using the aop:around tag by referring to the atmLayer. You defined with the aop:pointcut. Then when the atm is looked up with AtmMain (listed below), instead of getting the original atm, you get an AOP proxy, which is like a dynamic decorator.
Figure 3 shows graphically how the objects and advice are found and applied.

Let's complete our example by reviewing the AtmMain main method that looks up the atm out of the Spring applicatoinContext.
Let's review AtmMain as follows:
package com.arcmind.springquickstart.atm;

import java.math.BigDecimal;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.arcmind.springquickstart.security.SecurityService;
import com.arcmind.springquickstart.security.SecurityToken;

public class AtmMain {

public static void simulateLogin() {
SecurityService.placeSecurityToken(new SecurityToken(true,"Rick Hightower"));
}

public static void simulateNoAccess() {
SecurityService.placeSecurityToken(new SecurityToken(false,"Tricky Lowtower"));
}      

public static void main(String[] args) throws Exception {

simulateLogin();

ApplicationContext appContext = newClassPathXmlApplicationContext(
"classpath:./spring/applicationContext.xml");

AutomatedTellerMachine atm = (AutomatedTellerMachine) appContext
.getBean("atm");

atm.withdraw(new BigDecimal("00"));

atm.deposit(new BigDecimal("1000"));

System.out.println("done");

}

}
Before we added AOP support when we looked up the atm, we looked up the object directly as shown in figure  Now that we applied AOP, when we look up the object, we get what is in figure  When we look up the atm in the application context, we get the AOP proxy that applies the decoration (advice, method interceptor) to the atm target by wrapping the target and delegating to it after it invokes the series of method interceptors.
Conclusion
AOP is neither a cureall or voodoo magic but a powerful tool that needs to be in your bag of tricks. The Spring framework has brought AOP to the main stream masses, and Spring 5 has simplified using AOP.
You can use Spring AOP to apply services (called cross-cutting concerns) to objects. AOP need not seem like a foreign concept, as it is merely a more flexible version of the decorator design pattern. With AOP you can add additional behavior to an existing class without writing a lot of wrapper code. This can be a real time saver when you have a use case where you need to apply a crosscutting concern to a slew of classes.
Download Spring examples source code