google Analytics

Thursday, September 23, 2010

REST Authentication and Authorization example

Authentication and Authorization in JAX-RS
REST Authentication and Authorization example

Folder Structure

 

example Programe
=============================================================
 

package com.test;
import java.net.URI;
import java.net.URISyntaxException;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;

import org.jboss.resteasy.annotations.Form;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
/**
 *
 * @author NathA1
Spring will use any class annotated with the @Controller annotation as
a Controller in Spring MVC support
The @Produces is used to map a client request and match it up to the client's Accept header.
The Accept HTTP header is sent by the client and defines the media types the client prefers to
receive from the server
 */
@RolesAllowed({"admin","tomcat"})
@Controller
@Path(ProductsResource.CONTACTS_URL)
public class ProductsResource
{
   public static final String CONTACTS_URL = "/products";
   @Autowired
   ProductService service;

   @RolesAllowed("admin")
   @GET
   @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   @Path("data")
   public Products getAll()
   {
      return service.getAll();
   }

   @PermitAll
   @PUT
   @POST
   @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   @Path("data")
   public Response saveProduct(@Context UriInfo uri, Product product)
         throws URISyntaxException
   {
       System.out.println("Inside -->> saveProduct");
      service.save(product);
      URI newURI = UriBuilder.fromUri(uri.getPath()).path(product.getLongName()).build();
      return Response.created(newURI).build();
   }

   @RolesAllowed("tomcat")
   @GET
   @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   @Path("data/{shortName}")
   public Product get(@PathParam("shortName") String shortName)
   {
      return service.getProduct(shortName);
   }

   @PermitAll
   @POST
   @PUT
   @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
   @Produces(MediaType.TEXT_HTML)
   public ModelAndView saveContactForm(@Form Product product)
         throws URISyntaxException
   {
       System.out.println("Inside -->> saveContactForm");
      service.save(product);
      return viewAll();
   }
  

   @PermitAll
   @GET
   @Produces(MediaType.TEXT_HTML)
   public ModelAndView viewAll()
   {
      // forward to the "contacts" view, with a request attribute named
      // "contacts" that has all of the existing contacts
      return new ModelAndView("products", "products", service.getAll());
   }
}
/**
 * END OF PROGRAM
 * =======================================================================
package com.test;
import java.util.ArrayList;
import java.util.Collection;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
When a class is annotated with a @XmlRootElement annotation, RESTEasy
will select the JAXBXmlRootElementProvider. This provider handles basic marhaling and and
unmarshalling of custom JAXB entities
@author Anish Nath
 *
 */

@XmlRootElement
public class Products
{
   private Collection<Product> products;
   public Products()
   {
      this.products = new ArrayList<Product>();
   }
   public Products(Collection<Product> products)
   {
      this.products = products;
   }
   /**
    *  @XmlElement annotation to embed other JAXB-annotated classes.
    * @return
    */
   @XmlElement(name="product")
   public Collection<Product> getProducts()
   {
      return products;
   }
   public void setProducts(Collection<Product> product)
   {
      
      this.products = product;
   }
}

/**
 * END OF PROGRAM
 * =======================================================================
 */
package com.test;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Service;
/**
 *
 * Anish Nath
The @Service annotation marks classes that implement a part of the business
logic of the application
 *
 */
@Service
public class ProductService
{
   private Map<String, Product> productMap = new ConcurrentHashMap<String, Product>();
   public void save(Product product)
   {
       productMap.put(product.getShortName(), product);
   }
   public Product getProduct(String shortName)
   {
      return productMap.get(shortName);
   }
   public Products getAll()
   {
      return new Products(productMap.values());
   }
}

/**
 * END OF PROGRAM
 * =======================================================================
 */
 Web.xml
