Tuesday, October 5, 2010

Loading MySQL Driver in WebLogic 10.3.



I got in an awkward situation when I discovered that after putting the jar file (mysql-connector-java-5.1.5-bin) in the project classpath , my application was able to connect to the database but when I tried to deploy it in WebLogic 10.3 got exceptions . They are as follows-

• weblogic.common.resourcepool.
ResourceSystemException

• weblogic .jdbc.module.JDBCModule.
prepare


I found it difficult as I was working around it for 2 days just biting around the bush . At last i found the way to resolve it which I will be posting now. Figure below describes the stack trace of exceptions.






Prerequisites:

mysql-connector-java-5.1.5-bin.jar (jar file)
Jdeveloper 11g
WebLogic 10.3
MySQL Server 5.0


Steps that needs to followed :-

1. Copy the MySQL jar file specified above and put it inside the integrated WebLogic server i.e wlserver_10.3\server\lib as shown in the figure below.








2. Rename the file to weblogic_sp.jar because it is already present as a default which programmers can make use of it. That’s it , just need to restart your application server after this and you can deploy your application. This holds good for other database like Derby etc.

3. If you are not using the default jar file then paste the jar file as it is in the above specified location . Then add a weblogic classpath setting in the file commEnv.cmd present in the wlserver_10.3\common\bin. The changes are specified in the code snippet below.


Code Snippet:



@rem set up WebLogic Server's class path and config tools classpath
set WEBLOGIC_CLASSPATH=%JAVA_HOME%\lib\tools.jar;
%WL_HOME%\server\lib\weblogic_sp.jar;
%WL_HOME%\server\lib\weblogic.jar;
%WL_HOME%\server\lib\mysql-connector-java-5.1.5-bin.jar;




Creating a JNDI Name for MySQL :

My application will require the JNDI name for connecting to the database of MySQL. Fulfilling the same I need to create a JDBC Data Source. I have jotted down the steps for doing that too. They are stated as under.


Steps:

1. Goto the WebLogic console screen i.e http://localhost:7101/console and login with your userid and password.





2. Choose the Data Sources under JDBC as shown in the picture below.







3. Supply the connection name and JNDI name along with database type as shown under.







4. Select the driver you wish to use which is com.mysql.jdbc.Driver in my case.








5. Click Next with the default selection.






6. Provide the necessary information that is required for establishing connection to the MySQL. Below is the pictorial representation.






7. Click on the Test Configuration for testing the connection.







8. At the end success message is displayed , if the connection test is successful.






9. As indicated in the below picture a connection named MySQLConn and JNDI name MySQLConnDS is created in the Application Server which we can use it in the application.







10. Creating Database connections from the application end with the values shown below.






11. Then tried to deploy in the application server and the result I got was worth watching after all the troublesome i.e SUCCESS.







Right now there was some light thrown by one of my colleague (Pino) for another possible way or work around which could be an easiest way to deal with Jar complexities. So I am overburdened as I need to figure that out too.

Have a Good Day !!!

Sunday, September 26, 2010

Custom Converter Implementation.




Need for Custom Converter:

Let’s say we have an unique requirement of changing the inputted string to its Uppercase type. So we don’t have any specific Standard Converter who accomplishes the above objective. In that case we need to create a new class which handles the above requirement.


Implementation of Custom Converters:

JSF Page:




<f:subview id="converter3">
<h:form>
<br/>
<br/>
<h:outputLabel value="UpperCase Converter :"/>
<h:inputText id="text1" converter="uppercaseConverter"
converterMessage="Not a String"
value="#{startPage.converterChangeCase}"
onchange="submit()"/>
<h:message for="text1"/>
</h:form>
</f:subview>



Explanation:

Here the <h:inputText> tag has an attribute converter which is mapped in the faces-config.xml which finally points to the provider class i.e UppercaseConverter.java in our case.


Faces-config.xml:




<faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee">
<managed-bean>
<managed-bean-name>startPage</managed-bean-name>
<managed-bean-class>com.java.jsf.view.backing.StartPage</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<!--oracle-jdev-comment:managed-bean-jsp-link:1WEB-INF/pages/start_page.jspx-->
</managed-bean>
<converter>
<converter-id>uppercaseConverter</converter-id>
<converter-class> com.java.jsf.view.util.UpperCaseConverter
</converter-class>
</converter>
</faces-config>



Explanation:

Well, a custom converter before being used has to be specified inside the faces-config.xml. This is done by using <converter> paired tag which has <converter-id> and <converter-class> as child tags in it which specifies the address of the converter class.

Converter Class:




public class UpperCaseConverter implements Converter{
public Object getAsObject(FacesContext facesContext,UIComponent component,String stringValue){
return stringValue.toUpperCase();
}

public String getAsString(FacesContext facesContext,
UIComponent uiComponent, Object objectValue) {
return objectValue.toString();
}
}



Explanation:

The custom converter class should implement Converter interface. Another important factor that you have to take note of is that, it should implement two abstract methods in the class Converter. They are as follows-
getAsObject() [Converts from String user input to Object]
getAsString() [Converts from Object to String & back to screen]


Managed Bean :




public class StartPage{
private String converterChangeCase;

public void setConverterChangeCase(String converterChangeCase) {
System.out.println("Change Case : "+converterChangeCase);
this.converterChangeCase = converterChangeCase;
}

public String getConverterChangeCase(){
return converterChangeCase;
}
}




Explanation:

The managed bean has got an attribute converterChangeCase along with its accessor methods which is finally receives the input from the JSF component. This can be verified from the sys-out statement present inside the setter method.

Hope this will help you in creating your own customized CONVERTERS.
Good Night !!!

Saturday, September 25, 2010

Standard Converters ...




Need for Conversion:


Converter is a hot topic in JSF as it makes the life of a developer easy. Let us assume that we have an input form where it accepts name, age and date of birth. The corresponding managed bean will have attributes having data types String, Integer and Date. But values are entered as String which needs to be converted to its appropriate type before the accessors accepts it.


Standard Converters:

These converters are already defined in JSF for most of the common conversion process. Some of them are as follows:


•javax.faces.Double
• javax.faces.Integer
• javax.faces.Float
• javax.faces.Boolean

Implementation of Standard Converters:


JSF Page:



<f:view>
<f:subview id="converter1">
<h:form>
<br/>
<br/>
<h:outputLabel value="Date Converter :"/>
<h:inputText id="text"
value="#{startPage.converterDate}"
onchange="submit()">
<f:convertDateTime pattern="yyyy/MM/dd" type="date"/>
</h:inputText>
<h:message for="text"/>
<br/>
</h:form>
</f:subview>
<f:subview id="converter2">
<h:form>
<br/>
<br/>
<h:outputLabel value="Integer Converter :"/>
<h:inputText id="text2"
value="#{startPage.converterAge}"
onchange="submit()"
converter="javax.faces.Integer"/>
<h:message for="text2"/>
<br/>
</h:form>
</f:subview>
<f:view>



Explanation:

The first converter enclosed within the <f:subview> tag intends to accept a String and converts it to a Date Object. The above objective is achieved by the <f:convertDateTime> tag which defines the format of the date with the help of pattern attribute and the type attribute conveys the model to receive a Date object.
The second converter enclosed within the <f:subview> tag accepts in String format and converts it to Integer using interface (javax.faces.Integer). The use of converter attribute accomplishes the task.


Managed Bean:




private Date converterDate;
private int converterAge;

public void setConverterDate(Date converterDate) {
System.out.println("Date Entered : "+converterDate);
this.converterDate = converterDate;
}
public Date getConverterDate() {
return converterDate;
}
public void setConverterAge(int converterAge) {
System.out.println("Age Entered : "+converterAge);
this.converterAge = converterAge;
}

public int getConverterAge() {
return converterAge;

}




Explanation:

The model represents two attributes i.e converterDate and converterAge with Date and Integer data type respectively. For verification purpose you can check by including a sys-out statement inside the setters as shown in the example.

Upcoming post will be basically targeting the “Custom Converter Implementation”. So stay tuned 'n' focused.

Cheers !!!

