Sunday, September 19, 2010

Spring JSF Integration

Spring JSF integration can be achieved by following 2 ways
1) JSF Centric
2) Spring Centric
Recommended approach is Spring Centric using Spring Webflow.

Spring Webflow is on top of Spring MVC. Using webflow a complex
flow can be configured using xml mapping.

Steps for integrating Spring-JSF using Spring WebFlow2

1) In web.xml, configure

2) Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">

<persistence-unit name="examplePersistenceUnit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/OracleDS</jta-data-source>
<properties>
<property name="show_sql" value="true" />
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.SunONETransactionManagerLookup" />
<!-- property name="hibernate.connection.datasource" value="java:/OracleDS" />

<property name="hibernate.transaction.factory_class" value="org.hibernate.transaction.JTATransactionFactory" />
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup" />
<property name="hibernate.current_session_context_class" value="jta" />
<property name="jta.UserTransaction" value="java:comp/UserTransaction" />
<provider>org.hibernate.ejb.HibernatePersistence</provider>

<property name="dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<property name="hibernate.transaction.factory_class" value="org.hibernate.transaction.JTATransactionFactory" />
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup" />
<property name="hibernate.current_session_context_class" value="jta" />
<property name="jta.UserTransaction" value="java:comp/UserTransaction" /-->
<property name="hibernate.validator.apply_to_ddl" value="false" />
<property name="hibernate.validator.autoregister_listeners" value="false" />
</properties>
</persistence-unit>
</persistence>


Accessing JPA Entity Manager in EJB

@Stateless(name="ejb/EmployerBean",mappedName="EmployerBean")
public class EmployerBean {

@PersistenceUnit(unitName="examplePersistenceUnit")
private EntityManagerFactory emf;

@PersistenceContext()
private EntityManager em;

public void saveRecord(){
UserVO user = new UserVO();

user.setName("save");

AddressVO address = new AddressVO();

address.setName("add");
address.setUserInfo(user);

em.persist(user);
em.persist(address);
}
}


UserVO.java

@Entity
@Table(name="USEREMP1")//ackage not found or wo package-info.java: org.sample.mapping
public class UserVO {

@Id
@SequenceGenerator(name="seq_logical_name",sequenceName="seq_user_id")
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_logical_name")
@Column(name="id1")
private long id;

@Column(name="name1")
private String name;

@OneToMany(targetEntity=org.sample.mapping.AddressVO.class,cascade=CascadeType.ALL,mappedBy="userInfo") //@JoinColumn(name="user_id")
private List addressList;


public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public List getAddressList() {
return addressList;
}
public void setAddressList(List addressList) {
this.addressList = addressList;
}
}


@Entity
@Table(name="ADDRESS")
public class AddressVO {

@Id
@SequenceGenerator(name="seq_address_logical_name", sequenceName="seq_address_id")
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq_address_logical_name")
@Column(name="id1")
private long id;

@Column(name="name1")
private String name;

@ManyToOne()
@JoinColumn(name="user_id",nullable=false)
private UserVO userInfo;

public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UserVO getUserInfo() {
return userInfo;
}
public void setUserInfo(UserVO userInfo) {
this.userInfo = userInfo;
}


}

Friday, August 20, 2010

JSF

Benefits of JSF

Page navigation specification
Standard user interface components like input fields, buttons, and links
User input validation
Easy error handling
Java bean management
Event handling
Internationalization support

JSF Life Cycle

Restore View PhaseApply Request Values PhaseProcess Validations PhaseUpdate Model Values PhaseInvoke Application PhaseRender Response Phase

JSF JARS

jsf-impl.jar
jsf-api.jar
faces-config.xml

TAG LIBRARIES

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

SAMPLE CONFIG FILE

<?xml version="1.0"?>
lt;!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">

<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">

<faces-config>
<navigation-rule>
<from-view-id>/pages/inputname.jsp</from-view-id>
<navigation-case>
<from-outcome>greeting</from-outcome>
<to-view-id>/pages/greeting.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<managed-bean>
<managed-bean-name>personBean</managed-bean-name>
<managed-bean-class>jsfks.PersonBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</faces-config>