<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/products/*</url-pattern>
    </servlet-mapping>
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>product creation</web-resource-name>
            <url-pattern>/products</url-pattern>
            <http-method>POST</http-method>
        </web-resource-collection>
        <auth-constraint>
            <role-name>admin</role-name>
        </auth-constraint>
    </security-constraint>
    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>jaxrs</realm-name>
    </login-config>
    <security-role>
        <role-name>admin</role-name>
    </security-role>

</web-app>

==========================================================================
springmvc-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    ">
    <context:component-scan base-package="com.test" />
    <context:annotation-config />
    <import resource="classpath:springmvc-resteasy.xml" />
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>


==========================================================================================
tomcat-users.xml
<?xml version="1.0" encoding="UTF-8"?>
<tomcat-users>
  <role rolename="manager"/>
  <role rolename="tomcat"/>
  <role rolename="admin"/>
  <role rolename="role1"/>
  <user password="tomcat" roles="tomcat,role1" username="both"/>
  <user password="tomcat" roles="tomcat" username="tomcat"/>
  <user password="admin" roles="admin,manager" username="admin"/>
  <user password="tomcat" roles="role1" username="role1"/>
</tomcat-users>
===========================================================================================

spring rest services
spring rest example

RESTfull web service Example
restlet spring security
RestEasy with EJB Integration Example
RESTEasy and Spring MVC

ANish

RestEasy with EJB Integration Example

RestEasy with EJB Example
Using Restfull webservices with EJB

Deployed as EAR folder Structure




=============================================================
 

The code in the WAR project configures RESTEasy. It also registers the EJBs defined
by the EJB project with the JAX-RS runtime.

resteasy.jndi.resources, A comma delimited list of JNDI names which reference objects you want to register as
JAX-RS resources

================================================================================
 <?xml version="1.0" encoding="UTF-8"?>
<web-app>
   <display-name>Created Web Application</display-name>
   <context-param>
      <param-name>resteasy.jndi.resources</param-name>
      <param-value>Spring-RESTEasy/ProductResourceBean/local
      </param-value>
   </context-param>
   <listener>
      <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
   </listener>
   <servlet>
      <servlet-name>Resteasy</servlet-name>
      <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
   </servlet>
   <servlet-mapping>
      <servlet-name>Resteasy</servlet-name>
      <url-pattern>/*</url-pattern>
   </servlet-mapping>
</web-app>


=============================================================================

package com.test;
import javax.ejb.Local;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
/**
 *
 * @author Anish Nath
 *
 */
@Local
@Path("/")
public interface ProductResource
{
   @GET
   @Path("hello")
   @Produces("text/plain")
   String sayHelloWorld();

   @PUT
   @Path("hello")
   @Consumes("text/plain")
   void sayHelloWorld(String body);

}

/**
 * ======================================================================
 * END OF PROGRAM
 */

 package com.test;
import javax.ejb.Stateless;
/**
 *
 * @author ANish Nath
 *
 */
@Stateless(mappedName="productBean")
public class ProductResourceBean implements ProductResource
{
   public String sayHelloWorld()
   {
      System.out.println("sayHelloWorld()");
      return "HelloWorld";
   }
   public void sayHelloWorld(String body)
   {
      System.out.println("sayHelloWorld(anish)");
      System.out.println(body);
   }
}


/**
 * ======================================================================
 *
 */

====================

Helloworld With RestEasy WebServices
JBoss RESTEasy and Spring MVC
REST with Spring
http://opensourceframework.blogspot.com/2010/09/resteasy-and-spring-mvc.html
ANish

Wednesday, September 22, 2010

RESTEasy and Spring MVC

JBoss RESTEasy and Spring MVC
REST with Spring



example
=============================================================
 

package com.test;
import java.net.URI;
import java.net.URISyntaxException;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;

import org.jboss.resteasy.annotations.Form;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
/**
 *
 * @author NathA1
Spring will use any class annotated with the @Controller annotation as
a Controller in Spring MVC support
The @Produces is used to map a client request and match it up to the client's Accept header.
The Accept HTTP header is sent by the client and defines the media types the client prefers to
receive from the server
 */
@Controller
@Path(ProductsResource.CONTACTS_URL)
public class ProductsResource
{
   public static final String CONTACTS_URL = "/products";
   @Autowired
   ProductService service;

   @GET
   @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   @Path("data")
   public Products getAll()
   {
      return service.getAll();
   }

   @PUT
   @POST
   @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   @Path("data")
   public Response saveProduct(@Context UriInfo uri, Product product)
         throws URISyntaxException
   {
       System.out.println("Inside -->> saveProduct");
      service.save(product);
      URI newURI = UriBuilder.fromUri(uri.getPath()).path(product.getLongName()).build();
      return Response.created(newURI).build();
   }

   @GET
   @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   @Path("data/{shortName}")
   public Product get(@PathParam("shortName") String shortName)
   {
      return service.getProduct(shortName);
   }

