Core Java,J2EE,JSP,Servlet,JDBC,EJB,Struts,Webservices,,Restfull Web services,J2ee,Spring,Hibernate,Oracle,SQLPlus,EJB3.0,PLSQL,IOC,Spring MVC,ClearCase/ClearQuest,Axis,Jaxws,Eclipse,Jdev,Nebeaans,Ruby,Rails,Stored Procedure,Weblogic,Weblogic Integration,Tocat5.o,JavaEE,bea Tuxedo,SVN,Quality Center,Jboss,RDBMS,telecom BSS,VAS,Maven,Ant,MVC framework,Oc4j,Enterprise Architect,JPA,WLI,JSTL,Telecom Billing,SOAP,WSDL,gdb,Adsense
google Analytics
Monday, August 30, 2010
Generating XML Beans Using Maven
xmlbeans maven
=============================================================
=============================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.test.xmlbeans</groupId>
<artifactId>xmlbeansgenerate</artifactId>
<version>10.1.0</version>
</parent>
<artifactId>XMLBeans</artifactId>
<version>1.1.0</version>
<packaging>jar</packaging>
<name>XMLBeans</name>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>xmlbeans-maven-plugin</artifactId>
<version>2.3.3</version>
<executions>
<execution>
<goals>
<goal>xmlbeans</goal>
</goals>
</execution>
</executions>
<inherited>true</inherited>
<configuration>
<sourceGenerationDirectory>src/main/</sourceGenerationDirectory>
<source>1.6</source>
<target>1.6</target>
<xmlConfigs>
<xmlConfig implementation="java.io.File">src/main/xsdconfig/config.xsdconfig</xmlConfig>
</xmlConfigs>
<!--schemaDirectory>src/main/xsd</schemaDirectory-->
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>net.sf.saxon</groupId>
<artifactId>saxon</artifactId>
<version>8.7</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans-xpath</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans-xmlpublic</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans-qname</artifactId>
<version>2.4.0</version>
</dependency>
</dependencies>
</project>
Maven XML Beans Plugin - xmlbeans:xmlbeans
xmlbeans maven dependency
maven pom xml for xml beans
xmlbeans generate xml from xsd using maven
pom file for xmlbeans
ANish
named query in hibernate
Using Named Query
named query example
Calling a named query
In Hibernate, the getNamedQuery() method obtains a Query instance for a named query:
session.getNamedQuery("findItemsByName")
.setString("desc", description);
Java
Persistence also supports named
queries:
em.createNamedQuery("http://opensourceframework.blogspot.com/2010/07/hibernate-named-query-example.html
findItemsByName").setParameter("desc",
description);
Named queries don't have to be HQL or JPA QL strings; they may even be native
SQL queries—and your Java code doesn't
need to know the difference:
<sql-query name="findItemsByName">
<return alias="item"
class="Item"/>
<![CDATA[
select {item.*}
from item where name like :desc
]]>
</sql-query>
named query with annotations
Assume you consider
a particular named query to belong to a particular entity class:
package auction.model
import ...;
@NamedQueries({
@NamedQuery(
name = "findItemsByName",
query = "select i from Item i where i.name like :name"
),
...
})
@Entity
@Table(name = "ITEM")
public class Item { ... }
Named Query Hibernate
hibernate named
query annotation
named query in hibernate
hibernate named query example
Anish
Caching queries with HibernateTemplate
Caching queries with HibernateTemplate
hibernateTemplate caching
Speed Up Your Hibernate Applications with Second-Level Caching
hibernate jboss cache guide
Hibernate Caching with JBOSS Treecache example
Hibernate Caching
=============================================================
=============================================================
The treecache.xml
<?xml version="1.0" encoding="UTF-8"?>
<server>
<mbean code="org.jboss.cache.TreeCache" name="jboss.cache:service=TreeCache">
<depends>jboss:service=TransactionManager</depends>
<!-- Configure the TransactionManager -->
<attribute name="TransactionManagerLookupClass">org.jboss.cache.JBossTransactionManagerLookup</attribute>
<!-- Isolation level : SERIALIZABLE
REPEATABLE_READ (default)
READ_COMMITTED
READ_UNCOMMITTED
NONE
-->
<attribute name="IsolationLevel">REPEATABLE_READ</attribute>
<!-- Valid modes are LOCAL, REPL_ASYNC and REPL_SYNC -->
<attribute name="CacheMode">LOCAL</attribute>
<!-- Just used for async repl: use a replication queue -->
<attribute name="UseReplQueue">false</attribute>
<!-- Replication interval for replication queue (in ms) -->
<attribute name="ReplQueueInterval">0</attribute>
<!-- Max number of elements which trigger replication -->
<attribute name="ReplQueueMaxElements">0</attribute>
<!-- Whether or not to fetch state on joining a cluster -->
<attribute name="FetchStateOnStartup">true</attribute>
<!-- The max amount of time (in milliseconds) we wait until the
initial state (ie. the contents of the cache) are retrieved from
existing members in a clustered environment
-->
<attribute name="InitialStateRetrievalTimeout">5000</attribute>
<!-- Number of milliseconds to wait until all responses for a synchronous call have been received. -->
<attribute name="SyncReplTimeout">15000</attribute>
<!-- Max number of milliseconds to wait for a lock acquisition -->
<attribute name="LockAcquisitionTimeout">15000</attribute>
<!-- Name of the eviction policy class. -->
<!--
<attribute name="EvictionPolicyClass">org.jboss.cache.eviction.FIFOPolicy</attribute>
-->
<!-- Specific eviction policy configurations. This is LRU -->
<attribute name="EvictionPolicyConfig">
<config>
<attribute name="wakeUpIntervalSeconds">5</attribute>
<region name="/_default_">
<attribute name="maxNodes">5000</attribute>
<attribute name="timeToLiveSeconds">1000</attribute>
<attribute name="maxAgeSeconds">120</attribute>
</region>
<region name="hibernate/HibernateLogEntryDao">
<attribute name="maxNodes">5000</attribute>
<attribute name="timeToLiveSeconds">1000</attribute>
</region>
</config>
</attribute>
</mbean>
</server>
=================================================
The treecache.xml,to be placed in the common location where log4j properties files are read
Jar's Needed Jboss-cache.jar and jgroups.jar and comman hibernate Jar's
<?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:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jboss="http://www.springmodules.org/schema/jboss"
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.springmodules.org/schema/jboss
http://www.springmodules.org/schema/cache/springmodules-jboss.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value></property>
<property name="url"><value>jdbc:oracle:thin:@localhost:1521:XE</value></property>
<property name="username"><value>smc</value></property>
<property name="password"><value>smc</value></property>
<property name="maxActive"><value>100</value></property>
<property name="maxIdle"><value>30</value></property>
<property name="maxWait"><value>1000</value></property>
<property name="defaultAutoCommit"><value>false</value></property>
</bean>
<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingLocations">
<list>
<value>classpath*:/dataaccess/hibernate/*.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.TreeCacheProvider</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
</props>
</property>
</bean>
<bean id="hibernateDaoSupport" abstract="true" class="org.springframework.orm.hibernate3.support.HibernateDaoSupport">
<property name="sessionFactory" ref="hibernateSessionFactory"/>
</bean>
<bean id="templatelessLogEntryDao" class="com.apress.prospring2.ch11.dataaccess.hibernate.TemplatelessHibernateInvoiceLogEntryDao">
<constructor-arg ref="hibernateSessionFactory"/>
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean id="lodDao" class="com.apress.prospring2.ch11.dataaccess.HiberNateDaoSupportIml">
<property name="sessionFactory" ref="hibernateSessionFactory"/>
</bean>
</beans>
Implementation Code:-
public List<LogEntry> getAll() {
System.out.println("GetAll Called");
long start, end, total;
start = System.currentTimeMillis();
getHibernateTemplate().setQueryCacheRegion("HibernateLogEntryDao");
getHibernateTemplate().setCacheQueries(true);
List<LogEntry> returns=getHibernateTemplate().find("from LogEntry");
end = System.currentTimeMillis();
total = end - start;
System.out.println("Totall-->>"+total);
return returns;
}
hibernateTemplate 2nd level cache
Caching queries with HibernateTemplate
hibernateTemplate caching
Speed Up Your Hibernate Applications with Second-Level Caching
hibernate jboss cache guide
Using treecache as 2nd level cache
JBoss Cache based Hibernate Second Level Cache provider
Sunday, August 29, 2010
EJB 3.0 with Spring 1.2 SpringBeanAutowiringInterceptor
The EJB
EJB3-compliant interceptor class that injects Spring beans into fields
and methods which are annotated with @Autowired. Performs injection after
construction as well as after activation of a passivated bean.
To be applied through an @Interceptors annotation in the
EJB Session Bean
or Message-Driven Bean class, or through an interceptor-binding XML
element in the EJB deployment descriptor.
Delegates to Spring's AutowiredAnnotationBeanPostProcessor underneath,
allowing for customization of its specific settings through overriding
the configureBeanPostProcessor(org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor,
java.lang.Object) template method.
The actual BeanFactory to obtain Spring beans from is determined by the getBeanFactory(java.lang.Object)
template method. The default implementation obtains the Spring ContextSingletonBeanFactoryLocator,
initialized from the default resource location classpath*:beanRefContext.xml,
and obtains the single ApplicationContext defined there
package com.test;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor;
import com.test.TestSpringBeanAutoWiringSessionBean;
@Interceptors(SpringBeanAutowiringInterceptor.class)
public @Stateless class TestSpringBeanAutoWiringSessionBeanBean implements TestSpringBeanAutoWiringSessionBean {
@Override
public void sayHello(String name) {
System.out.println("Anish---->>"+name);
}
@Autowired
private AnnotatedTarget target;
}
The beanRefContext.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="beanfactoryTDS"
class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg value="META-INF/SpringContext.xml" />
</bean>
</beans>
and here' smy SpringContext.xml
META-INF\SpringContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="foo" class="com.apress.prospring2.ch03.autowiring.Foo"/>
<bean id="bar" class="com.apress.prospring2.ch03.autowiring.Bar"/>
<bean id="annotatedTarget" class="com.apress.prospring2.ch03.autowiring.AnnotatedTarget"/>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
</beans>
public class AnnotatedTarget {
@Autowired
private Foo foo;
@Autowired
private Foo foo2;
@Autowired
private Bar bar;
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("AnnotatedTarget");
sb.append("{foo=").append(foo);
sb.append(", foo2=").append(foo2);
sb.append(", bar=").append(bar);
sb.append('}');
return sb.toString();
}
}
==================================================================================================================================
public class Bar {
@Override
public String toString() {
return getClass().getName();
}
}
==================================================================================================================================
public class Foo {
@Override
public String toString() {
return getClass().getName();
}
}
Technology Solutions: MDB Using SpringBeanAutowiringInterceptor ...
MDB USING Spring Bean Autowiring Interceptor
http://opensourceframework.blogspot.com/2010/08/mdb-using-springbeanautowiringintercept.html
EJB 3.0 with Spring 1.2
SpringBeanAutowiringInterceptor Spring2.5.2 API
Versioning without version numbers or timestamps Hibernate
=============================================================
=============================================================
Application don't have version or timestamp columns, Hibernate can still perform automatic versioning, but only for objects that are retrieved and modified in the same persistence context (that is, the same Session). If you need optimistic locking for conversations implemented with detached objects, you must use a version number or timestamp that is transported with the detached object.
=============================================================
=============================================================
This alternative implementation of versioning checks the current database state against the unmodified values of persistent properties at the time the object was retrieved (or the last time the persistence context was flushed). You may enable this functionality by setting the optimistic-lock attribute on the class mapping:
<class name="Book" table="Book" optimistic-lock="all">
<id .../>
...
</class>
=============================================================
=============================================================
Versioning with Java Persistence or JPA
To enable automatic versioning for a particular entity, you need to add a version property or field:
@Entity
public class BOOK{
...
@Version
@Column(name = "VERSION")
private int version;
...
}
======================================================================
=============================================================
=============================================================
Versoning Example In Hibernate
http://opensourceframework.blogspot.com/2010/07/hibernate-vesioning-example.html
Thursday, August 26, 2010
Calling EJB3 from Spring
=============================================================
=============================================================
<?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="helper" class="com.test.ejb.TestEjbImpl" scope="singleton">
<property name="testenvejb" ref="testenvejb" />
</bean>
<jee:jndi-lookup id="testenvejb" jndi-name="testenvejb">
<jee:environment>
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost:1300
</jee:environment>
</jee:jndi-lookup>
</beans>
=============================================================
=============================================================
package com.test.ejb;
import org.springframework.beans.factory.annotation.Autowired;
import com.testenv.TestEnvEjbRemote;
public class TestEjbImpl {
public TestEjbImpl() {
System.out.println("called");
}
@Autowired
public TestEnvEjbRemote testenvejb;
public void callMe(){
System.out.println(testenvejb);
testenvejb.sayHello("ANish");
}
public void setTestenvejb(TestEnvEjbRemote testenvejb) {
this.testenvejb = testenvejb;
}
}
=============================================================
=============================================================
The Ejb
package com.testenv;
import javax.ejb.Stateless;
/**
* Session Bean implementation class TestEnvEjb ANISH
*/
@Stateless(mappedName = "testenvejb")
public class TestEnvEjb implements TestEnvEjbRemote, TestEnvEjbLocal {
/**
* Default constructor.
*/
public TestEnvEjb() {
// TODO Auto-generated constructor stub
}
@Override
public void sayHello(String name) {
System.out.println("name------>>>>>>>"+name);
}
}
package com.testenv;
import javax.ejb.Remote;
@Remote
public interface TestEnvEjbRemote {
public void sayHello(String name);
}
package com.testenv;
import javax.ejb.Local;
@Local
public interface TestEnvEjbLocal {
}
===============================
=============================================================
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class TestEjb {
public static void main(String[] args) {
XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource(
"/META-INF/spring/ODSSpring.xml"));
System.out.println(bf.getBean("helper"));
TestEjbImpl helper = (TestEjbImpl) bf.getBean("helper");
helper.callMe();
}
}
<jee:jndi-lookup/> (with multiple JNDI environment settings)
Using Jee Calling EJB3.0 with SpringUnderstanding the jee environment Settings
jndi environment with jee schema
Monday, August 23, 2010
The eTOM Framework
The eTOM Framework
The eTOM is "a business process framework or model that provides the enterprise processes required for a service provider,
In the eTOM, the focus is on the customer, and processes that directly support the customer. In the eTOM framework, the processes that do this are in three main areas called Fulfillment, Assurance, and Billing
This framework is described pictorially, with emphasis on these three areas, as below:
Fulfillment
This process is responsible for providing customers with the products that they have requested, in a timely and accurate manner.
Assurance
In the Assurance area, the enterprise ensures that the maintenance activities are carried out to ensure services provided to customers, keeping in mind the SLA, and QoS standards required.
Billing
Billing concerns itself with the production of timely and accurate bills, for providing pre-bill use information and billing to customers, for processing their payments, and for performing payment collections
http://www.tmforum.org/BusinessProcessFramework/1647/home.html
--
Regards
Anish
Sunday, August 22, 2010
Improve Hibernate Speed
Ehcache is an open source widely used java distributed cache for general purpose caching, Java EE and light-weight containers. It features memory and disk stores, replicate by copy and invalidate, listeners, cache loaders, cache extensions, cache exception handlers, a gzip caching servlet filter, RESTful and SOAP APIs and much more. Ehcache is available under an Apache open source license and is actively supported
Hibernate Second Level Cache
Setting Ehcache as the Hibernate Second Level Cache
Hibernate 3.0 - 3.2
Use:
<property name="hibernate.cache.provider_class">
net.sf.ehcache.hibernate.EhCacheProvider
</property>
for instance creation, or
<property name="hibernate.cache.provider_class">
net.sf.ehcache.hibernate.SingletonEhCacheProvider
</property>
to force Hibernate to use a singleton Ehcache CacheManager.
For example to enable cache entries for the domain object
com.somecompany.someproject.domain.Country there would be a mapping file
something like the following:
<hibernate-mapping>
<class
name="com.somecompany.someproject.domain.Country"
table="ut_Countries"
dynamic-update="false"
dynamic-insert="false"
>
...
</class>
</hibernate-mapping>
This can also be achieved using the @Cache annotation, e.g.
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Country { ... }
To enable caching, add the following element.
<cache usage="read-write|nonstrict-read-write|read-only" />
For example, let's say we have a common query running against the Country Domain.
Code to use a query cache follows:
public List getStreetTypes(final Country country) throws HibernateException {
final Session session = createSession();
try {
final Query query = session.createQuery(
"select st.id, st.name"
+ " from StreetType st "
+ " where st.country.id = :countryId "
+ " order by st.sortOrder desc, st.name");
query.setLong("countryId", country.getId().longValue());
query.setCacheable(true);
query.setCacheRegion("query.StreetTypes");
return query.list();
} finally {
session.close();
}
}
The query.setCacheable(true) line caches the query.
The query.setCacheRegion("query.StreetTypes") line sets the name of the Query Cache.
=========================================================================
Introduction to Hibernate Caching
Hibernate Performance Tuning
Hibernate Second Level Cache
Searches related to hibernate 2nd level cache
hibernate 2nd level cache spring modules
manipulating hibernate 2nd level cache
hibernate ehcache
spring modules cache java
nhibernate 2nd level cache
hibernate cache use second level cache
hibernate clear second level cache
for more information on ehCache
http://ehcache.org/documentation/hibernate.html
Saturday, August 21, 2010
Job Scheduling with Spring
Scheduling support in Spring comes in two distinct forms: JDK Timer-based and Quartz-based.
The JDK Timer-based approach provides scheduling capabilities on any version 1.3 or later JVM,
and it does not need external dependencies beyond Spring. Timer-based scheduling is quite primitive
and provides limited flexibility when defining job schedules. However, Timer support is included
with Java and requires no external libraries, which might be beneficial if you are restricted by application
size or corporate policy. Quartz-based scheduling is much more flexible and allows triggers
to be defined in a much more real-world way, such as the earlier example of 3:00 p.m. every Monday,
Wednesday, and Friday
Scheduling Jobs Using JDK Timer
Creating a Simple Job
To create a job to use with the Timer class, you simply extend the TimerTask class and implement the
run() method to execute your job’s logic
public class HelloWorldTask extends TimerTask {
public void run() {
System.out.println("Hello World!");
}
}
import java.util.Timer;
public class OneOffScheduling {
public static void main(String[] args) {
Timer t = new Timer();
t.schedule(new HelloWorldTask(), 1000);
}
}
=============================================
Scheduling a Repeating Task
public class FixedDelayScheduling {
public static void main(String[] args) throws Exception{
Timer t = new Timer();
t.schedule(new HelloWorldTask(), 1000, 3000);
}
}
import java.util.Timer;
public class FixedRateScheduling {
public static void main(String[] args) throws Exception {
Timer t = new Timer();
t.scheduleAtFixedRate(new HelloWorldTask(), 1000, 1000);
}
}
=====================================
Spring Support for JDK Timer Scheduling
The core of Spring’s Timer support comes in the form of the ScheduledTimerTask and
TimerFactoryBean classes. The ScheduledTimerTask class acts as a wrapper around your TimerTask
implementations and allows you to define trigger information for the job. Using the TimerFactoryBean,
you can have Spring automatically create Timer instances for a given list of ScheduledTimerTask beans
using the trigger configuration data when creating the trigger
Configuring Job Scheduling Using TimerFactoryBean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=http://www.springframework.org/schema/beans
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="job" class="com.apress.prospring2.ch12.timer.HelloWorldTask"/>
<bean id="timerTask"
class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="delay" value="1000" />
<property name="period" value="3000" />
<property name="timerTask" ref="job" />
</bean>
<bean id="timerFactory"
class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref local="timerTask"/>
</list>
</property>
</bean>
</beans>
=================================
Scheduling Jobs Using OpenSymphony Quartz
Quartz provides a huge range of features such as persistent jobs, clustering,
and distributed transaction,The core of Quartz is made up of two interfaces, Job and Scheduler, and two classes, JobDetail
and Trigger
Scheduling jobs using Quartz or Timer
Dynamic Job Scheduling using Spring
Scheduling Jobs Using OpenSymphony Quartz
Friday, August 20, 2010
REST vs SOAP Web Services
=============================================================
=============================================================
=============================================================
=============================================================
A RESTful approach to Web services.
REST vs SOAP Web Services
difference between rest and soap web services
What are the difference between a REST-based Web Services
--
Anish
RESTfull webservice, Using Jboss Resteasy folder Structure
RESTeasy is deployed as a WAR archive and thus depends on a Servlet container.
Download RESTeasy and unzip it you will see a lib/ directory that contains the
libraries needed by resteasy. Copy these into your /WEB-INF/lib directory. Place your JAX-RS
annotated class resources and providers within one or more jars within /WEB-INF/lib or your raw
class files within /WEB-INF/classes
Anish
Thursday, August 19, 2010
RESTfull webservices Overview
Invented by : 2000 by Roy Fielding also known as e principal authors of the Hypertext Transfer Protocol (HTTP) specification
Concept: REST-style architectures consist of clients and servers. Clients initiate requests to servers; servers process requests and return appropriate responses. Requests and responses are built around the transfer of "representations" of "resources". A resource can be essentially any coherent and meaningful concept that may be addressed. A representation of a resource is typically a document that captures the current or intended state of a resource.
Resource | GET | PUT | POST | DELETE |
---|---|---|---|---|
Collection URI, such as http://example.com/resources/ | List the URIs and perhaps other details of the collection's members. | Replace the entire collection with another collection. | Create a new entry in the collection. The new entry's URL is assigned automatically and is usually returned by the operation. | Delete the entire collection. |
Element URI, such as http://example.com/resources/142 | Retrieve a representation of the addressed member of the collection, expressed in an appropriate Internet media type. | Update the addressed member of the collection, or if it doesn't exist, create it. | Treat the addressed member as a collection in its own right and create a new entry in it. | Delete the addressed member of the collection. |
JSR Implementation: RESTEasy JAX-RS
Implementation
- Deployed as War file,
- Get the Rest easy war from the open source
- JAr's Required if Using JBOSS Rest Easy
RESTeasy is implemented as a Servlet and deployed within a WAR file.
- httpcore-4.0.1.jar
- javassist-3.6.0.GA.jar
- jaxrs-api-2.0.1.GA.jar
- jcip-annotations-1.0.jar
- jcl-over-slf4j-1.5.8.jar
- jsr250-api-1.0.jar
- resteasy-jaxrs-2.0.1.GA.jar
- scannotation-1.0.2.jar
- slf4j-api-1.5.8.jar
- slf4j-simple-1.5.8.jar
- activation-1.1.jar
- commons-codec-1.2.jar
- commons-httpclient-3.1.jar
- httpclient-4.0.ja
Other's java Implementation for REST full Web services are
Java Jt Design Pattern Framework, Wink , Restlet, JBoss RESTEasy, Jersey, Apache CXF, NetKernel, Apache Sling, Restfulie
Anish
RESTfull webservices Overview
Invented by : 2000 by Roy Fielding also known as e principal authors of the Hypertext Transfer Protocol (HTTP) specification
Concept: REST-style architectures consist of clients and servers. Clients initiate requests to servers; servers process requests and return appropriate responses. Requests and responses are built around the transfer of "representations" of "resources". A resource can be essentially any coherent and meaningful concept that may be addressed. A representation of a resource is typically a document that captures the current or intended state of a resource.
Resource | GET | PUT | POST | DELETE |
---|---|---|---|---|
Collection URI, such as http://example.com/resources/ | List the URIs and perhaps other details of the collection's members. | Replace the entire collection with another collection. | Create a new entry in the collection. The new entry's URL is assigned automatically and is usually returned by the operation. | Delete the entire collection. |
Element URI, such as http://example.com/resources/142 | Retrieve a representation of the addressed member of the collection, expressed in an appropriate Internet media type. | Update the addressed member of the collection, or if it doesn't exist, create it. | Treat the addressed member as a collection in its own right and create a new entry in it. | Delete the addressed member of the collection. |
JSR Implementation: RESTEasy JAX-RS
Implementation
- Deployed as War file,
- Get the Rest easy war from the open source
- JAr's Required if Using JBOSS Rest Easy
RESTeasy is implemented as a Servlet and deployed within a WAR file.
- httpcore-4.0.1.jar
- javassist-3.6.0.GA.jar
- jaxrs-api-2.0.1.GA.jar
- jcip-annotations-1.0.jar
- jcl-over-slf4j-1.5.8.jar
- jsr250-api-1.0.jar
- resteasy-jaxrs-2.0.1.GA.jar
- scannotation-1.0.2.jar
- slf4j-api-1.5.8.jar
- slf4j-simple-1.5.8.jar
- activation-1.1.jar
- commons-codec-1.2.jar
- commons-httpclient-3.1.jar
- httpclient-4.0.ja
Other's java Implementation for REST full Web services are
Java Jt Design Pattern Framework, Wink , Restlet, JBoss RESTEasy, Jersey, Apache CXF, NetKernel, Apache Sling, Restfulie
Anish
Sunday, August 15, 2010
Oracle SQL Query FAQ
2 What are the difference between DDL, DML and DCL commands?
3 Difference between TRUNCATE, DELETE and DROP commands?
4 How does one escape special characters when writing SQL queries?
5 Can one select a random collection of rows from a table?
6 How does one eliminate duplicates rows from a table?
7 How does one get the time difference between two date columns?
8 How does one add a day/hour/minute/second to a date value?
9 How does one code a matrix/crosstab/pivot report in SQL?
10 Can one retrieve only rows X to Y from a table?
11 Can one retrieve only the Nth row from a table?
12 How can one dump/ examine the exact content of a database column?
13 How does one add a column to the middle of a table?
14 How does one code a hierarchical tree-structured query?
15 How does one count/sum data values in a column?
16 How does one drop/ rename a column in a table?
17 How does one implement IF-THEN-ELSE logic in a SELECT statement?
18 How does one prevent Oracle from using an Index?
19 How does one select EVERY Nth row from a table?
20 How does one select the LAST N rows from a table?
21 How does one select the TOP N rows from a table?
22 How to generate a text graphs (histograms) using SQL?
23 Map/ concatenate several rows to a column
24 What is the difference between VARCHAR, VARCHAR2 and CHAR data types?
http://www.orafaq.com/wiki/SQL_FAQ
(JMS) Sending Large Messages to Queue
{
public static void main(final String[] args)
{
new LargeMessageExample().run(args);
}
private final long FILE_SIZE = 10L * 1024 * 1024 * 1024; // 10 GiB message
@Override
public boolean runExample() throws Exception
{
Connection connection = null;
InitialContext initialContext = null;\
try
{
// Step 1. Create an initial context to perform the JNDI lookup.
initialContext = getContext(0);
// Step 2. Perfom a lookup on the queue
Queue queue = (Queue)initialContext.lookup("/queue/exampleQueue");
// Step 3. Perform a lookup on the Connection Factory. This ConnectionFactory has a special attribute set on
// it.
// Messages with more than 10K are considered large
ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("/ConnectionFactory");
// Step 4. Create the JMS objects
connection = cf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(queue);
// Step 5. Create a huge file - this will form the body of the message we will send.
File fileInput = new File("huge_message_to_send.dat");
createFile(fileInput, FILE_SIZE);
// Step 6. Create a BytesMessage
BytesMessage message = session.createBytesMessage();
// Step 7. We set the InputStream on the message. When sending the message will read the InputStream
// until it gets EOF. In this case we point the InputStream at a file on disk, and it will suck up the entire
// file, however we could use any InputStream not just a FileInputStream.
FileInputStream fileInputStream = new FileInputStream(fileInput);
BufferedInputStream bufferedInput = new BufferedInputStream(fileInputStream);
message.setObjectProperty("JMS_HQ_InputStream", bufferedInput);
System.out.println("Sending the huge message.");
// Step 9. Send the Message
producer.send(message);
System.out.println("Large Message sent");
System.out.println("Stopping server.");
// Step 10. To demonstrate that that we're not simply streaming the message from sending to consumer, we stop
// the server and restart it before consuming the message. This demonstrates that the large message gets
// persisted, like a
// normal persistent message, on the server. If you look at ./build/data/largeMessages you will see the
// largeMessage stored on disk the server
connection.close();
initialContext.close();
stopServer(0);
// Give the server a little time to shutdown properly
Thread.sleep(5000);
startServer(0);
System.out.println("Server restarted.");
// Step 11. Now the server is restarted we can recreate the JMS Objects, and start the new connection
initialContext = getContext(0);
queue = (Queue)initialContext.lookup("/queue/exampleQueue");
cf = (ConnectionFactory)initialContext.lookup("/ConnectionFactory");
connection = cf.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer messageConsumer = session.createConsumer(queue);
connection.start();
System.out.println("Receiving message.");
// Step 12. Receive the message. When we receive the large message we initially just receive the message with
// an empty body.
BytesMessage messageReceived = (BytesMessage)messageConsumer.receive(120000);
System.out.println("Received message with: " + messageReceived.getBodyLength() +
" bytes. Now streaming to file on disk.");
// Step 13. We set an OutputStream on the message. This causes the message body to be written to the
// OutputStream until there are no more bytes to be written.
// You don't have to use a FileOutputStream, you can use any OutputStream.
// You may choose to use the regular BytesMessage or
// StreamMessage interface but this method is much faster for large messages.
File outputFile = new File("huge_message_received.dat");
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
BufferedOutputStream bufferedOutput = new BufferedOutputStream(fileOutputStream);
// Step 14. This will save the stream and wait until the entire message is written before continuing.
messageReceived.setObjectProperty("JMS_HQ_SaveStream", bufferedOutput);
fileOutputStream.close();
System.out.println("File streamed to disk. Size of received file on disk is " + outputFile.length());
return true;
}
finally
{
// Step 12. Be sure to close our resources!
if (initialContext != null)
{
initialContext.close();
}
if (connection != null)
{
connection.close();
}
}
}
private void createFile(final File file, final long fileSize) throws FileNotFoundException, IOException
{
FileOutputStream fileOut = new FileOutputStream(file);
BufferedOutputStream buffOut = new BufferedOutputStream(fileOut);
byte[] outBuffer = new byte[1024 * 1024];
for (long i = 0; i < fileSize; i += outBuffer.length)
{
buffOut.write(outBuffer);
}
buffOut.close();
}
}
Friday, August 13, 2010
Spring+HibernateDaoSupport Class Example using JNDI as Datasource Lookup
applicationContext.java
===========================================================================================================================
<?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:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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">
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/testing"/>
</bean>
<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingLocations">
<list>
<value>classpath*:/com/hibernate/*.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
</props>
</property>
</bean>
<bean id="myTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernateSessionFactory"/>
<property name="nestedTransactionAllowed" value="false"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="hibernateDaoSupport" abstract="true"
class="org.springframework.orm.hibernate3.support.HibernateDaoSupport">
<property name="sessionFactory" ref="hibernateSessionFactory"/>
</bean>
<bean id="userDao" class="com.dataaccess.hibernate.HibernateUserDao"
parent="hibernateDaoSupport"/>
</beans>
===========================================================================================================================
HibernateUserDao.java
===========================================================================================================================
public class HibernateUserDao extends HibernateDaoSupport implements UserDao {
public void save(User user) {
getHibernateTemplate().save(user);
}
public void delete(User user) {
getHibernateTemplate().delete(user);
}
public User getById(Long id) {
return (User) getHibernateTemplate().get(User.class, id);
}
public List<User> getAll() {
return getHibernateTemplate().find("from User");
}
public User getByUsername(String username) {
List objects = getHibernateTemplate().find("from User where username = ?", username);
if (objects.size() == 1) return (User) objects.get(0);
if (objects.size() > 1) {
throw new InvalidResultException("Found more than one results");
}
return null;
}
}
WebService with Annotaion Example using JBOSS
CalculatorBean.java
=============================================================================================================================================
@Stateless
@WebService(endpointInterface = "org.jboss.tutorial.webservice.bean.Calculator")
public class CalculatorBean
{
public int add(int x, int y)
{
return x + y;
}
public int subtract(int x, int y)
{
return x - y;
}
}
=============================================================================================================================================
Calculator.java
=============================================================================================================================================
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style = Style.RPC)
public interface Calculator extends Remote
{
@WebMethod
int add(int x, int y);
@WebMethod
int subtract(int x, int y);
}
=============================================================================================================================================
Client.java
=============================================================================================================================================
public class Client
{
public static void main(String[] args) throws Exception
{
URL url = new URL("http://localhost:8080/jboss-ejb3-tutorial-webservice/CalculatorBean?wsdl");
QName qname = new QName("http://bean.webservice.tutorial.jboss.org/", "CalculatorBeanService");
ServiceFactory factory = ServiceFactory.newInstance();
Service service = factory.createService(url, qname);
Calculator calculator = (Calculator) service.getPort(Calculator.class);
System.out.println("1 + 1 = " + calculator.add(1, 1));
System.out.println("1 - 1 = " + calculator.subtract(1, 1));
}
}
Thursday, August 12, 2010
Hibernate3 /Ejb3 (Entity Bean)building session factory entiry classes Uses Annotation JDK1.5+
<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"
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">
<bean id="SessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
scope="singleton">
<property name="hibernateProperties">
<props>
<prop key="hibernate.archive.autodetection">class, hbm</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.connection.autocommit">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.persistence.entity</value>
</list>
</property>
<property name="dataSource" ref="defaultDS" />
</bean>
<bean id="defaultDS" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:defaultDS</value>
</property>
</bean>
</beans>
JNDI lookup for buildng Hibernate Session factory from datasource
<property name="jndiName">
<value>java:defaultDS</value>
</property>
</bean>
--Default Datasource is JNDI lookup, created in Weblogic,JBOss or any App Server
Wednesday, August 11, 2010
Jboss Loading multiple ear with one class laoder
<?xml version="1.0" encoding="UTF-8"?>
<jboss-app>
<loader-repository>
org.myapp:loader=MyClassLoader
<loader-repository-config>
java2ParentDelegation=false
</loader-repository-config>
</loader-repository>
</jboss-app>
Monday, August 9, 2010
MDB Using SpringBeanAutowiringInterceptor EJB3.0 with JBOSS Example
=============================================================
@MessageDriven(
activationConfig = { @ActivationConfigProperty( propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName="destination", propertyValue="testqueue")
})
@Interceptors(SpringBeanInterceptors.class)
public class TestMDB implements MessageListener {
public TestMDB() {
System.out.println("Inside TestMDB()");
}
@Autowired
private AnnotatedTarget target;
public void onMessage(Message message) {
System.out.println("onMessage-->>"+message);
}
}
=============================================================
=============================================================
==================================================================================================================================
public class SpringBeanInterceptors extends SpringBeanAutowiringInterceptor {
=============================================================
=============================================================
private static final String DEFAULT_RESOURCE_LOCATION = "classpath*:beanRefContext.xml";
@Override
protected BeanFactoryLocator getBeanFactoryLocator(Object target) {
System.out.println("Called BeanFactoryLocator2->>>>>>>>>>>>>>>>>>>>>>>>>>>>");
return ContextSingletonBeanFactoryLocator
.getInstance(DEFAULT_RESOURCE_LOCATION);
}
}
======================================================
==================================================================================================================================
public class AnnotatedTarget {
@Autowired
private Foo foo;
@Autowired
private Foo foo2;
@Autowired
private Bar bar;
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("AnnotatedTarget");
sb.append("{foo=").append(foo);
sb.append(", foo2=").append(foo2);
sb.append(", bar=").append(bar);
sb.append('}');
return sb.toString();
}
}
==================================================================================================================================
=============================================================
=============================================================
public class Bar {
@Override
public String toString() {
return getClass().getName();
}
}
==================================================================================================================================
public class Foo {
@Override
public String toString() {
return getClass().getName();
}
}
=============================================================
=============================================================
==================================================================================================================================
META-INF\SpringContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="foo" class="com.apress.prospring2.ch03.autowiring.Foo"/>
<bean id="bar" class="com.apress.prospring2.ch03.autowiring.Bar"/>
<bean id="annotatedTarget" class="com.apress.prospring2.ch03.autowiring.AnnotatedTarget"/>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
</beans>
==================================================================================================================================
--
in Ear folder outside META-INF
beanRefContext.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="beanfactoryTDS"
class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg value="META-INF/SpringContext.xml" />
</bean>
</beans>
=============================================================
=============================================================
==================================================================================================================================
Create EAR
Spring with ejb3.0
ANish
Monday, August 2, 2010
EJB3 Session Bean annotation Example
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost:1300
/**
* Session Bean implementation class CallEjb3Bean
*/
@Stateless(name="CallEjb3Bean", mappedName="CallEjb3")
public class CallEjb3Bean implements CallEjb3BeanLocal {
/**
* Default constructor.
*/
public CallEjb3Bean() {
System.out.println("CallEjb3Bean");
}
public void callme(){
System.out.println("callme-->> Called");
}
}
@Local
public interface CallEjb3BeanLocal {
public void callme();
}
@Stateless(mappedName="testejb")
public class TestEjb3Bean implements TestEjb3BeanRemote, TestEjb3BeanLocal {
/**
* Default constructor.
*/
public TestEjb3Bean() {
System.out.println("TestEjb3Bean->>>>>>> Called");
}
@EJB
private static CallEjb3BeanLocal local;
public void sayHello(String name){
System.out.println("Name-->>"+name);
try {
System.out.println("Start--------------->g>>>");
InitialContext ctx = new InitialContext();
local.callme();
System.out.println("Ends--------------->>>>");
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception----------------->>");
}
}
}
@Local
public interface TestEjb3BeanLocal {
public void sayHello(String name);
}
@Remote
public interface TestEjb3BeanRemote {
public void sayHello(String name);
}
public class Client
{
@EJB
public static TestEjb3BeanRemote remote;
public static void main(String[] args) throws Exception
{
InitialContext ctx = new InitialContext();
TestEjb3BeanRemote testEjb3BeanRemote = (TestEjb3BeanRemote) ctx.lookup("testejb");
testEjb3BeanRemote.sayHello("ANISH");
}
}