SAMPLE WEB.XML FILE

<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<!-- Just here so the JSF implementation can initialize -->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>

SAMPLE JSP CODE

<html>
<body>
<f:view>
<h:form id="person">
<h:commandLink id="Details"
action="editBook"
actionListener="#{personBean.getDetails}">
<h:outputText value="Add a book" />
</h:commandLink>
</h:form>
</f:view>
</body>
</html>

Sunday, April 18, 2010

JBoss Basic Authentication

1) In web.xml, enable basic authentication
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>default</realm-name>
</login-config>

2) In jboss-web.xml, set security domain
<jboss-web>
<security-domain>java:/jaas/Sample</security-domain>
<context-root>testProject</context-root>
</jboss-web>

3) In login-config.xml file, add entry for "securoty domain" id mentioned in step2.

<application-policy name = "Sample">
<authentication>
<login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule" flag="required"/>
</authentication>
</application>

4) In users.properties file, add username & password entries.
Users entered in this file only can access the resources.

******************************************************************************

Miscellaneous :-
1) For enabling directory listing, don't put any entry for "welcome file list" in web.xml. Also don't put any html file in ROOT directory of war file.

In jboss4.2.3, in server >> default >> deploy >> jboss-web.deployer >> conf >> web.xml, make listing "true" for DefaultServlet InitParameter.

Thursday, April 1, 2010

MAVEN

Maven is a project Management tool which handles
Dependency Management,
Executing PlugIn Goals,
Defining Project Object Model,
Project life cycle.

Maven can Build, run reports, generate site.

Maven Default Project Structure

${basedir}/src/main/java -- Java Source Directory
${basedir}/src/main/webapp -- Web(JSP, JS, Images, CSS) Directory
${basedir}/src/main/resource -- Resources (properties file etc)
${basedir}/src/test -- test classes
${basedir}/target/classes -- Compiled source output Directory

Maven delegates responsibilities to PlugIns.
e.g.
mvn install uses Maven PlugIn for creating New project.
SureFire plugin is for JUnit test execution.

Maven Important Commands
mvn clean -- Clean Project Workspace
mvn validate -- Validates POM file
mvn test -- Execute Test Cases
mvn package -- Compile & Package artifacts
mvn install -- Deploy artifacts in maven local repository
mvn deploy -- Installs artifact in maven remote repository
mvn site -- Creates site based on contents from /src/site folder
mvn:exec:java -Dexec.mainClass=org.sample.payment.forex -Dexec.args="INR"

mvn help:describe -Dplugin=surefire -- Display help for given plugin
mvn:help effective-pom -- Effective POM for given project
mvn archetype:create -DgroupId=com.sample.payment -DartifactId=forex -DpackageName=com.sample.payment -Dversion=1.0 -- Create New project with default folder structure

Artifacts are stored in repositories in following naming convention
/<groupId>/<artifactId>/<version>/<artifactId>-<version>.<packaging>

Project Versions naming are as follows <major>.<minor>.<incremental>-<qualifier>

If a project contains multiple projects then move common dependencies
to Parent project. So version change for dependencies will be at one
place only. Also group PlugInDependencies in parent project.

Every Maven project includes super-pom.xml file which has common maven tasks
like clean, package, text, install etc

Maven Best Practices
1) Group dependencies :- Create Parent project for big project containing many modules.
& Centralize dependencies in Parent project.

2) "env" variables are accessible in Maven.
e.g:- For Linux, ${JAVA_HOME} will return java home from "env".

3) Project variables can be accessed in including subprojects by using suffix
project for the property
e.g.:- ${project.groupId}

4) settings variable exposes Maven settings information.

Dependency Type
1)Compile :- Default setting. Package specified Jars in final artifacts.
2)Provided :- Dependency jars provided by container like servlet.jar, jta.jar.
3)Test :- Dependency jars used for only testing.
4)Runtime :-
5)System