Thursday, September 23, 2010

Password Encryption ‘n’ Decryption.




What is MD5?

The MD5 hash also known as checksum for a file is a 128-bit value, something like a fingerprint of the file. There is a very small possibility of getting two identical hashes of two different files. This feature can be useful both for comparing the files and their integrity control. MD5 (Message-Digest algorithm 5) is a widely used cryptographic hash function. It has been employed in a wide variety of security applications. An MD5 hash is typically expressed as a 32-digit hexadecimal number.

Encryption is used for converting a given String value to its equivalent hexadecimal code. Decryption is nothing but just the vice versa.

MD5.java:





public class MD5 {

public static String digest(String text) throws NoSuchAlgorithmException,
UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] md5hash = new byte[32];
md.update(text.getBytes("iso-8859-1"), 0, text.length());
md5hash = md.digest();
return convertToHex(md5hash);
}

private static String convertToHex(byte[] b) {
StringBuilder result = new StringBuilder(32);
for (int i = 0; i < b.length; i++) {
result.append(Integer.toString((b[i] & 0xff) + 0x100, 16)
.substring(1));
}
System.out.println(result.toString());
return result.toString();
}

}




Explanation:


The first getInstance() method accepts an argument, which is suppose to be the algorithm to be used i.e MD5 ,SHA ,SHA1 etc. If no provider can be found that implements the given algorithm, a NoSuchAlgorithmException is thrown. If the named provider cannot be found, a NoSuchProviderException is thrown.


Then comes the update() method which accepts three arguments i.e (byte[] input, int offset, int length) and suppose to be the subset of the array of data. This method may be called any number of times to add the desired data to the digest.


After the data is accumulated we have to compute the data using digest() method. The resulting digest is returned as a byte array. Once a digest has been calculated, the internal state of the algorithm is reset.


The resulting byte array is then transformed to corresponding hexadecimal equivalent in the convertToHex() method. Now the encrypted format of the string is ready to be used in your project.


Friday, September 17, 2010

Preselection in SelectManyCheckBox



Guys today I want to share something very simple but yet will haunt your precious time while you deal with it. While implementing <h:selectManyCheckBox> ,i found that the selected values are easily available in the managed bean specifically in a list variable. But it was weird when I say the component was not loaded with previously selected values. This session basically aims at loading the above component with pre selected values as I have achieved success in resolving it.

Prerequisites:

1) richfaces-api-3.3.0.GA

2) richfaces-impl-3.3.0.GA

3) richfaces-ui-3.3.0.GA

4) Following taglibs should be included at the top of the page to get ajax and richfaces support.


<%@ taglib uri="http://richfaces.org/a4j" prefix="a4j"%>
<%@ taglib uri="http://richfaces.org/rich" prefix="rich"%>


JSF Page:



<%@ taglib uri="http://richfaces.org/a4j" prefix="a4j"%>
<%@ taglib uri="http://richfaces.org/rich" prefix="rich"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:subview id="manyCheck">
<h:form>
<h:selectManyCheckbox id="contact" value="#{echoBean.contact}">
<f:selectItem itemLabel="All" itemValue="All" />
<f:selectItem itemLabel="Phone" itemValue="Phone" />
<f:selectItem itemLabel="Mob" itemValue="Mob" />
<f:selectItem itemLabel="Email" itemValue="Email" />
<f:selectItem itemLabel="Fax" itemValue="Fax" />
<a4j:support event="onchange" action="#{echoBean.saveManyCheckBox}" reRender="as"/>
</h:selectManyCheckbox>
</h:form>
</f:subview>
<f:subview id="manyCheck1">
<a4j:form id="as">
<h:selectManyCheckbox id="contact1" value="#{echoBean.resultList}" rendered="#!{echoBean.resultList}">
<f:selectItem itemLabel="All" itemValue="All" />
<f:selectItem itemLabel="Phone" itemValue="Phone" />
<f:selectItem itemLabel="Mob" itemValue="Mob" />
<f:selectItem itemLabel="Email" itemValue="Email" />
<f:selectItem itemLabel="Fax" itemValue="Fax" />
</h:selectManyCheckbox>
</a4j:form>
</f:subview>