   @POST
   @PUT
   @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
   @Produces(MediaType.TEXT_HTML)
   public ModelAndView saveContactForm(@Form Product product)
         throws URISyntaxException
   {
       System.out.println("Inside -->> saveContactForm");
      service.save(product);
      return viewAll();
   }
  

   @GET
   @Produces(MediaType.TEXT_HTML)
   public ModelAndView viewAll()
   {
      // forward to the "contacts" view, with a request attribute named
      // "contacts" that has all of the existing contacts
      return new ModelAndView("products", "products", service.getAll());
   }
}
/**
 * END OF PROGRAM
 * =======================================================================
package com.test;
import java.util.ArrayList;
import java.util.Collection;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
When a class is annotated with a @XmlRootElement annotation, RESTEasy
will select the JAXBXmlRootElementProvider. This provider handles basic marhaling and and
unmarshalling of custom JAXB entities
@author Anish Nath
 *
 */

@XmlRootElement
public class Products
{
   private Collection<Product> products;
   public Products()
   {
      this.products = new ArrayList<Product>();
   }
   public Products(Collection<Product> products)
   {
      this.products = products;
   }
   /**
    *  @XmlElement annotation to embed other JAXB-annotated classes.
    * @return
    */
   @XmlElement(name="product")
   public Collection<Product> getProducts()
   {
      return products;
   }
   public void setProducts(Collection<Product> product)
   {
      
      this.products = product;
   }
}

/**
 * END OF PROGRAM
 * =======================================================================
 */
package com.test;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Service;
/**
 *
 * Anish Nath
The @Service annotation marks classes that implement a part of the business
logic of the application
 *
 */
@Service
public class ProductService
{
   private Map<String, Product> productMap = new ConcurrentHashMap<String, Product>();
   public void save(Product product)
   {
       productMap.put(product.getShortName(), product);
   }
   public Product getProduct(String shortName)
   {
      return productMap.get(shortName);
   }
   public Products getAll()
   {
      return new Products(productMap.values());
   }
}

/**
 * END OF PROGRAM
 * =======================================================================
 */
 Web.xml
