Monday, December 4, 2017

Spring 4 CORE , MVC,JDBC,BATCH,CACHE



SPRING CORE
____________________________________________________________________

Spring IOC :(loads/wire/dispense on request )beans, manages life cycle ,uses DI to inject beans
Spring beans are Objects that are instantiates/wired /managed by the Spring IoC container.
Container creates them using  configuration metadata supplied by user
The way of create/configure/inject/obtain/access spring Beans.
SCOPES 
UNIVERSAL:Singleton,Prototype: 
WEB-AWARE SPRING APPLICATION CONTEXT:Request,Session,Global-session: 
Explain Bean lifecycle in Spring framework?

(INSTANTIATE | POPULATE | PRE INITALIZATION | POST INITIALIZATION|  READY TO USE)
1) spring container finds the bean’s definition 
2) Populate properties: Using the DI, 
Set Bean Name: If the bean implements BeanNameAware interface, 
4)Set Bean factory: If Bean implements BeanFactoryAware interface, 
5)Pre Initialization: Also called post process of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
6)Initialize beans: If the bean implements IntializingBean, its afterPropertySet() method is called. 
7)Post Initialization: – If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
8)Ready to use: Now the bean is ready to use by the application


10) Explain Spring Bean lifecycle?

The life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required.
Spring bean factory is responsible for managing the life cycle of beans created through spring container. The life cycle of beans consist of call back methods which can be categorized broadly in two groups:
  1. Post initialization call back methods
  2. Pre destruction call back methods
Spring framework provides following 4 ways for controlling life cycle events of bean:
  • InitializingBean and DisposableBean callback interfaces
  • Other Aware interfaces for specific behavior
  • Custom init() and destroy() methods in bean configuration file
  • @PostConstruct and @PreDestroy annotations
For example, customInit() and customDestroy() methods are example of life cycle method.
    "demoBean" class="com.howtodoinjava.task.DemoBean" init-method="customInit" destroy-method="customDestroy">
Inner beans
https://stackoverflow.com/questions/24213823/anyway-to-inject-autowire-an-inner-class-into-an-outer-class


INTERFACES

____________________________________________________________________

1)BeanFactory interface provides an advanced configuration mechanism capable of managing objects of any nature

2)ApplicationContext interface builds on top of the BeanFactory (it is a sub-interface).
 It adds other functionality such as easier integration with 
Spring’s AOP features
message 
resource handling (for use in internationalization), 
event propagation, and 
application-layer specific contexts such as the WebApplicationContext for use in web applications.

BeanNameAware: BeanNameAware can be used to set bean name. The class has to implement interface BeanNameAware and override its method setBeanName(String beanName).
https://www.concretepage.com/spring/example_beannameaware_spring

BeanFactoryAware: BeanFactoryAware can be used to set bean factory. The BeanFactoryAware interface is used during the initialization of an ApplicationContext. It has been used in Spring 2 to customize the weaving of beans before they get initialized. An example would be in order to additionally add pointcuts at load time (LTW) e.g. for autogenerated find methods of DAOs. Another usage could be to load a minimized context for test, to speed up tests (lazy initialization would be a better practice)

Initialization callbacks:

Implementing the org.springframework.beans.factory.InitializingBean interface allows a bean to perform initialization work after all necessary properties on the bean have been set by the container. The InitializingBeaninterface specifies exactly one method:
void afterPropertiesSet() throws Exception;
BeanPostProcessors:Associated with the bean, Spring calls postProcesserBeforeInitialization()


BeanPostProcessors interface provides methods that you can implement to have your own instantiation logic.Also you can write your own logic after spring IOC finishes instantiating, configuring, and initializing a bean by plugging in one or more BeanPostProcessor implementations.
You can configure multiple BeanPostProcessors and also can decide the order in which they will run relative to each other by setting order property but foe that BeanPostProcessors  have to implement ordered interface.
Extensionof BeanPostProcessor is BeanFactoryPostProcessor interface which allows direct modification of bean definitions before a bean is instantiated

An ApplicationContext will automatically register and process a bean that implements either of these interfaces, but a BeanFactory would have to have a BeanPostProcessor or BeanFactoryPostProcessor registered with it programatically.






Destruction callbacks:

Implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a callback when the container containing it is destroyed. The DisposableBean interface specifies a single method:
void destroy() throws Exception;
appContext.registerShutdownHook();
you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods.

If you have too many beans having initialization and or destroy methods with the same name, you don’t need to declare init-method and destroy-method on each individual bean.


xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-init-method="init"
default-destroy-method="destroy"
>


ApplicationContextAware :Implementing ApplicationContextAware interface makes sense for example when an object requires access to a set of collaborating beans. Note that configuration via bean references is preferable to implementing this interface just for bean lookup purposes.

This interface can also be implemented if an object needs access to file resources, i.e. wants to call getResource, wants to publish an application event, or requires access to the MessageSource. However, it is preferable to implement the more specific ResourceLoaderAwareApplicationEventPublisherAware or MessageSourceAware interface in such a specific scenario.

ResourceLoaderAware

ApplicationEventPublisherAware or 

MessageSourceAware






Difference between BeanFactory and ApplicationContext?

BeanFactory 
  1. is like a factory class that contains a collection of beans
  2. holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.
  3.  is able to create associations between collaborating objects as they are instantiated.
  4. removes the burden of configuration from bean itself and the beans client
  5. BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.

On the surface, an application context is same as a 

  • bean factory.Both
  • load bean definitions,
  • wire beans together, 

and dispense beans upon request. But it also provides:
  1. A means for resolving text messages, including support for internationalization.
  2. A generic way to load file resources.
  3. Events to beans that are registered as listeners.