Explanation:

The above jsf code has got two selectManyCheckBox component. First one will accept the user input and the second one will display the user selection using AJAX tag i.e <a4j:support>. On change of the first component saveManyCheckBox() method will be invoked.

The value of the list is interchanged with another list i.e resultList which is responsible for populating the subsequent component.
Instead of <h:form>, I have used <a4j:form> so as to render the portion of the page through AJAX.


Managed Bean:(EchoBean.java)



private List contact;

private List resultList;

// Setters & Getters to be created

public void saveManyCheckBox() {

System.out.println("In saveManyCheck");
System.out.println("Before List Values:" + contact);
String str = this.list2String(this.contact);
System.out.println("STR Values:" + str);
resultList = this.string2List(str);
System.out.println("ResultList Values:" + resultList);

}


public List string2List(String str) {
List list = new ArrayList();
String str1 = str.replaceAll("[\\]\\[]", "");
StringTokenizer tokens = new StringTokenizer(str1, ",");
int i = 0;
while (tokens.hasMoreTokens()) {
String f = tokens.nextToken();
list.add(f.trim());
i++;
}
return list;
}

public String list2String(List list) {
String str = null;
str = list.toString();
return str;
}



Explanation:

The saveManyCheckBox() accepts the inputed value from contact(List) and then transforms it to String in the list2String().

The second method i.e string2List() is responsible for chopping the string “[x,y,z]” into segregated values called as tokens like x y z and then adding it to the resultList(List). This resultList is responsible for displaying the user selected values instantly.

Before making the above example work properly you have to make some configuration changes for your deployment descriptor(WEB.XML) for AJAX and Rich Faces.
I hope you can figure that out.

Saturday, September 11, 2010

Quartz Scheduling in Console Application


Prerequisites:

1) quartz-all-1.6.4.jar

2) commons-collections-3.1.jar

3) commons-codec-1.3.jar

4) commons-digester-1.8.jar

5) commons-logging-1.0.4.jar

6) commons-io.jar

7) jta.jar

8) commons-beanutils-1.7.0.jar

All the above mentioned jar files should be available inside the project build path>libraries.

Please note the instructions are related to eclipse europa 3.4 IDE.

Conceptual Touch:

•Quartz is an open source software provided by Open Symphony and which can be downloaded from http://www.opensymphony.com.

•It is a full-featured , open source job scheduling framework written entirely in Java. It can be integrated with J2SE & J2EE with smallest standalone to largest e-commerce system.

•Job Scheduler is a system that is responsible for executing other software components when a predetermined (scheduled) time arrives.

•It is distribured as a small java library (.jar file). Its important functionalities are like scheduling jobs, unscheduling jobs, starting/stopping/pausing the scheduler.

•If you want to schedule your software components then it must implement the Job Interface which overrides the execute() method.

•If you want components to notify when scheduled fire time arrives , then you should implement either TriggerListener / JobListener interface.

• Two important tasks need to be done beforehand. Firstly configure the Job class then secondly set up the schedule. When the scheduler determines the notifying time to your job, the quartz framework will call the execute() method on your Job class.

•Triggers are of two types i.e Simple trigger and Cron Trigger. Simple trigger is used for single execution of job at a given moment of time and have it repeat N times with a delay of T between executions. Cron trigger is used when you want triggers based on calendar like schedules such as Saturday, at noon or at 12.35 on the 15th day of every month.


Steps to do:


1) Create the instance of ScheduledFactory by getting the reference of org.quartz.impl.StdSchedulerFactory class.

2) Invoke the getScheduler() by this instance to instantiate the scheduler.

3) In execute() method , must implement the Job interface for software components scheduling.


Implementation of Simple Trigger:

HelloSchedule.java



package com.odisys.test;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;