<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

    <servlet>

        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/products/*</url-pattern>
    </servlet-mapping>

</web-app>

==========================================================================
springmvc-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    ">
    <context:component-scan base-package="com.test" />
    <context:annotation-config />
    <import resource="classpath:springmvc-resteasy.xml" />
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

===========================================================================================
spring rest services
spring rest example

RESTfull web service Example
restlet spring security
ANish

Tuesday, September 21, 2010

Quick Sorting

Quick Sorting


=============================================================
 

The QUICKSORT algorithm, first introduced by C.A.R. Hoare, is
indeed simpler than MEDIAN SORT,
http://opensourceframework.blogspot.com/2010/09/median-sorting.html

QucikSort Complexity
Best O(n log n)
Average O(n log n)
Worst  O(n^2)


=================================================================
Quick Sort Algorithm

Sort(Array)
quickSort(Array,0,n-1)
end

quickSort(Array,left,right)
if(left<right) then
pi=partition(Array,left,right)
quickSort(Array,left,pi-1)
quickSort(Array,pi+1,right)
end

partition(Array,left,right)
p=selectPivot in Array[left,right]
Swap Array[p] and Array[right]
store left
for i=left to right -1 do
if(Array[i]<=Array[rigth])
then
swap Array[i] and Array[Store]
store++
swap Array[Store] and Array[right]
return store
end

===========================================================================================

--
ANish

Median Sorting

MedianSorting


=============================================================
 

MEDIAN SORT(DIVIDE AND CONQUER) algorithm sorts an
array A of n≥1 elements by swapping the median element A[me] with the middle
element of A , creating a left and right half of the array. MEDIAN SORT
then swaps elements in the left half that are larger than A[mid] with elements in
the right half that are smaller or equal to A[mid]

Median   Sort Complexity
Best O(n log n)
Average O(n log n)
Worst  O(n^2)


=================================================================
Median Sort Algorithm

Sort(Array)
for i=1to n-1 do
medianSort(Array,0,n-1)
end

medianSort(Array,left,right)
if(left<right) then
find Median value Array[median] in Array[left,right]
mid=(right+left)/2
swap Array[mid] and Array[median]
for i=left to mid-1 do
if(Array[i]>Array[mid])then
find Array[k] <=Array[mid] where k>mid
swap A[i] and A[k]
medianSort(Array,left,mid-1)
medianSort(Array,mid+1,right)
end
===========================================================================================

--
ANish

Insertion sorting

Insertion Sorting


=============================================================
 

Use INSERTION SORT when you have a small number of elements to sort or the
elements in the initial collection are already “nearly sorted.”
Insertion Sort Complexity
Best O(n)
Average O(n^2)
Worst  O(n^2)

=================================================================
Insertion Sort Algorithm

Sort(Array)
for i=1to n-1 do
insert(Array,i,Array[i])
end

insert(Array,pos,value)
i=pos-1
while(i>=0 and Array[i]>value) do
Array[i+1]=Array[i]
--i
Array[i+1]=value
end
===========================================================================================

Cons
INSERTION SORT suffers from being too conservative for “random
data.
--
ANish

Monday, September 20, 2010

Jboss Cluster Configuration


Jboss Cluster Configuration



=============================================================
 

Starting with a newly unzipped copy of JBoss, navigate into the server
directory and copy the
 all directory twice: once to a directory called
node1 and once to a directory called node2. The contents of your server
directory should now look like that




Issue the following command

run -c node1 -g  cluster1 -u 239.255.100.100 -b localhost -Djboss.messaging.ServerPeerID=1 -Djboss.service.binding.set=ports-01
run  -c node2 -g cluster2 -u 239.255.100.100 -b localhost -Djboss.messaging.ServerPeerID=1 -Djboss.service.binding.set=ports-02





=============================================================

Creating a clustered EJB

The remote interface for a clustered SLSB
import javax.ejb.Remote;
@Remote
public interface TestRemote {
  public void sayHello(String msg);
}

The bean code for a clustered SLSB
import javax.ejb.Stateless;
import org.jboss.ejb3.annotation.Clustered;
@Stateless
@Clustered
public class TestBean implements Counter {
  public void sayHello(String msg) {
    System.out.println(countNumber);
  }
}
 
@org.jboss.ejb3.annotation.Clustered annotation defined.
This annotation tells the server that this bean is clustered and should be load balanced.



Calling the clustered EJB
The client code that calls the clustered SFSB

import javax.naming.Context;
import javax.naming.InitialContext;
public class Client {
  public static void main(String[] args) throws Exception {
    InitialContext ctx = new InitialContext();
    TestRemote s = (TestRemote) ctx.lookup("TestBean/remote");
    for (int i = 0; i < 100; i++) {
      s.sayHello("Anish")
      Thread.sleep(1000);
    }
  }
}


includes the client/jbossallclient.jar in your classpath
The Jndi.properties file
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming

=========================================
jboss clustering example/clustering with JBOSS 5.0/ejb
jboss clustering step by step
jboss clustering step by step
@clustered annotation
EJB Clustering Example
===============================================

ANish

Wednesday, September 15, 2010

Spring 3.0 @Controller Overview

@Controller
Spring 3.0, the @Controller mechanism also allows you to create RESTful Web sites and applications,
through the @PathVariable annotation and other features
Spring will use any class annotated with the @Controller annotation as a Controller in Spring MVC support.


=============================================================
 

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 *
@author NathA1
Spring 3.0, the @Controller mechanism also allows you to create RESTful Web sites and applications,
through the @PathVariable annotation and other features
Spring will use any class annotated with the @Controller
annotation as a Controller in Spring MVC support.
 */
 

@Controller
/**
The @RequestMapping annotation is used to map URLs to the Controller class or aparticular method
If you want to use the @RequestMapping annotation at the method level,
you need to configure DefaultAnnotationHandlerMapping. This is done
by default for DispatcherServlet, but if you are implementing your own handler adapter, you will
have to define AnnotationMethodHandlerAdapter

@RequestMapping Configuration  in Spring

<?xml version="1. 0" encoding="UTF-8" ?>
<context: component-scan base-package="com.test.web" />
<bean class="org.springframework.web.➥
servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<bean class="org. springframework. web. ➥
servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>

 */
@RequestMapping(value="/account")

public class AccountController {

    private Map<Long, Account> accounts = new ConcurrentHashMap<Long, Account>();
   
    @RequestMapping(method=RequestMethod.GET)
    public String getCreateForm(Model model) {
        model.addAttribute(new Account());
        return "account/createForm";
    }
   
    @RequestMapping(method=RequestMethod.POST)
    public String create(@Valid Account account, BindingResult result) {
        if (result.hasErrors()) {
            return "account/createForm";
        }
        this.accounts.put(account.assignId(), account);
        return "redirect:/account/" + account.getId();
    }
   