The three commonly used implementations of ApplicationContext are:
  1. ApplicationContext context
     = new ClassPathXmlApplicationContext(“bean.xml”);
    new FileSystemXmlApplicationContext(“bean.xml”);

TYPES OF CONTEXT

____________________________________________________________________


 ApplicationContext:
   ClassPathApplicationContext:
    FileSystemXmlApplicationContext-
    XmlWEBApplicationContext
:  AnnotationConfigApplicationContext
     AnnotationWebConfigApplicationContext 
Loading bean definitions from xml files

XmlWebApplicationContext:
implementation of WebApplicationContext interface 

AnnotationConfigApplicationContext
·      It loads bean definitions from an XML file contained within a web application. By default it loads the configuration from file "/WEB-INF/applicationContext.xml".

AnnotationConfigApplicationContext :from java classes annotated with @Configuration, instead of xml files.

AnnotationWebConfigApplicationContext:Creates WebApplication context using @configurtaion


Ways to configure Spring in application


WAYS TO CONFIGURE SPRING IN APPLICATION
____________________________________________________________________

  1. XML Based Configuration
  2. Annotation-based configuration|Annotation Based DI
  3. Java-based configuration
  4. Java-based configuration

@Configuration// CONFIGURED
@ComponentScan(basePackages = "com.howtodoinjava")// ENABLED SCANNING
public class AppConfig
{
    @Bean//Methods instantiates/configures/initalizes a new object
    public MyService myService() {
        return new MyServiceImpl();
    }
}
IS SAME AS 

[beans|bean id="myService" class="com.howtodoinjava.services.MyServiceImpl"|beans]
INSTANTIAION .
public static void main(String[] args) {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
    MyService myService = ctx.getBean(MyService.class);
    myService.doStuff();
}

If you are using above configuration in a web application then you will be using AnnotationConfigWebApplicationContext class. This implementation may be used when configuring the Spring ContextLoaderListener servlet listener, Spring MVC DispatcherServlet etc.



Dependency Injection 


9) What is Spring Annotation-based Configuration?

1)To configure the dependency injection using annotations.   
2)Bean wiring is moved the bean configuration into the component class itself 
2 a)By using annotations on the relevant class, method, or field declaration. 

Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file. So consider to have following configuration file in case you want to use any annotation in your Spring application.
'<'beans'>''<'context:annotation-config'>''<'beans'>'
Once  is configured, you can start annotating your code to indicate that Spring should automatically wire values into properties, methods, and constructors.
Few important annotations which you will be using in this type of configuration are :
  1. @Required : The @Required annotation applies to bean property setter methods.
  2. @Autowired : The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties.
  3. @Qualifier : The @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired.
  4. JSR-250 Annotations : Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations.
_________________________________________________________________ Aspect Oriented Programming.



Spring Core Model:-
https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans

What is method injection 

Name some of the important Spring Modules?
Some of the important Spring Framework modules are:
    1. Spring Context – for dependency injection.
    2. Spring AOP – for aspect oriented programming.
    3. Spring DAO – for database operations using DAO pattern
    4. Spring JDBC – for JDBC and DataSource support.
    5. Spring ORM – for ORM tools support such as Hibernate
    6. Spring Web Module – for creating web applications.
    7. Spring MVC – Model-View-Controller implementation for creating web applications, web services etc.
Core dependencies 
Framework jar
  • antlr-2.7.2.jar
  • spring-aop-3.2.2.RELEASE.jar
  • spring-aspects-3.2.2.RELEASE.jar
  • spring-beans-3.2.2.RELEASE.jar
  • spring-context-support-3.2.2.RELEASE.jar
  • spring-context-3.2.2.RELEASE.jar
  • spring-core-3.2.2.RELEASE.jar
  • spring-expression-3.2.2.RELEASE.jar
  • commons-logging-1.1.1.jar


  • This Core Module is the base module of a spring frame work application.This Core module will provide the following information to the spring programmers.



IOC and Dependency Injection


What is IOC and Dependency Injection?
Inversion of control (IoC) is a programming technique in which object coupling is bound at run time by an assembler object and is typically not known at compile time.
What is Dependency Injection?

Dependency Injection is a way to achieve Inversion of control (IoC) in our application by moving objects binding from compile time to runtime. We can achieve IoC through 
Factory Pattern, Template Method Design Pattern, Strategy Pattern and Service Locator pattern too.
  • There are 3 types of dependency Injection.
    • Constructor Injection : Dependencies are provided as constructor parameters.
    • Setter Injection : Dependencies are assigned through JavaBeans properties (ex: setter methods).
    • Interface Injection: Injection is done through an interface
    • This Core Module will provide the following information to the spring programmers.
  1. The way of creating spring Beans.
  2. The way of Configuring Spring Beans.
  3. The way of injecting the dependencies.
  4. The way of obtaining a spring container object.
  5. The way of accessing the spring beans from container

SPRING MVC
____________________________________________________________________