public class HelloSchedule {
public HelloSchedule() throws Exception {
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler schedule = sf.getScheduler();
schedule.start();
//long ts = Long.parseLong("October 24, 2009, 11:03:00 IST");

JobDetail jd = new JobDetail("myjob", schedule.DEFAULT_GROUP,
HelloJob.class);
SimpleTrigger st = new SimpleTrigger("mytrigger", schedule.DEFAULT_GROUP,new Date(getCurrentDate()), null, 4, 60L * 1000L);
schedule.scheduleJob(jd, st);
}

public static long getCurrentDate() throws ParseException {
DateFormat dateFormat = new SimpleDateFormat();
Date date = new Date();
String currentDate = (dateFormat.format(date));
Date dt2 = new SimpleDateFormat().parse(currentDate);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(dt2);
long milliseconds1 = calendar2.getTimeInMillis();
return milliseconds1;
}

public static void main(String args[]) {
try {
new HelloSchedule();
} catch (Exception e) {
}
}
}



Explanation:

In the HelloSchedule.java, I have created an instance out of getScheduler() method. Then a job is defined based upon the HelloJob class. The final step is to supply the time interval parameters to the SimpleTrigger i.e 60L*1000L milliseconds. The getCurrentDate() method eventually checks for the appropriate time to come with regards to the interval defined. Once the interval of delay is achieved, it triggers a call to the HelloJob class where the execute() method is defined.

HelloJob.java




package com.odisys.test;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.util.Date;

public class HelloJob implements Job {
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("Hello World Quartz Scheduler: " + new Date());
//System.exit(0);
}
}





Explanation:

Upon call to the execute() method defined inside the HelloJob.class , it performs an output statement which can be verified in the console screen. The screenshot of the console screen is given below.







This session was just meant to give you the first taste of Scheduling Mechanism .In the upcoming sessions our prior motto will be to implement Cron Trigger in a web application which I am still working on.

Thank you for still holding on to your patience.

Friday, September 10, 2010

log4j implementation in Web application .



Prerequisites:

1) Create a log4j.properties file inside the src folder of your project as shown in the screen below.



2) Copy the log4j-1.2.11.jar inside the WEB-INF/lib folder also displayed in the screen below.



3) Application Server used in this case is Tomcat 6.0.


Log4j.properties:



### direct log messages to a file ###
log4j.appender.file=org.apache.log4j.FileAppender

log4j.appender.file.File=C:/apache-tomcat-6.0.18/logs/ideapokebeta.log

log4j.appender.file.layout=org.apache.log4j.PatternLayout

log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=info, file
log4j.logger.javax.faces =debug


Explanation:

The file (log4j.properties) created earlier needs to be pasted with the above lines of code. After pasting, you have to check for your Tomcat’s location in your computer, copy it and paste it against “log4j.appender.file.File“. Beforehand you need to create a .log file and paste it in the logs folder of Tomcat.

Implementation :

Code Snippet(java class):




public class ForgotPassword
{
private String fullname;
private String email;
private boolean exist;
private UserLogin userLogin;
private static Log log = LogFactory.getLog(ForgotPassword.class);
// Setter & Getter Methods Starts //
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isExist() {
return exist;}

public void setExist(boolean exist) {
this.exist = exist;
}
// Setter & Getter Methods ends here //

// forgot Method is called for sending the password to email provided //
public String forgot() throws Exception
{
String status="failure";
exist=false;
String[] to = new String[1];
HibernateSpringDAO dao = (HibernateSpringDAO)ServiceFinder.findBean("SpringHibernateDao");
dao1=(HibernateSpringDAO)ServiceFinder.findBean("mailbean");
if(!this.getEmail().equals("") && (dao.validateEmailOnly(this.getEmail())!=null))
{
exist=true;
userLogin=dao.validateEmailOnly(this.getEmail());
String pass = userLogin.getPassword();
String fullname = userLogin.getFullName();
String userEmail = userLogin.getLoginId();
to[0] = userEmail;
String from="admin@ideapoke.com";
String subject="Your User Id And Password !!!";
String message="Hi,"+fullname;

message+="\n Your password is "+pass+".";
message+="\n Please login to the web site with your password given.";
message+="\n \n Thanks";
message+="\n \n \n Regards";
System.out.println(message);
try{
(new SendMail()).sendMail(to, subject, message, from);
}
catch(Exception ex)
{
log.info(ex.getMessage());
}
status="success";
}
return status;
}
}