    @RequestMapping(value="{id}", method=RequestMethod.GET)
    public String getView(@PathVariable Long id, Model model) {
        Account account = this.accounts.get(id);
        if (account == null) {
            throw new ResourceNotFoundException(id);
        }
        model.addAttribute(account);
        return "account/view";
    }

}

==========================================================================


ANish

Tuesday, September 14, 2010

Using JBoss Cache as a Hibernate Second Level Cache

Using JBoss Cache as a Hibernate Second Level Cache


=============================================================
 

<?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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jee="http://www.springframework.org/schema/jee"         
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-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/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
       ">
    <bean id="cisSessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" scope="singleton">
        <property name="hibernateProperties">
            <props>               
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.generate_statistics">true</prop>   
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.jbc2.JndiMultiplexedJBossCacheRegionFactory</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.region.jbc2.cachefactory">java:CacheManager</prop>
                <prop key="hibernate.cache.region.jbc2.cfg.entity">mvcc-entity</prop>
                <prop key="hibernate.cache.region.jbc2.cfg.query">local-query</prop>

            </props>
        </property>


        <property name="packagesToScan">
            <list>
                <value>com.test.persistence.entity</value>
            </list>
        </property>
        <property name="dataSource" ref="persistence.datasource"/>
        <property name="jtaTransactionManager" ref="jtaTransactionManager"/>
    </bean>
     
    <bean id="persistence.datasource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName">
            <value>java:TestDS</value>
        </property>
    </bean>


   <bean id="testDao" class="com.test.dao.hibernate.TestDAOImpl">
        <property name="sessionFactory" ref="testSessionFactory"/>
  </bean>
       <bean id="jtaTransactionManager"   class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName"><value>java:/TransactionManager</value></property>
    </bean>
    <bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>
    <aop:aspectj-autoproxy/>
    <tx:annotation-driven transaction-manager="txManager"/>
</beans>



========================================================
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class TestDAOImpl extends HibernateDaoSupport {

    public List<StudentEntity> getStudents() {
        getHibernateTemplate().setQueryCacheRegion("/com/test/Student");
        getHibernateTemplate().setCacheQueries(true);
        List<StudentEntity> studentList = getHibernateTemplate()
                .findByNamedQuery("student.All");
        return studentList;
    }
}

======================================================
1.The JndiMultiplexedJBossCacheRegionFactory requires that the JBoss Cache CacheManager
is already bound in JNDI; it will not create and bind one if it isn't. It is up to the the user to ensure
the cache is CacheManager and bound in JNDI before the Hibernate SessionFactory is created.

2.For non-JPA Hibernate second level caching, the same configuration properties and values are used;
they are just declared in a Hibernate SessionFactory cfg.xml
file using its syntax (and with "hibernate." removed from the property names):


1.The JndiMultiplexedJBossCacheRegionFactory requires that the JBoss Cache CacheManager
is already bound in JNDI; it will not create and bind one if it isn't. It is up to the the user to ensure
the cache is CacheManager and bound in JNDI before the Hibernate SessionFactory is created.

2.For non-JPA Hibernate second level caching, the same configuration properties and values are used;
they are just declared in a Hibernate SessionFactory cfg.xml
file using its syntax (and with "hibernate." removed from the property names):

3. JBoss Cache requires integration with a JTA TransactionManager in order to meet the
requirements of the second level caching use case. This means your Hibernate application must
be configured to use JTA:


Single JBoss Cache Instance Architecture
    For the single cache case, the user should specify SharedJBossCacheRegionFactory as their
    hibernate.cache.region.factory_class
Multiple JBoss Cache Instance Architecture
    Here the user should specify MultiplexedJBossCacheRegionFactory as their
    hibernate.cache.region.factory_class. The MultiplexedJBossCacheRegionFactory
    shares almost all its code with SharedJBossCacheRegionFactory; the main
    difference is it constructs a different CacheInstanceManager implementation -- the
    MultiplexedCacheInstanceManager.

Hibernate Second Level Caching in JBoss AS 5
Clustered JPA
http://opensourceframework.blogspot.com/2010/08/caching-queries-with-hibernatetemplate.html

----
---
ANish

Wednesday, September 1, 2010

MethodSecurityInterceptor Example

Spring Security
methodsecurityinterceptor example
The spring-security.xml