SPRING LIFE CYCLE



  • When use AbstractAnnotationConfigDispatcherServletInitializer and WebApplicationInitializer?

  • With the release of the Servlet 3.0 spec it became possible to configure your Servlet Container with (almost) no xml. For this there is the ServletContainerInitializer in the Servlet specification. In this class you can register filters, listeners, servlets etc. as you would traditionally do in a web.xml.
    Spring provides a an implementation the SpringServletContainerInitializer which knows how to handle WebApplicationInitializer classes. Spring also provides a couple of base classes to extend to make your life easier the AbstractAnnotationConfigDispatcherServletInitializer is one of those.

    AbstractAnnotationConfigDispatcherServletInitializer registers a

     ContextLoaderlistener (optionally) and a 

    DispatcherServlet 

    and allows you to easily add configuration classes to load for both classes and to apply filters to the DispatcherServlet and to provide the servlet mapping.
    The WebMvcConfigurerAdapter is for configuring Spring MVC, the replacement of the xml file loaded by the DispatcherServlet for configuring Spring MVC. The WebMvcConfigurerAdapter should be used for a @Configuration class.
    @Configuration     THIS IS INCORRECT APPROACH
    @EnableWebMvc
    public class WebConfiguration 
        extends WebMvcConfigurerAdapter implements WebApplicationInitializer
    { ... }
    I wouldn't recommend mixing those as they are basically 2 different concerns. The first is for configuring the servlet container, the latter for configuring Spring MVC.
    You would want to split those into 2 classes.
    For the configuration.
    @Configuration
    @EnableWebMvc
    public class WebConfiguration extends WebMvcConfigurerAdapter { ... }
    For bootstrapping the application.
    public class MyWebApplicationInitializer
        extends AbstractAnnotationConfigDispatcherServletInitializer
    {
    
        protected Class[] getRootConfigClasses() {
            return new Class[] {RootConfig.class};
        }
    
        protected Class[] getServletConfigClasses()  {
            return new Class[] {WebConfiguration.class};
        }
    
        protected String[] getServletMappings() {
            return new String[] {"/"};
        }
    
    }
    An added advantage is that you now can use the convenience classes provided by Spring instead of manually configuring the DispatcherServlet and/or ContextLoaderListener.
  • ContextLoaderListener

    • Spring web applications have 2 application contexts.
      • DispatcherServlet loads beans containing web components such as controllers, view resolvers, handler mappings, etc.
      • ContextLoaderListener loads the other beans in the application that are typically used by service and data access layers.
    • loads the beans for the application (not web related beans)

  •  Input types to request handler method in controller

    1. No input parameter
    2. Model
    3. java.util.Map
    4. Parameters annotated with @RequestParam
    5. Parameters annotated with @PathVariable
    6. POJO populated with form parameters
    7. Errors - used for form validation

  • Output/return types from request handler method in controller


    1. void
    2. String
      1. logical view name (“car”)
      2. physical view name (/WEB-INF/jsp/car.jsp)
      3. special view names (redirect:/cars/7)
      4. ModelAndView
    3. Model
    4. Map
    5. ModelMap
    6. View
    7. @ResponseBody
    8. @ModelAttribute


  • 6.To map to method & provide type of request
    LEVEL: [CLASS|METHOD]
    @RequestMappingvalue={”method1/{id}/{name},method2”}
                                              method ={”RequestMethod.GET,RequestMethod.POST”}
                                              produces = {“application/json”,”application/xml”}
                                              consumes = {“text/html”,…..})
    public @ResponseBody String method1(@PathVariable(“id”) long id,
                                                                                      @PathVariable(“name”)String name,@RequestParam(value=”paramname”, required=true))

SPRING JDBC
____________________________________________________________________

org.springframework.jdbc.core.JdbcTemplate 

UPDATE: insert/update/delete
_________________________________________________________________________________ 

jdbcTemplate.update(query);  
 String query="insert into employee values(    '"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')";  
   return jdbcTemplate.update(query);  

 String query="update employee set      name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' "; 
 return jdbcTemplate.update(query);      String query="delete from employee where id='"+e.getId()+"' "
 return jdbcTemplate.update(query);  


EXECUTE: 

insert:preparestatement:preparedstatementCallback:doPreparedStatment
select: ResultSetExtractor:extractData
select:Rowmapper:mapRow
_________________________________________________________________________________ 