Build Profiles:- Profiles allow to customize build for particular environments.
e.g. Production, Staging, Development, Testing
mvn clean install -Pproduction

Assembly plugin
Assembly plugin helps in creating custom archievies for projects.
Predefined assembly descrriptors
bin :- It packages LICENSE, README, NOTICE files.
jar-with-dependencies :- It packages jar with unpacked contents of runtime dependencies.It adds Main-Class entry in Manifest.mf file.
project :- It packages project directory structure as it exists in file system.
src :- It packages project directory structure, LICENSE, READ ME, NOTICE, POM.xml file.
Assembly plugin can be executed by binding it to project life cycle.

Wednesday, February 17, 2010

WebServices

POJO WebService & ADB Client
1) Write POJO class with required business logic.
2) Create AAR file & copy it into "services" folder of AXIS2.war
3) Start server & create ADB client using following command
WSDL2Java -p org.sample.stub -uri http://localhost:8080/axis2/services/BankingService?wsdl
4) Create Client class & access webservice using WebServiceClient stub created in step 3.

POJO Class:-

package org.sample.service;

import org.sample.util.EmployeeInfo;

public class BankingService {

public EmployeeInfo employeeDetails(String empno)
{
EmployeeInfo empInfo = new EmployeeInfo();

empInfo.setName("ABC");
empInfo.setEmployeeID(1111111);

return empInfo;
}

}


package org.sample.util;

public class EmployeeInfo{

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

CLIENT Class
package org.sample.stub;

import java.rmi.RemoteException;
import org.sample.stub.BankingServiceStub.EmployeeInfo;

public class Client {

public static void main(String[] args)
{
try {

String URL = "http://localhost:8080/axis2/services/BankingService";

BankingServiceStub stub = new BankingServiceStub(URL);

BankingServiceStub.EmployeeDetails empDetails = new BankingServiceStub.EmployeeDetails();

empDetails.setEmpno("a");

BankingServiceStub.EmployeeDetailsResponse empDtl = stub.employeeDetails(empDetails);

EmployeeInfo empInfo = (EmployeeInfo)empDtl.local_return;

System.out.println("Emp Id " + empInfo.getEmployeeID());
} catch (AxisFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

RPCClient
public static void main(String[] args1) throws AxisFault {

RPCServiceClient serviceClient = new RPCServiceClient();

Options options = serviceClient.getOptions();

EndpointReference targetEPR
= new EndpointReference(
"http://localhost:8080/axis2/services/BankingService");

options.setTo(targetEPR);

// Get the weather (no setting, the Spring Framework has already initialized it for us)
QName opGetResult = new QName("http://service.sample.org", "employeeDetails");

String name = "abc";

Object[] opGetResultArgs = new Object[] {name};
Class[] returnTypes = new Class[] { EmployeeInfo.class };

Object[] response = serviceClient.invokeBlocking(opGetResult,
opGetResultArgs, returnTypes);

EmployeeInfo result = (EmployeeInfo) response[0];

// display results
if (result == null) {
System.out.println("No data found!");
}else{
System.out.println("Emp Record " + result.getName());
}
}

}

Friday, January 8, 2010

Applet Remote Debugging Using Eclipse

Following are the steps for remote debugging applets in eclipse.
1) GoTo settings >> Control Panel >> Java.
2)In Java >> View, add following text in "Runtime Parameters"

-Djava.compiler=NONE -Xnoagent -Xdebug -Xrunjdwp:transport=dt_socket,address=1045,server=y,suspend=y


3) Configure Remote Debugging in Eclipse. Give port as 1045(Or any port that you are using).



4) Start browser. Navigate to the page containing Applet.

5) As soon as Applet starts getting loaded, in eclipse it will stop at breakpoint & user can debug as normal java debugging.

6)Sometimes browser may get hanged or crashed, in such cases disconnect debugging from Eclipse & Click on page containing applet & then relaunch remote debugging in Eclipse.