Explanation:

The above code represents a forgot password process whose objective is to mail the password information to the user’s registered mail box.
The log4j implementation starts with the initialization process which takes an argument of the class name as a parameter. The getLog() method is responsible for taking an input i.e ForgotPassword.class in my case. The statement responsible for sending mail is enclosed within a try catch block which we assume will be throwing an exception. The exception is caught and channelized to the log file with the help of log.info(message) method. Now we can verify the log inputs by cross checking the log file. We have some methods like debug(), warn(),trace() etc which we can make use according to situations. The screenshot for the log file result is given below.



These steps can be followed for implementing log4j in your web application. I think this will suffice your requirements and if not, just post comments regarding the difficulties you face, I will try to make things happen for you.
Looking forward to blog regarding Scheduler in my next session.

Thursday, September 9, 2010

Passing parameters through faces-config.xml.


View Page:


Code Snippet-1



<f:view>
<h1>Welcome to Account Activation Page</h1>
<h:form>
<h:outputText value="Please click on the link below to activate your account."/>
<h:commandLink value="http://localhost:8080/IdeaPoke/jsp/activation-page.jsf" action="#{ActivateUser.activate}">
<f:param name="key" value="#{ActivateUser.queryString}"/>
</h:commandLink>
</h:form>
</f:view>



Explanation:


The above code(CS -1) introduces an attribute <f:param> within the <h:commandLink> which suggests that it will be holding on to a value named queryString and pass it to the faces-config.xml file whenever the link is clicked. The value to the attribute queryString is attached with a reference name i.e “key” which practically acts as the carrier.

Managed Bean (ActivateUser):

Code Snippet-2





public class ActivateUser
{
private String key;
private String queryString;

// Setter & Getter Methods started here //
public String getKey() {
return key;
}

public void setKey(String key) {
this.key = key;
}

public String getQueryString() throws DataAccessException,SQLException{

// Database connection established here

HibernateSpringDAOdao=(HibernateSpringDAO)ServiceFinder.findBean("SpringHibernateDao");
userLogin=dao.getLastRecordId();
// Value retrieved and assigned to queryString
setQueryString(userLogin.getVerificationKey());
System.out.println(queryString);
return queryString;
}

public void setQueryString(String queryString) {
this.queryString = queryString;
}
// Setter & Getter Methods ended here //


public String activate() throws Exception {
String status = "failure";
String key_value = (FacesContext.getCurrentInstance()
.getExternalContext().getRequestParameterMap().get("key"));
return status;
}

}







Explanation:

At the time of page load (view page), it invokes getQueryString() method which retrieves the persisted value from the database and is available in the view page. The “SpringHibernateDao” is the bean which we will be interacting while making any database transactions. Since this is not our concern right now, so we will leave that for now.
The event starts when the user clicks on the link. The activate() method is triggered which retrieves the parameter value based on the object “key” through the getRequestParameterMap() method.


Faces-config.xml:


Code Snippet-3




<managed-bean>
<managed-bean-name>ActivateUser</managed-bean-name>
<managed-bean-class>com.login.action.ActivateUser</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>key</property-name>
<value>#{param.key}</value>
</managed-property>
</managed-bean>


<navigation-rule>
<from-view-id>/jsp/activation-page.jsp</from-view-id>
<navigation-case>
<from-action>#{ActivateUser.activate}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/jsp/login.jsp</to-view-id>
</navigation-case>
</navigation-rule>




Explanation:

I would like to bring to your notice the addition of an attribute <managed-property> which encloses two new parameters <property-name> and <value> in CS -3 . This attribute is actually responsible for transmission of value from one page to another.
The rest of the code is normal which defines a page navigation rule, hence after clicking the link the user will carried forward to login.jsp.

Inputs from your end will be highly appreciated.
Looking forward to implement log4j inside a web application.



** CS means Code Snippet

Wednesday, September 8, 2010

Interacting with Session Objects in JSF.


In this session I will try to bring small tips n tricks to lime light for enhancing JSF capabilities. We will first see how an user information is tracked in session.

