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

Monday, February 8, 2010

Spring Hibernate Example - Credit Rating

Project: Spring_Credit_Rating
Description: Make Spring and Hibernate work together
IDE: Eclipse
JARs:
commons-logging-1.1.1.jar
spring.jar (2.5.6)
cglib-nodep-2.1.3.jar
asm-attrs-1.5.3.jar
antlr-2.7.6.jar
asm-1.5.3.jar
ojdbc14.jar
commons-collections-2.1.1.jar
dom4j-1.6.1.jar
ehcache-1.2.3.jar
hibernate-3.2.5.ga.jar
jta.jar
xml-apis.jar
serializer.jar
xercesImpl.jar
xalan.jar
xsltc.jar

Spring Configuration
<bean id="createCreditCard" class="com.somellc.CreateCreditCardAccount"> <property name="creditRatingInterface"> <ref bean="creditRating" /> </property> <property name="creditLinkingInterface"> <ref bean="creditLinking" /> </property> <property name="emailInterface"> <ref bean="email" /> </property> </bean> <bean id="creditLinking" class="com.somellc.CreditLinking"> <property name="url"> <value>http://localhost/creditLinkService</value> </property> </bean> <bean id="creditRating" class="com.somellc.CreditRating"> </bean> <bean id="email" class="com.somellc.Email"> <property name="smtpHost"> <value>localhost</value> </property> <property name="fromEmail"> <value>mycompanyadmin@mycompanyadmin.com</value> </property> <property name="userId"> <value>myuserid</value> </property> <property name="password"> <value>mypassword</value> </property> </bean>
Hibernate Configuration
<hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@wshi7:1521:orcl</property> <property name="hibernate.connection.username">hr</property> <property name="hibernate.connection.password">hr</property> <property name="default_schema">hr</property> <property name="connection.autocommit">false</property> <property name="show_sql">true</property> <property name="use_outer_join">false</property> <property name="hibernate.cache.use_second_level_cache">false</property> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <property name="current_session_context_class">thread</property> <property name="hibernate.connection.pool_size">10</property> <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> <property name="hibernate.hbm2ddl.auto">update</property> <!-- Mapping files --> <mapping resource="Customer.hbm.xml"/>
</session-factory></hibernate-configuration>

Customer Table Configuration
<hibernate-mapping> <class name="com.somellc.NewCustomer" table="TAB_CUSTOMER"> <id name="customerId" type="long" column="CUSTOMER_ID" > <generator class="sequence"/> </id>
<property name="customerName" type="java.lang.String" column="CUSTOMER_NAME" update="true" insert="true"></property>
</class></hibernate-mapping>

Product Table Configuration
<hibernate-mapping> <class name="com.onstar.brm.begspring.Product" table="TAB_PROD"> <id name="productId" type="long" column="PROD_ID" > <generator class="sequence"/> </id>
<property name="productName" type="java.lang.String" column="PROD_NM" update="true" insert="true"></property> <property name="productDesc" type="java.lang.String" column="PROD_DESC" update="true" insert="true"></property>
</class></hibernate-mapping>


CreateCreditAccountClient.java
INewCustomer inewcustomer = new NewCustomer();inewcustomer.setCustomerName("Hibernate Example Customer");
IProductDAO iproductDAO1 = new ProductDAO(); iproductDAO1.createSession(); iproductDAO1.getProduct(63); //CreditCardAccountCreateCreditCardAccountInterface creditCardAccount = (CreateCreditCardAccountInterface)appContext.getBean("createCreditCard");creditCardAccount.createCreditCardAccount(icustomer);

CreateCreditCardAccount.java
public void createCreditCardAccount(ICustomer icustomer) throws Exception{
boolean crediRating = getCreditRatingInterface().getUserCreditHistoryInformation(icustomer);
icustomer.setCreditRating(crediRating);
//Good Rating
if(crediRating){
getCreditLinkingInterface().linkCreditBankAccount(icustomer);
}
getEmailInterface().sendEmail(icustomer);
}


CreateCreditCardAccountInterface.java
public interface CreateCreditCardAccountInterface {
public CreditLinkingInterface getCreditLinkingInterface();
public void setCreditLinkingInterface(
CreditLinkingInterface creditLinkingInterface);
public CreditRatingInterface getCreditRatingInterface();
public void setCreditRatingInterface(
CreditRatingInterface creditRatingInterface);
public EmailInterface getEmailInterface();
public void setEmailInterface(EmailInterface emailInterface);
public void createCreditCardAccount(ICustomer icustomer) throws Exception;
}