String query="insert into employee values(?,?,?)";     return jdbcTemplate.execute(query,new PreparedStatementCallback()
public Boolean doInPreparedStatement(PreparedStatement ps)  
throws SQLException, DataAccessException {  
ps.setInt(1,e.getId());  
ps.setString(2,e.getName());  
ps.setFloat(3,e.getSalary());        
return ps.execute(); 
__________________________________________________________________________ 
public List query(String sql, RowMapper rse)is used to fetch records using RowMapper.

  public List getAllEmployees(){  
 return jdbctemplate.query("select * from employee",new ResultSetExtractor
 public List extractData(ResultSet rs) throws SQLException,DataAccessException {  
 List list=new ArrayList();  
while(rs.next()){  
Employee e=new Employee();  
e.setId(rs.getInt(1));  
e.setName(rs.getString(2));  
e.setSalary(rs.getInt(3));  
list.add(e);  
return list;  
___________________________________________________________________________ 
return jdbctemplate.query("select * from employee",new RowMapper(){  
 public Employee mapRow(ResultSet rs, int rownumber) throws SQLException 
Employee e=new Employee();  
e.setId(rs.getInt(1));       return e;  
__________________________________________________________________________ 

NAMEDPARAMETERJDBCTEMPALTE: 

EXECUTE:
_______________________________________________________________________ 

String query="insert into employee values (:id,:name,:salary)";  
Map map=new HashMap(); 
map.put("id",e.getId());  
map.put("name",e.getName());
map.put("salary",e.getSalary());
jdbctemplate.execute(query,map,new PreparedStatementCallback() : doInPreparedStatement  
SIMPLEJDBCTEMPALTE: 

EXECUTE:SimpleJdbcTemplate template; 
return jdbctemplate.update(query,e.getName(),e.getId());
________________________________________________________________________ 



      
public class Main {
  public static void main(String args[]) throws Exception {ApplicationContext ac = new ClassPathXmlApplicationContext("context.xml", Main.class);
DataSource dataSource = (DataSource) ac.getBean("dataSource");
//STEP1: GET DATA SOURCE BEAN
 // DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource");
//STEP2:  PASS IT TO JDBCTEMPLATE
 JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
//STEP3:
 String machaceksName = (String) jdbcTemplate.query(new PreparedStatementCreator() {
      public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
        return connection. prepareStatement("select first_name from customer where last_name like ?");
            .
      }
    }, new PreparedStatementSetter() {
      public void setValues(PreparedStatement preparedStatement) throws SQLException {
        preparedStatement.setString(1, "Mach%");
      }
    }, new ResultSetExtractor() {
      public Object extractData(ResultSet resultSet) throws SQLException, DataAccessException {
        if (resultSet.next()) {
          return resultSet.getLong(1);
        }
        return null;
      }
    });
    System.out.println(machaceksName);



SPRING CACHE
___________________________________________



Caching Annotations

  1. @Cacheable : Triggers cache population
  2. @CachePut : Updates the cache, without interfering with the method execution
  3. @CacheEvict : Triggers cache eviction[removing items from cache]
  4. @Caching : Regroups multiple cache operations to be applied on a method
  5. @CacheConfig : Shares some common cache-related settings at class-level
  6. @EnableCaching : Configuration level annotation, enables Cachin

@Cacheable

value : Specifies the name of the cache being used.
key : Used to specify the key for cache storage. You can use SpEL to specify the key.
condition : Conditional Caching. Item will be cached only if the condition mentioned in ‘condition’ met. Note that condition applies to method argument and evaluated before method execution.


@Cacheable(value="products", key="#product.name", condition="#product.price<500 code="">)
public Product findProduct(Product product){
..
return aproduct;
}


@Cacheable


@CachePut(value = "products", key = "#product.name" , unless="#result==null")
public Product updateProduct(Product product) {
    logger.info("");
    for(Product p : products){
        if(p.getName().equalsIgnoreCase(product.getName()))
            p.setPrice(product.getPrice());
            return p;
    }
    return null;
}


@CacheEvict



@CacheEvict(value = "products", key = "#product.name")
public void refreshProduct(Product product) {
    //This method will remove only this specific product from 'products' cache.
}  
@CacheEvict(value = "products", allEntries = true)
public void refreshAllProducts() {
    //This method will remove all 'products' from cache, say as a result of flush-all API.
}  



Class level annotation :



@CacheConfig(value="products", keyGenerator="myKeyGenerator")
class MyClass{
    @Cacheable
    public Product findProduct(Product product) {...
        ..
        return aproduct;
    }
    @Cacheable(value="items")
    public Product findSoldProduct(Product product) {...
        ..
        return aproduct;
    }
}







CacheMangers

Spring's central cache manager SPI. Allows for retrieving named Cache regions.

AbstractCacheManager,


 AbstractTransactionSupportingCacheManager,


 CaffeineCacheManager,


 CompositeCacheManager,

 ConcurrentMapCacheManager,


 EhCacheCacheManager,

CacheManager backed by an EhCache CacheManager.


 JCacheCacheManager,

CacheManager implementation backed by a JCache CacheManager.


 NoOpCacheManager


SimpleCacheManager,

Simple cache manager working against a given collection of caches. Useful for testing or simple caching declarations.


 TransactionAwareCacheManagerProxy

This code has been picked from net for personnal learning purpose


import org.springframework.cache.CacheManager;  
 import org.springframework.cache.annotation.EnableCaching;  
 import org.springframework.cache.ehcache.EhCacheCacheManager;  
 import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;  
 import org.springframework.context.annotation.Bean;  
 import org.springframework.context.annotation.ComponentScan;  
 import org.springframework.context.annotation.Configuration;  
 import org.springframework.core.io.ClassPathResource;  
 @EnableCaching  
 @Configuration  
 @ComponentScan(basePackages = "")  
 public class AppConfig {  
      /*       
      //Suitable for basic use cases, no persistence capabilities or eviction contracts.  
      @Bean  
      public CacheManager cacheManager() {  
          // configure and return an implementation of Spring's CacheManager SPI  
          SimpleCacheManager cacheManager = new SimpleCacheManager();  
          cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("products")));  
          return cacheManager;  
        }  
   */  
      //EhCache based CacheManager, most commonly used in Enterprise applications.  
      @Bean  
      public CacheManager cacheManager() {  
           return new EhCacheCacheManager(ehCacheCacheManager().getObject());  
      }  
      @Bean  
      public EhCacheManagerFactoryBean ehCacheCacheManager() {  
           EhCacheManagerFactoryBean factory = new EhCacheManagerFactoryBean();  
           factory.setConfigLocation(new ClassPathResource("ehcache.xml"));  
           factory.setShared(true);  
           return factory;  
      }  
 }  


import org.springframework.cache.annotation.CacheEvict;  
 import org.springframework.cache.annotation.Cacheable;  
 import org.springframework.stereotype.Service;  
 import com.websystique.spring.model.Product;  
 @Service("productService")  
 public class ProductServiceImpl implements ProductService{  
      @Override  
      @Cacheable("products")  
      public Product getByName(String name) {  
           slowLookupOperation();  
           return new Product(name,100);  
      }  
      @CacheEvict(value = "products", allEntries = true)  
      public void refreshAllProducts() {  
           //This method will remove all 'products' from cache, say as a result of flush API.  
      }       
      public void slowLookupOperation(){  
            try {  
            long time = 5000L;  
            Thread.sleep(time);  
          } catch (InterruptedException e) {  
            throw new IllegalStateException(e);  
          }  
      }  
 }  











---------------------------------------------------------------------------------
import org.springframework.cache.annotation.Cacheable;

import org.springframework.stereotype.Service;





 import org.springframework.context.annotation.AnnotationConfigApplicationContext;  
 public class CacheDemoA {  
      public static void main(String[] args) {  
           AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();  
           ctx.register(AppConfigA.class);  
           ctx.refresh();  
           BookAppA bookAppA = ctx.getBean(BookAppA.class);  
           //Calling getBook method first time.  
           System.out.println(bookAppA.getBook().getBookName());  
           //Calling getBook method second time.  
           //This time, method will not execute because result is cached with "mycache"  
           System.out.println(bookAppA.getBook().getBookName());  
           ctx.close();  
      }  
 }  
 
 import org.springframework.cache.annotation.Cacheable;  
 import org.springframework.stereotype.Service;  
 @Service  
 public class BookAppA {  
      Book book = new Book();  
      @Cacheable(value = "mycache")  
      public Book getBook() {  
           System.out.println("Executing getBook method...");  
           book.setBookName("Mahabharat");  
           return book;  
      }  
 } 


 import org.springframework.cache.CacheManager;  
 import org.springframework.cache.annotation.EnableCaching;  
 import org.springframework.cache.guava.GuavaCacheManager;  
 import org.springframework.context.annotation.Bean;  
 import org.springframework.context.annotation.ComponentScan;  
 import org.springframework.context.annotation.Configuration;  
 import com.google.common.cache.CacheBuilder;  
 @Configuration  
 @ComponentScan("com.")  
 @EnableCaching  
 public class AppConfigA {  
   @Bean  
   public CacheManager cacheManager() {  
     GuavaCacheManager cacheManager = new GuavaCacheManager("mycache");  
     CacheBuilder


SPRING DATA:
_____________________________________________________________________________Configurations :
package com.concretepage;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.oxm.castor.CastorMarshaller;

@Configuration
public class AppConfig {
 @Bean
 public Converter getHandler(){
   Converter handler= new Converter();
   handler.setMarshaller(getCastorMarshaller());
   handler.setUnmarshaller(getCastorMarshaller());
   return handler;
 }
 @Bean
 public CastorMarshaller getCastorMarshaller() {
   CastorMarshaller castorMarshaller = new CastorMarshaller();
   Resource resource = new ClassPathResource("mapping.xml");
   castorMarshaller.setMappingLocation(resource);
   return castorMarshaller;
 }
}


XML:


p


    
  Spring OXM and Castor
    
name="com.concretepage.bean.Country"> xml="country-info" /> name="id" type="int">name="id" node="attribute"/> name="countryName" type="string"> name="country-name" node="element"/> name="pmName" type="string"> name="pm-name" node="element"/>




Converter 

package com.concretepage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;

public class Converter {
    private Marshaller marshaller;
    private Unmarshaller unmarshaller;

    public void setMarshaller(Marshaller marshaller) {
        this.marshaller = marshaller;
    }

    public void setUnmarshaller(Unmarshaller unmarshaller) {
        this.unmarshaller = unmarshaller;
    }
    //Converts Object to XML file
    public void doMarshaling(String fileName, Object graph) throws IOException {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fileName);
            marshaller.marshal(graph, new StreamResult(fos));
        } finally {
         fos.close();
        }
    }
    //Converts XML to Java Object
    public Object doUnMarshaling(String fileName) throws IOException {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(fileName);
            return unmarshaller.unmarshal(new StreamSource(fis));
        } finally {
         fis.close();
        }
    }
}


Preview:
package com.concretepage;

import java.io.IOException;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.concretepage.bean.Country;

public class RunApplication {
 public static void main(String[] args) throws IOException {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(AppConfig.class);
    ctx.refresh();
    Converter converter = ctx.getBean(Converter.class);
    //Perform Marshaling ->object->xml
    Country country = new Country();
    country.setId(100);
    country.setCountryName("India");
    country.setPmName("ABC");
    converter.doMarshaling("country.xml", country);
    System.out.println("Marshaling performed");
    //Perform UnMarshaling xml -> object
    country = (Country)converter.doUnMarshaling("country.xml");
    System.out.println("After UnMarshaling Data is: id:"+ country.getId()+", CountryName:"+country.getCountryName());
 }
SPRING QUARTZ


____________________________________________________________




JOB :ANY CLASS IMPLEMENTING JOB INTERFACE| EXECUTE METHOD
J


JOBDETAILFACTORYBEAN : TAKES JOB AS PARAMETER AND CREATES JOB DETAIL OBJECT WITH ALL REQUIRED PARAMETERS


   @Bean  
      public JobDetailFactoryBean jobDetailFactoryBean(){  
           JobDetailFactoryBean factory = new JobDetailFactoryBean();  
           factory.setJobClass(MyJobTwo.class);  
           Map map = new HashMap();  
           map.put("name", "RAM");  
           map.put(MyJobTwo.COUNT, 1);  
           factory.setJobDataAsMap(map);  
           factory.setGroup("mygroup");  
           factory.setName("myjob");  
           return factory;  


JOBDETAIL OBJECT IS OBTAINED THROUGH MethodInvokingJobDetailFactoryBean

   @Bean  
      public MethodInvokingJobDetailFactoryBean methodInvokingJobDetailFactoryBean() {  
           MethodInvokingJobDetailFactoryBean obj = new MethodInvokingJobDetailFactoryBean();  
           obj.setTargetBeanName("jobone");  
           obj.setTargetMethod("myTask");  
           return obj;  
      } 


SIMPLETRIGGERFACTORYBEAN
  @Bean  
      public SimpleTriggerFactoryBean simpleTriggerFactoryBean(){  
           SimpleTriggerFactoryBean stFactory = new SimpleTriggerFactoryBean();  
           stFactory.setJobDetail(methodInvokingJobDetailFactoryBean().getObject());  
           stFactory.setStartDelay(3000);  
           stFactory.setRepeatInterval(30000);  
           stFactory.setRepeatCount(3);  
           return stFactory;  
CRONTRIGGERFACTORYBEAN

@Bean  
      public CronTriggerFactoryBean cronTriggerFactoryBean(){  
           CronTriggerFactoryBean stFactory = new CronTriggerFactoryBean();  
           stFactory.setJobDetail(jobDetailFactoryBean().getObject());  
           stFactory.setStartDelay(3000);  
           stFactory.setName("mytrigger");  
           stFactory.setGroup("mygroup");  
           stFactory.setCronExpression("0 0/1 * 1/1 * ? *");  
           return stFactory;  
      }  

SCHEDULARFACTORYBEAN


STEPS TO CONFIGURE SPRING QUARTZ

CONFIGIRATION
 import java.util.HashMap;  
 import java.util.Map;  
 import org.springframework.context.annotation.Bean;  
 import org.springframework.context.annotation.ComponentScan;  
 import org.springframework.context.annotation.Configuration;  
 import org.springframework.scheduling.quartz.CronTriggerFactoryBean;  
 import org.springframework.scheduling.quartz.JobDetailFactoryBean;  
 import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;  
 import org.springframework.scheduling.quartz.SchedulerFactoryBean;  
 import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;  
 import com.concretepage.job.MyJobTwo;



Preview:
import java.util.HashMap;  
 import java.util.Map;  
 import org.springframework.context.annotation.Bean;  
 import org.springframework.context.annotation.ComponentScan;  
 import org.springframework.context.annotation.Configuration;  
 import org.springframework.scheduling.quartz.CronTriggerFactoryBean;  
 import org.springframework.scheduling.quartz.JobDetailFactoryBean;  
 import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;  
 import org.springframework.scheduling.quartz.SchedulerFactoryBean;  
 import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;  
 import com.concretepage.job.MyJobTwo;  
 @Configuration   
 @ComponentScan("com.concretepage")   
 public class QuartzConfiguration {  
      @Bean  
      public MethodInvokingJobDetailFactoryBean methodInvokingJobDetailFactoryBean() {  
           MethodInvokingJobDetailFactoryBean obj = new MethodInvokingJobDetailFactoryBean();  
           obj.setTargetBeanName("jobone");  
           obj.setTargetMethod("myTask");  
           return obj;  
      }  
      @Bean  
      public SimpleTriggerFactoryBean simpleTriggerFactoryBean(){  
           SimpleTriggerFactoryBean stFactory = new SimpleTriggerFactoryBean();  
           stFactory.setJobDetail(methodInvokingJobDetailFactoryBean().getObject());  
           stFactory.setStartDelay(3000);  
           stFactory.setRepeatInterval(30000);  
           stFactory.setRepeatCount(3);  
           return stFactory;  
      }  
      @Bean  
      public JobDetailFactoryBean jobDetailFactoryBean(){  
           JobDetailFactoryBean factory = new JobDetailFactoryBean();  
           factory.setJobClass(MyJobTwo.class);  
           Map map = new HashMap();  
           map.put("name", "RAM");  
           map.put(MyJobTwo.COUNT, 1);  
           factory.setJobDataAsMap(map);  
           factory.setGroup("mygroup");  
           factory.setName("myjob");  
           return factory;  
      }  
      @Bean  
      public CronTriggerFactoryBean cronTriggerFactoryBean(){  
           CronTriggerFactoryBean stFactory = new CronTriggerFactoryBean();  
           stFactory.setJobDetail(jobDetailFactoryBean().getObject());  
           stFactory.setStartDelay(3000);  
           stFactory.setName("mytrigger");  
           stFactory.setGroup("mygroup");  
           stFactory.setCronExpression("0 0/1 * 1/1 * ? *");  
           return stFactory;  
      }  
      @Bean  
      public SchedulerFactoryBean schedulerFactoryBean() {  
           SchedulerFactoryBean scheduler = new SchedulerFactoryBean();  
           scheduler.setTriggers(simpleTriggerFactoryBean().getObject(),cronTriggerFactoryBean().getObject());  
           return scheduler;  
      }  
 } 




________________________________________________________________________





SPRING BATCH
________________________________________________________________





SCENARIOS


Business Scenarios
• Commit batch process periodically
• Concurrent batch processing: parallel processing of a job
• Staged, enterprise message-driven processing
• Massively parallel batch processing
• Manual or scheduled restart after failure
• Sequential processing of dependent steps (with extensions to workflow-driven batches)
• Partial processing: skip records (e.g. on rollback)
• Whole-batch transaction: for cases with a small batch size or existing stored procedures/scripts


Job Stereotypes ... 5
2.3.1. Job ... 6



Job
A job is represented by a Spring bean that implements the Job interface and contains all of the information necessary to define the operations performed by a job. A job configuration is typically contained within a Spring XML configuration file and the job's name is determined by the "id" attribute associated with the job configuration bean. The job configuration contains

JobInstance
A JobInstance refers to the concept of a logical job run. Let's consider a batch job that should be run once at the end of the day, such as the 'EndOfDay' job from the diagram above. There is one 'EndOfDay' Job, but each individual run of the Job must be tracked separately. In the case of this job, there will be one logical JobInstance per day.


JobParameters
A JobInstance refers to the concept of a logical job run. Let's consider a batch job that should be run once at the end of the day, such as the 'EndOfDay' job from the diagram above. There is one 'EndOfDay' Job, but each individual run of the Job must be tracked separately. In the case of this job, there will be one logical JobInstance per day.


JobExecution

A JobExecution refers to the technical concept of a single attempt to run a Job. An execution may end in failure or success, but the JobInstance corresponding to a given execution will not be marked as complete unless the execution completes successfully. For instance, if we have a JobInstance of the EndOfDay job for 01-01-2008, as described above, that fails to successfully complete its work the first time it is run, when we attempt to run it again (with the same job parameters of 01-01-2008), a new job execution will be created.




Step
A StepExecution represents a single attempt to execute a Step. Using the example from JobExecution, if there is a JobInstance for the "EndOfDayJob", with JobParameters of "01-01-2008" that fails to successfully complete its work the first time it is run, when it is executed again, a new StepExecution will be created. Each of these step executions may represent a different invocation of the batch framework, but they will all correspond to the same JobInstance, just as multiple JobExecutions belong to the same JobInstance.


ExecutionContext
An ExecutionContext represents a collection of key/value pairs that are persisted and controlled by the framework in order to allow developers a place to store persistent state that is scoped to a StepExecution. For those familiar with Quartz, it is very similar to JobDataMap. The best usage example is restart.
executionContext.putLong(getKey(LINES_READ_COUNT), reader.getPosition());



JobRepositary
JobRepository is the persistence mechanism for all of the Stereotypes mentioned above.

public interface JobRepository {
  public JobExecution createJobExecution(Job job, JobParameters jobParameters)
       throws JobExecutionAlreadyRunningException, JobRestartException;
void saveOrUpdate(JobExecution jobExecution);
    void saveOrUpdate(StepExecution stepExecution);
    void saveOrUpdateExecutionContext(StepExecution stepExecution);
    StepExecution getLastStepExecution(JobInstance jobInstance, Step step);
    int getStepExecutionCount(JobInstance jobInstance, Step step);
}




JobLauncher
JobLauncher represents a simple interface for launching a Job with a given set of JobParameters:


JobLocator
JobLocator represents an interface for locating a Job:








ItemReader
ublic interface ItemReader {
  Object read() throws Exception;
//calling it returns one Item, returning null if no more items are left.



  void mark() throws MarkFailedException;
.    Mark() will be called before reading begins. 


  void reset() throws ResetFailedException;
.    reset at anytime will position the ItemReader to its position when mark was last called. 


}



Flatfile|xml|database





ItemWriter
public interface ItemWriter {
  void write(Object item) throws Exception;
It will attempt to write out the item passed in as long as it is open.

  void flush() throws FlushFailedException;
  void clear() throws ClearFailedException;
it is expected that an ItemWriter will perform some type of buffering. flush will empty the buffer by actually writing the items out, whereas clear will simply throw the contents of the buffer away.
}

















ItemStream

public interface ItemStream {
  void open(ExecutionContext executionContext) throws StreamException;
  void update(ExecutionContext executionContext);
  void close(ExecutionContext executionContext) throws StreamException;
}












Tasklet
A Tasklet represents the execution of a logical unit of work, as defined by its implementation of the Spring Batch provided Tasklet interface. A Tasklet is useful for encapsulating processing logic that is not natural to split into read-(transform)-write phases, such as invoking a system command or a stored procedure.








Flat files
1)Delimited
2)Fixed Length


FieldSet ~resultset

provides consistent parsing of flat file input


String[] tokens = new String[]{"foo", "1", "true"};
FieldSet fs = new DefaultFieldSet(tokens);
String name = fs.readString(0);
int value = fs.readInt(1);
boolean booleanValue = fs.readBoolean(2);

FlatFileItemReader

The three most important of these properties are
Resource,
Resource resource = new FileSystemResource("resources/trades.csv");

FieldSetMapper
and LineTokenizer.

FieldSetMapper
public interface FieldSetMapper {
  public Object mapLine(FieldSet fs);
}

which takes a FieldSet object and maps its contents to an object.

LineTokenizer

n abstraction for turning a line of input into a FieldSet is necessary. In Spring Batch, this is called a LineTokenizer:

public interface LineTokenizer {
  FieldSet tokenize(String line);
}

DelmitedLineTokenizer - Used for files that separate records by a delimiter. The most common is a comma, Spring Batch 1.0 17
public interface FieldSetMapper {
  public Object mapLine(FieldSet fs);
}
public interface LineTokenizer {
  FieldSet tokenize(String line);
}
 
ItemReaders and ItemWriters but pipes or semicolons are often used as well
• FixedLengthTokenizer - Used for tokenizing files where each record is separated by a 'fixed width' that must be defined per record.
• PrefixMatchingCompositeLineTokenizer - Tokenizer that determines which among a list of Tokenizers should be used on a particular line by checking against a prefix.






FlatFileItemWriter
file writing must have a way to aggregate multiple fields into a single string for writing to a file. In Spring Batch this is the LineAggregator:


LineAggregator
public interface LineAggregator {
  public String aggregate(FieldSet fieldSet);
}
DelimitedLineAggregator and FixedLengthLineAggregator.




public void write(Object data) throws Exception {
  FieldSet fieldSet = fieldSetCreator.mapItem(data);
  getOutputState().write(lineAggregator.aggregate(fieldSet) + LINE_SEPARATOR);
}






Job is composed of one to many Steps. Each Step can work in two modes :
  • Chunk Oriented Processing or READ-PROCESS-WRITE mode: Step needs to read from a resource , process the data and then write back the process data to a resource. In this approach, Step has exactly one ItemReader(reader which reads from a resource, be it file, database, messaging queue etc.), ItemProcessor ( provides a hook to apply business logic) and ItemWriter (writer which writes to a resource, be it file, database, messaging queue etc).
  • TASKLET mode: Step has to perform a single operation (be it just sending email, executing a stored procedure, cleaning up files older than x days, etc). In this approach Step includes a Tasklet interface which have only one method execute which can perform above mentioned activities.
    A job is launched via JobLauncher, and JobRepository stores the meta data about the currently running process.Note that Steps can be chained together.

Spring Batch needs two infrastructure components:
  • Job repository — To store the state of jobs (finished / failed / currently running)
  • Job launcher — To create the state of a job before launching it




Spring Batch- Read a CSV file and write to an XML file

1. Add dependencies
2.  Prepare the input flat file and corresponding domain object /mapped POJO
3.Create a FieldSetMapper
FieldSetMapper is responsible for mapping each field form the input to a domain object





public class ExamResultFieldSetMapper implements FieldSetMapper{
    public ExamResult mapFieldSet(FieldSet fieldSet) throws BindException {
        ExamResult result = new ExamResult();
        result.setStudentName(fieldSet.readString(0));
        result.setDob(new LocalDate(fieldSet.readDate(1,"dd/MM/yyyy")));
        result.setPercentage(fieldSet.readDouble(2));
        return result;

    }
4. Create an ItemProcessor
ItemProcessor is Optional, and called after item read but before item write. It gives us the opportunity to perform a business logic on each item.In our case, for example, we will filter out all the items whose percentage is less than 60.So final result will only have records with percentage >= 60.
import org.springframework.batch.item.ItemProcessor; 
import com.websystique.springbatch.model.ExamResult;
 @Override
    public ExamResult process(ExamResult result) throws Exception {
        System.out.println("Processing result :"+result);


5. Add a Job listener(JobExecutionListener)
Job listener is Optional and provide the opportunity to execute some business logic before job start and after job completed.For example setting up environment can be done before job and cleanup can be done after job completed.
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;

    @Override
    public void beforeJob(JobExecution jobExecution) {
        startTime = new DateTime();
        System.out.println("ExamResult Job starts at :"+startTime);
    }
    @Override
    public void afterJob(JobExecution jobExecution) {



Step 7: Create Main application to finally run the job



import
org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionException;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


        
ApplicationContext context = new ClassPathXmlApplicationContext("spring-batch-context.xml");
        JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
        Job job = (Job) context.getBean("examResultJob");
        try {
            JobExecution execution = jobLauncher.run(job, new JobParameters());
            System.out.println("Job Exit Status : "+ execution.getStatus());
        } catch (JobExecutionException e) {
            System.out.println("Job ExamResult failed");
            e.printStackTrace();

-----------------------------------------------------------------
Writing to database

public class ExamResultItemPreparedStatementSetter implements ItemPreparedStatementSetter {
    public void setValues(ExamResult result, PreparedStatement ps) throws SQLException {
        ps.setString(1, result.getStudentName());
        ps.setDate(2, new java.sql.Date(result.getDob().toDate().getTime()));
        ps.setDouble(3, result.getPercentage());
    }
}



SPRING DATA
________________________________________________________________________








-->
28.SPRING DATA: WHAT IS SPRING DATA ?
The goal of Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.


29. SPRING DATA: List important interfaces

Repositary [marker interface]
·      The CrudRepository provides sophisticated CRUD functionality for the entity class that is being managed.
ü  Saves an entity
ü  Finds an entity with id
ü  Return all entities
ü  Return  the number of entities
ü  Deletes the given entity
ü  Indicates whether an entity with the given id exists
public interface CrudRepository<T, ID extends Serializable>     extends Repository<T, ID> {   
  <extends T> S save(S entity);    
  T findOne(ID primaryKey); //find element by ID           
Iterable<T> findAll(); //findAll elment by ID             
Long count();     //count                
void delete(T entity);   //delete the entry             
boolean exists(ID primaryKey);        // … more functionality omitted. }



30. SPRING DATA : PagingAndSortingRepository

public interface PagingAndSortingRepository
  extends CrudRepository {

  Iterable findAll(Sort sort);

  Page findAll(Pageable pageable);
}

PagingAndSortingRepository repository = // … get access to a bean
Page users = repository.findAll(new PageRequest(1, 20));


public interface UserRepository extends CrudRepository {

  Long deleteByLastname(String lastname);

  List removeByLastname(String lastname);

}































_______________________________________________________________________

Extra

Good Reads:


https://www.javacodegeeks.com/2014/02/spring-jms-processing-messages-within-transactions.html

https://www.javaworld.com/article/2077963/open-source-tools/distributed-transactions-in-spring--with-and-without-xa.html?page=2


https://stackoverflow.com/questions/27736082/transaction-management-in-spring-jms-listener


https://www.javacodegeeks.com/2014/02/spring-jms-processing-messages-within-transactions.html

http://www.jakubkorab.net/2011/08/configuring-activemq-transactions-in-spring.html

https://ourcraft.wordpress.com/2008/07/01/spring-and-local-jms-transactions/


http://websystique.com/spring/spring-4-jms-activemq-example-with-jmslistener-enablejms/



______________________________________________________
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:util="http://www.springframework.org/schema/util"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:lang="http://www.springframework.org/schema/lang"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
                           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
                           http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd">

   

   


No comments:

Post a Comment