Setting Session object in jsf:

Code Snippet-1




FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession)
context.getExternalContext().getSession(true);
session.setAttribute("emailid",this.getEmaillogin());
session.setAttribute("networkID",this.getNetworkId());

InetAddress thisIp = InetAddress.getLocalHost();
String ip=thisIp.getHostAddress();
String reg_geography=TimeZone.getDefault().getID();




Getting Session object in jsf:

Code Snippet-2




FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession)
context.getExternalContext().getSession(true);
setEmailid(session.getAttribute("emailid").toString());




Terminating Session object in jsf:

Code Snippet-3



HttpSession session = (HttpSession)
FacesContext.getCurrentInstance().getExternalContext().getSession(false);
FacesUtils.resetManagedBean("UserRegistration");
if (session != null) {
session.invalidate();
}



Explanation:

Conceptually, you can think of FacesContext as the class that has all the stuff you need to interact with the UI and the rest of the JSF environment. The JSF implementation will either create a new instance for each request or choose one from a pool of available instances. Either way, there will be an instance available to you any time your application is interacting with a user.Technically, it represents the state of the current HTTP request.


For accessing the latest session object we need to call the getSession() based upon the current thread (context).Once we have the session object we can play around its given methods like setAttribute() and getAttribute().



The setAttribute() as its name suggests , it sets the attributes to a String object like “emailid” and “networkId” in our case illustrated in Code Snippet -1.After setting the String Object , the next step is to access it .This is accomplished by the getAttribute() method which we have to base it on the String Object like “emailid” in the Code Snippet -2.



Once we are done with the manipulation of the Session Object , the next big thing that comes to our mind is how to terminate the session.For achieving the above objective we require two methods i.e resetManagedBean() and session.invalidate() as displayed in Code Snippet -3.
resetManagedBean() method helps us to remove the managed bean based on the bean name, in our case “UserRegistration” is the bean .



This ends our current topic of discussion . I hope it will help you in some way or the other.
Stay tuned for the upcoming topic “Passing Parameters in faces-config.xml”.


Sunday, May 16, 2010

Google Suggest Implemented ....


Guys, this is my first blog that i have released so far. While working with the Seam framework, i have found out lots of tips n tricks which i will be sharing from now on. It took me a day to get it going in my project.

In the view page, just paste the code within the form.The rich:suggestionBox is having three attributes i.e minChars,for and suggestionAction which is worth noting. The first one is the character limit, which upon achieving triggers the calling of a method. Second one is a kind of notification sent to the container suggesting about the component(id) to which it has been applied.The final one is for triggering a method action which invokes autoComplete() written in the Java class that finally fetches data from the database.

Get the EntityManager object earlier as Ejb 3.0 has been used and then you are done i guess.


JSP CODE:

<h:inputText id="searchedVehicle" 
value="#{mapAction.searchedVehicle}" style="width:160px"
size="20"/>
<rich:suggestionbox height="150" width="163"
rules="#{suggestionBox.rules}" usingSuggestObjects="false"
nothingLabel="No Registration Number Found"
suggestionAction="#{mapAction.autoComplete}"
var="cap" minChars="5" for="searchedVehicle"
fetchValue="#{cap.registrationNumber}"
id="suggestion" tokens=",">
  <h:column>
    <h:outputText value="#{cap.registrationNumber}"/>
  </h:column>
</rich:suggestionbox>
<rich:spacer width="17px"/>




JAVA CODE:


public List autocomplete(Object suggest)
{
String pref= (String)suggest;
log.info("In Pref = "+pref);
ArrayList result = new ArrayList();
result.clear();
List resultList = new ArrayList();
resultList=entityManager.createQuery("from Vehicle vehicle where vehicle.registrationNumber like" + "'"+pref+"%'").getResultList();
log.info("IN AutoComplete = "+resultList.size());
return resultList;
}


JavaScript:


<Script type="text/javascript">
function printObjectsSelected(output,sgcomponent)
{
output.innerHTML=sgcomponent.getSelectedItems().pluck('state');
}
</Script>