CreditLinking.java
public class CreditLinking implements CreditLinkingInterface {
private String url;
public void linkCreditBankAccount(ICustomer icustomer) throws Exception {
//Connect to URL
System.out.println("url to connect is" + url);
System.out.println("credit card linked for customer id " +icustomer.getCustomerId());
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}


CustomerDAO.java
public class CustomerDAO implements ICustomerDAO{
private Session session = null;
public void createSession(){
Configuration cfg = new Configuration()
.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
this.session = sf.getCurrentSession();
}
public INewCustomer create(INewCustomer inewCustomer) {
Transaction transaction = session.beginTransaction();
session.save(inewCustomer);
transaction.commit();
return inewCustomer;
}
}


Customer.java
public class Customer implements ICustomer {
// Existing Customer of bank
private String customerId;
// Customer Information
private String ssnId;
private String firstName;
private String lastName;
private String emailAddress;
private boolean creditRating;
// Address Information
private IAddress iAddress;
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public IAddress getIAddress() {
return iAddress;
}
public void setIAddress(IAddress address) {
iAddress = address;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSsnId() {
return ssnId;
}
public void setSsnId(String ssnId) {
this.ssnId = ssnId;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public boolean isCreditRating() {
return creditRating;
}
public void setCreditRating(boolean creditRating) {
this.creditRating = creditRating;
}
}


Spring AOP Example - Person Service

Project: Spring_AOP
Description: Have AOP attached to Person Service
IDE: Eclipse
JARs:

aspectj-1.6.8.jar
aspectjweaver.jar
commons-logging-1.1.1.jar
spring.jar (2.5.6)

XML Configuration


<!-- this is the object that will be proxied by Spring's AOP infrastructure --><bean id="personService" class="com.somellc.aop.DefaultPersonService"/> <!-- this is the actual advice itself --><bean id="profiler" class="com.somellc.aop.SimpleProfiler"/><aop:config><aop:aspect ref="profiler"> <aop:pointcut id="aopafterMethod" expression="execution(* com.somellc.aop.DefaultPersonService.getAfter())"/> <aop:after pointcut-ref="aopafterMethod" method="afterMethod"/> <aop:pointcut id="aopBefore" expression="execution(* com.somellc.aop.DefaultPersonService.getBefore(String)) and args(myName)"/> <aop:before pointcut-ref="aopBefore" method="beforeMethod"/>
</aop:aspect></aop:config>


Client.java
public class AOPClient {
public static void main(final String[] args) throws Exception {
String filename = "aop-context.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(filename);
IPersonService ipersonService = (IPersonService)context.getBean("personService");
ipersonService.getPerson("John Doe", 12);
ipersonService.getAfter();
ipersonService.getBefore("Jack Smith");
}
}



PersonService Interface:
public class AOPClient {
public static void main(final String[] args) throws Exception {
String filename = "aop-context.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(filename);
IPersonService ipersonService = (IPersonService)context.getBean("personService");
ipersonService.getPerson("John Doe", 12);
ipersonService.getAfter();
ipersonService.getBefore("Jack Smith");
}
}



Person.java
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Person(String nm, int ag) {
name = nm;
age = ag;
}
}



Person Service Class:
public class DefaultPersonService implements IPersonService {
public Person getPerson(String name, int age) {
return new Person(name, age);
}
public void getAfter() {;}
public void getBefore(String myName) {;}
}



Profiler Java class:
public class SimpleProfiler {
public void afterMethod() throws Throwable {
System.out.println("After the method is called");
}
public void beforeMethod(String myName){
System.out.println("beforeMethod is called. My name is "+myName);
}
}

Spring IOC Example - Calculator



Project: Spring_Calculator
Description: This Example shows how three binary operations (Add, Minus, Multiply) can be realized without controller's knowledge. The result can be written to a file or be displayed on the screen.
IDE: Eclipse
JARS:
cglib-nodep-2.1.3.jar
commons-logging-1.1.1.jar
spring.jar (2.5.6)

XML Configuration Diagram

XML Configuration
<bean id="screen" class="com.somellc.spring_calculator.ScreenWriter" /> <bean id="File" class="com.somellc.spring_calculator.DataFileWriter" /> <bean id="multiply" class="com.somellc.spring_calculator.OpMultiply" /> <bean id="add" class="com.somellc.spring_calculator.OpAdd" /> <bean id="minus" class="com.somellc.spring_calculator.OpMinus" />
<bean id="opsbean1" class="com.somellc.spring_calculator.CalculateSpring"> <property name="ops" ref="add" /> <property name="writer" ref="screen"/> </bean>
<bean id="opsbean2" class="com.somellc.spring_calculator.CalculateSpring"> <property name="ops" ref="multiply" /> <property name="writer" ref="screen"/> </bean>
<bean id="opsbean3" class="com.somellc.spring_calculator.CalculateSpring"> <property name="ops" ref="minus" /> <property name="writer" ref="screen"/> </bean>

Operation.java Interface;
public interface Operation {
long operate(long op1, long op2);
String getOpsName();
}

OpAdd.java
public class OpAdd implements Operation{
public OpAdd() {}
public String getOpsName() {
return " plus ";
}
public long operate(long op1, long op2) {
return op1 + op2;
}
}

OpMinus.java
public class OpMinus implements Operation{
public OpMinus() {}
public String getOpsName() {
return " minus ";
}
public long operate(long op1, long op2) {
return op1 - op2;
}
}

OpMultiply.java
public class OpMultiply implements Operation {
public OpMultiply() {}
public String getOpsName() {
return " times ";
}
public long operate(long op1, long op2) {
return op1 * op2;
}
}

ResultWriter.java Interface
public interface ResultWriter {
void showResult(String result) ;
}

ScreenWriter.java
public class ScreenWriter implements ResultWriter{
public ScreenWriter() {}
public void showResult(String result) {
System.out.println(result);
}
}

DataFileWriter.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
public class DataFileWriter implements ResultWriter {
public DataFileWriter() {}
public void showResult(String result) {
File file = new File("output.txt");
try {
PrintWriter fwriter = new PrintWriter(
new BufferedWriter(new FileWriter(file)));
fwriter.println(result);
fwriter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Sending and Receiving Message using Spring, ActiveMQ and JMS

Project: Spring_ActiveMQ
IDE: Eclipse
JARS:
activemq-core-5.3.0.jar
commons-lang-2.1.jar
commons-logging-1.1.1.jar
concurrent-1.3.4.jar
jms-1.1.jar
log4j-1.2.9.jar
spring-2.0-rc3.jar

XML Configuration
Shared Context:

<bean id="requestQueue" class="org.apache.activemq.command.ActiveMQQueue"> <constructor-arg value="requestQ"/> </bean> <bean id="replyQueue" class="org.apache.activemq.command.ActiveMQQueue"> <constructor-arg value="replyQ"/> </bean> <bean id="connectionFactory" class="org.apache.activemq.spring.ActiveMQConnectionFactory"> <property name="brokerURL" value="tcp://localhost:61616"/> </bean>


Client Context:

<bean id="replyNotifier" class="com.somellc.spring_activemq.ReplyNotifier"/> <bean id="listener" class="org.springframework.jms.listener.adapter.MessageListenerAdapter"> <property name="delegate" ref="replyNotifier"/> <property name="defaultListenerMethod" value="notify"/> </bean> <bean id="container" class="org.springframework.jms.listener.SimpleMessageListenerContainer"> <property name="connectionFactory" ref="connectionFactory"/> <property name="messageListener" ref="listener"/> <property name="destination" ref="replyQ"/> </bean> <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"> <property name="connectionFactory" ref="connectionFactory"/> <property name="defaultDestination" ref="requestQ"/> </bean>


Server Context:

<bean id="registrationService" class="com.somellc.spring_activemq.RegistrationService"/> <bean id="listener" class="org.springframework.jms.listener.adapter.MessageListenerAdapter"> <property name="delegate" ref="registrationService"/> <property name="defaultListenerMethod" value="processRequest"/> <property name="defaultResponseDestination" ref="replyQ"/> </bean> <bean id="container" class="org.springframework.jms.listener.SimpleMessageListenerContainer"> <property name="connectionFactory" ref="connectionFactory"/> <property name="messageListener" ref="listener"/> <property name="destination" ref="requestQ"/> </bean>


Client.java
ApplicationContext context = new ClassPathXmlApplicationContext(filename);
JmsTemplate jmsTemplate = (JmsTemplate) context.getBean("jmsTemplate");
jmsTemplate.convertAndSend(request);

Server.java
new ClassPathXmlApplicationContext(filename);
System.in.read();

ReplyNotifier.java
Has method notify()