=============================================================
 

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE beans PUBLIC '-//SPRING//DTD BEAN//EN' 'http://www.springframework.org/dtd/spring-beans.dtd'>
<beans>
<bean id='TestBean' class='com.springSecurity.TestBeanImpl'/>
<!--  1. use Spring’s BeanNameAutoProxyCreator and simply list the beans that you’ll want secured -->

  <bean id='autoProxyCreator' class='org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator'>
    <property name='interceptorNames'>
      <list><value>securityInterceptor</value></list>
    </property>
    <property name='beanNames'>
      <list><value>bookBean</value></list>
    </property>
  </bean>

<!-- Here the autoproxy creator has been instructed to proxy its beans with a single interceptor, a bean named securityInterceptor.
The securityInterceptor bean is configured as follows --
MethodSecurityInterceptor does for method invocations what FilterSecurityInterceptor 
does for servlet requests. That is, it intercepts the invocation and coordinates the efforts of
the authentication manager and the access decision manager to ensure that method requirements are met.
>

  <bean id='securityInterceptor' class='org.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor'>
    <property name='authenticationManager' ref='authenticationManager'/>
    <property name='accessDecisionManager' ref='accessDecisionManager'/>
    <property name='objectDefinitionSource'>
      <value>
        com.springSecurity.TestBean.setValue=ROLE_MANAGER
        com.springSecurity.TestBean.changeValue=ROLE_WORKER,ROLE_MANAGER
      </value>
    </property>
  </bean>


<!-- Spring Security comes with InMemoryDaoImpl,The userMap property is configured with an org.acegisecurity.userdetails.memory.UserMap
object that defines a set of usernames, passwords, and privileges. -->


  <bean id='userDetailsService' class='org.acegisecurity.userdetails.memory.InMemoryDaoImpl'>
    <property name='userMap'>
      <value>
        manager=manager,ROLE_MANAGER
        worker=worker,ROLE_WORKER
        anonymous=anonymous,
        disabled=disabled,disabled,ROLE_WORKER
        anish=anish,ROLE_ADMIN
      </value>
    </property>
  </bean>
 
<!--
org.acegisecurity.vote.AffirmativeBased    Allows access if at least one voter votes to grant access
org.acegisecurity.vote.ConsensusBased    Allows access if a consensus of voters vote to grant access
org.acegisecurity.vote.UnanimousBased    Allows access if all voters vote to grant access
-->

  <bean id='accessDecisionManager' class='org.acegisecurity.vote.AffirmativeBased'>
    <property name='decisionVoters'>
      <list><ref bean='roleVoter'/></list>
    </property>
  </bean>

 <!--
The purpose of ProviderManager is to enable you to
authenticate users against multiple identity management sources.
-->


  <bean id='authenticationManager' class='org.acegisecurity.providers.ProviderManager'>
    <property name='providers'>
      <list><ref bean='authenticationProvider'/></list>
    </property>
  </bean>

  <bean id='authenticationProvider' class='org.acegisecurity.providers.dao.DaoAuthenticationProvider'>
    <property name='userDetailsService' ref='userDetailsService'/>
  </bean>
<!--
The way that RoleVoter decides on its vote is by simply comparing all
of the configuration attributes of the secured resource
(that are prefixed with ROLE_) with all of the authorities
granted to the authenticated user. If RoleVoter
finds a match, it will
cast an ACCESS_GRANTED vote.
Otherwise, it will cast an ACCESS_DENIED vote.
-->

  <bean id='roleVoter' class='org.acegisecurity.vote.RoleVoter'/>
  
</beans>

=============================================================

 

 
package com.springSecurity;

public interface TestBean {
    public int getValue();
    public void setValue(int value);
    public void changeValue(int value);
}




==================================
public class TestBeanImpl implements TestBean {

    private int value = 0;

    public TestBeanImpl() {
        super();
    }

    public int getValue() {
        return this.value;
    }

    // replace the value.
    public void setValue(int value) {
        this.value = value;
    }

    // change the value.
    public void changeValue(int value) {
        this.value += value;
    }
}


==
MethodSecurityInterceptor Example
MethodSecurityInterceptor
Configuring AOP MethodSecurityInterceptor
MethodSecurityInterceptor (Spring Security 3.0.0.RELEASE API)
securing Method invocation Spring
Spring Security
Using Method Invocation
objectDefinitionSource Example
methodsecurityinterceptor objectdefinitionsource
ANish