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.