Pages

Thursday, January 31, 2008

Implementing Quartz to Struts

Our Objective is we are going to implement Quartz to Struts Framework.



Anyway what is Quartz?
- Quartz is a full-featured, open source job scheduling system that can be integrated with, or used along side virtually any J2EE or J2SE application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components or EJBs. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering.(http://www.opensymphony.com/quartz/)


We are going to make an mail scheduler attached in our web application using the Struts framework. Quartz is pretty simple and straight forward, All we need to do is implement the Job (org.quartz.Job) and instantiate the implementation. After doing that Quartz stuff we will implement the Struts Plugin (org.apache.struts.action.PlugIn) and will map the our made plugin to Struts-config.xml.

lets get started.

------------------------------------------------------------------------
1. We'll make an Java class that will implement the Job (org.quartz.Job).
sample below.

import Constants;
import MailDetails;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
*MailNewsletterJob.java
* @author amontejo
*/
public class MailNewsletterJob implements Job {

public void execute(JobExecutionContext context) throws JobExecutionException {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException c) {
System.out.println("Class not found!");
}
try {
String strUser = Constants.USER;
String strPassword = Constants.password;
String strDatabase = Constants.DATABASE;
String strServer = Constants.SERVER;
int mysqlport = Constants.PORT;
String url = "jdbc:mysql://" + strServer + ":" + mysqlport + "/" + strDatabase;
Properties props = new Properties();
props.setProperty("user", strUser);
props.setProperty("password", strPassword);
try {
con = DriverManager.getConnection(url, props);
} catch (SQLException sqle) {
sqle.printStackTrace();
}

try {//email newsletter
MailDetails maildetails = new MailDetails();
mailer.postMail(con, maildetails.getRecipients(), "Sample Mail", message, "From Quartz");
}
} catch (Exception e) {
e.printStackTrace();
}
con.close();
} catch (Exception s) {
System.out.println("Doesn't establish the connection!");
System.exit(0);
}
}
}

Note: MailDetails is simple POJO that implement the Javamail API.
------------------------------------------------------------------------

2. We'll make an Java file that will instantiate the Job.

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

/**
*MailNewsletterScheduler.java
* @author amontejo
*/
public class MailNewsletterScheduler {

public MailNewsletterScheduler() throws Exception {
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sche = sf.getScheduler();
sche.start();
JobDetail jDetail = new JobDetail("Newsletter", "SampleNewsletterJob", MailNewsletterJob.class);
//"0 0 12 * * ?" Fire at 12pm (noon) every day
CronTrigger crTrigger = new CronTrigger("cronTrigger", "SampleNewsletterJob", "0 0 12 * * ?");
sche.scheduleJob(jDetail, crTrigger);
}
}

As you can see we to instantiate an JobDetails and pass as argument the Job that we made which is the MailNewsletterJob.class, and well create an Trigger to set when our Job will start to get working.

------------------------------------------------------------------------

3. Next is, we are going to create an implementation of the Struts Plugin.

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;

/**
*NewsLetter.java
* @author amontejo
*/
public class NewsLetter implements PlugIn {

public static final String PLUGIN_NAME_KEY = NewsLetter.class.getName();

public void init(ActionServlet servlet, ModuleConfig config)
throws ServletException {
try {
System.out.println("Initializing NewsLetter PlugIn");
ServletContext context = null;
context = servlet.getServletContext();
MailNewsletterScheduler objPlugin = new MailNewsletterScheduler();
context.setAttribute(PLUGIN_NAME_KEY, objPlugin);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

------------------------------------------------------------------------
4. And Lastly we will tell and map our plugin to Struts-config.xml.




Done! As you can see its pretty straight forward, we just create an implementation of Quartz Job,
instantiate the Job Details, Create an implementation of Struts Plugin and map to Struts configuration xml. See http://www.opensymphony.com/quartz/wikidocs/TutorialLesson1.html
more about Quartz Framework.

Saturday, January 26, 2008

Binding an Object into Session

Sometimes it is useful to know when an object is getting bound or unbound from a session object. For instance, in an application that binds a JDBC java.sql.Connection object to a session , it is important that the Connection be explicitly closed when the session is destroyed.

The javax.servlet.http.HttpSessionBindingListener interface handles this task. It includes two methods, valueBound() and valueUnbound(), that are called whenever the object that implements the interface is bound or unbound from a session, respectively. Each of these methods receives an HttpSessionBindingEvent object that provides the name of the object being bound/unbound and the session involved in the action. Here is an object that implements the HttpSessionBindingListener interface in order to make sure that a database connection is destroy.

below is the sample JDBC connection object binds to your Session.

/*
* SessionConnection.java
*/

import java.sql.*;
import javax.servlet.http.*;

/**
* @author amontejo
*/
public class SessionConnection implements HttpSessionBindingListener {

Connection connection;

/** Creates a new instance of SessionConnection */
public SessionConnection() {
this.connection = null;
}

public Connection getConection() {
return connection;
}

public void setConnection(Connection connection) {
this.connection = connection;
}

public void valueBound(HttpSessionBindingEvent event) {
if (connection != null) {
System.out.println("Binding a valid connection");
} else {
System.out.println("Binding a null connection");
}
}

public void valueUnbound(HttpSessionBindingEvent event) {
if (connection != null) {
System.out.println("Closing the bound connection as the session expires");
try {
connection.close();
} catch (SQLException ignore) {
}
}
}
}

As the Session expire the object will be closed too. You can set/check your session expiry in your web.xml.

<session-config>
<session-timeout>
30
</session-timeout>
<session-config>

-> means session expire within 30 minutes idle
see
HttpSessionBindingListener documentation here.
http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpSessionBindingListener.html

Tuesday, January 22, 2008

Sun To Acquire MySQL

I been using oracle database 3+ years already, doing with heavy query. From oracle forms, pushing oracle sql to its limit. Oracle database is really strong when it comes to security and also its SQL dialect has an rich inline function. I try to used MySql lately for some of our project, I was amaze of its performance, the query return so quickly and a lots of functionality also.

Now that Sun is about to acquire the MySql AB Lab, I think they are just a perfect chemistry for Web Application...

whats you think?...

Monday, January 21, 2008

Struts and Jmaki yahoo.dataTable/dojo.table using doAjax

Sample how to populate the yahoo/dojo table with doAjax using Struts+Jmaki.

Requirement:
so let start ...

1. Create an sample view page lets name as view.jsp

-------------------------------------------------------------------------
<%@ taglib prefix="a" uri="http://jmaki/v1.0/jsp" %>

<script type="text/javascript">

function reloadGrid(){
jmaki.doAjax({ url : "updaterow.do?refresh=true",
method : 'POST',
callback: function(_req) {
var rows = eval('(' + _req.responseText + ')');
jmaki.publish("/yahoo/dataTable/clear", { });
jmaki.log(_req.responseText);
jmaki.log("Rows: " + rows);
jmaki.getWidget('table1').addRows({value : rows});
}
});
}

</script>


<a:widget name="yahoo.dataTable" id="table1" service="/view.do">
</a:widget>
-------------------------------------------------------------------------

2. We will create an jsp page that will return JSon script, thus this will used to feed to the table widgets. We will name it as data.jsp

-------------------------------------------------------------------------
<%@ page import="java.util.List,java.util.Iterator, java.util.ArrayList, bean.data" %>

{scrollable:true},
{
columns :[
{'label' : 'Field1.', 'id' : 'field1', width : 125},
{'label' : 'Field2.', 'id' : 'field2', width : 125},
{'label' : 'Field3.', 'id' : 'field3', width : 125},
{'label' : 'Field4.', 'id' : 'field4', width : 125},
{'label' : 'Field5.', 'id' : 'field5', width : 125},
{'label' : 'Field6.', 'id' : 'field6', width : 125},
{'label' : 'Field7.', 'id' : 'field7', width : 125}
],

rows : [

<% ArrayList results = (ArrayList) request.getAttribute("data"); if (results != null) { Iterator it = results.iterator(); bean.data prevlist = null; while (it.hasNext()) { prevlist = (bean.data) it.next(); %>
{'field1' : '<%=prevlist.getField1()%>',
'field2' : '<%=prevlist.getField1%>',
'field3' : '<%=prevlist.getField1%>',
'field4' : '<%=prevlist.getField1%>',
'field5' : '<%=prevlist.getField1%>',
'field6' : '<%= fw.utils.getField1 %>',
'field7' : '<%=prevlist.getField1 %>'
}
<% if (it.hasNext()) { out.println(","); } %>
<% } }%>
]
}

-------------------------------------------------------------------------

3. Map your data.jsp to your struts-config.xml.
sample below

-------------------------------------------------------------------------
<action input="/view.jsp"
path="/view"
scope="request"
type="com.sample.ViewAction">
<forward name="success" path="/data.jsp"/>
</action>
-------------------------------------------------------------------------

4. Make a jsp files that will poplulate the row of the grid upon calling the doAjax,
lets name it as row.jsp, this should return as JSon script that will feed to the table
widgets. And map the jsp page to the struts-config.xml.

-------------------------------------------------------------------------
<%@ page import="java.util.List,java.util.Iterator, java.util.ArrayList, bean.data" %>

[
<%
ArrayList results = (ArrayList) request.getAttribute("data");

if (results != null) {
Iterator it = results.iterator();
bean.data prevlist = null;
while (it.hasNext()) {
prevlist = (bean.data) it.next();
%>
{
{'field1' : '<%=prevlist.getField1()%>',
'field2' : '<%=prevlist.getField1%>',
'field3' : '<%=prevlist.getField1%>',
'field4' : '<%=prevlist.getField1%>',
'field5' : '<%=prevlist.getField1%>',
'field6' : '<%= fw.utils.getField1 %>',
'field7' : '<%=prevlist.getField1 %>'
}
<% if (it.hasNext()) { out.println(","); } %>
<% } }%>
]

-------------------------------------------------------------------------

Jmaki has this feature that you can trace the JSon script that goes out and return.
Good tools to help you debug the your script. Turn it on, see glue.js,
Also if you are using mozilla it has an nice plugin for Javascript debugging Firebug. You can download it from this link
https://addons.mozilla.org/en-US/firefox/addon/1843

-------------------------------------------------------------------------

jmaki.debug = true
// uncomment to show publish/subscribe messages
jmaki.debugGlue = true

Saturday, January 19, 2008

Java IDE


Searching the net using keyword Best Java IDE you would end up with blogs with WAR, no wonder if we are going to build an java web apps we end up with WAR too(joke ..), Im a netbeans guy, I start developing java apps in netbeans 5. Now Im a great fun of Netbeans, specially Netbeans 6 now is out, lots of feature and enhancement of has been added.

We got this project from outsource firm that was built in Eclipse platform and we end up their contract and now we are in the state of take over what they've build in short we are going to enhance. whheww... am I going to transfer to eclipse? I've research about eclipse, I also find lots of developer talking about fastest and the SWT stuff over Swing, and I think eclipse is good too. But as what I experience in Netbeans, I never find problem in building apps, it is an simply amazing, I think it is just a complete IDE, theres a lot of online document and video tutorial too(http://www.netbeans.org/kb/index.html), as what they said Netbeans simply ROCKS. Neatbeans has this plugin that you can easily import eclipse project so my problem was solves. Now sun has full support for netbeans, I think next release of netbeans has a lot of new exciting stuff.

Now heres my challenge, We are using Oracle Database and oracle has this Java IDE too JDeveloper, my superior wanted me to build our new apps in JDeveloper, their idea is we are going to utilize all the tools that oracle can give us since were using their database. I been already explain to them that database has no connection in building that web apps and also Netbeans has plugin for Oracle Toplink(take note I been explaining to none Java people). This superior of mine has no experience in java or web application, its really hard for me to explain what really like to build an web application. We are not in the same frequency. So to make the story short, I agreed to build new apps to JDeveloper. I must make a research and study now JDeveloper, I find Oracle has this good framework too, Oracle ADF and ADFUI.


But I will never leave Netbeans, I still use it to build my personal kind of stuff(hehehe). I have a great believe in Netbeans that soon this we'l become a great java IDE.

Question is how to handle this kind of situation like explaining to people that has no experience on particular technology? anybody?

Web Framework's Experience

I have been studying lots of frameworks this days not just for research but i must because my company has these outsource web apps built in different framework. And take not take note I was the only one Java developer they got, huh! pretty tough right!(hehehe). Anyway they got this web apps called Customer Feedback System(CFS) build in Struts 1 framework, it was develop before for some group of student but the problem here is it was not done, so I will finished the system, I find lots of hard time debugging their Struts framework since no turn over, no documentation so i must digg it my self from Backend design to Frontend, and they implement the MVC in the wrong way, i guess those guys don't really know what is MVC and why they use Framework, anyway they are just student many things to learn. I manage to continue and somehow separate the overlapping View layer to Controller and Model and vice versa and it was quite easy for me to get hook to their apps since i have already experience in whole life Cycle of Struts Framework.

Here comes again another web apps called Subsidiary Ledger(SL) it was built in Java Server Face(JSF), Spring MVC and Hibernate in Model, the good thing is it was already done and running already in production. And here comes the user request enhancement come, As a solo flight Java application Developer I must learn and get hook with the three Framework, whew! lots of googling these time, Thanks to Shang Shin from Sun, He has this site www.javapassion.com, it really helps a lot for me to get started with the framework and also he also recommended some book to read from his site.

As what I experience I really enjoyed learning some new things, I find each framework has these different strength. Stuts is very good in Controller and easy to implement, very straight forward.
Spring MVC is also good, no wonder it is very hot today Dependency Injection works well, separation of interface from implementation, decoupling an Objects. JSF is very good in View using EL expression and Backing bean, unlike Struts i find painful to implement in View layer and struts also not so good interaction with Ajax. And of course the Hibernate on the Model layer, this framework is very helpful doing CRUD(Create,Retrieve,Update,Delete), unlike before Im using native JDBC and I find it is not a good thing to do since it prevent the portability of the application, bare with me i came from PC base system development were using native SQL in communicating the Database.

So to sum up... I've learn and enhance my skill in ...
  • Struts 1.9
  • Spring MVC
  • Hibernate
  • JSF
  • and also the new framework from Sun which I also like the Jmaki (web 2.o stuff).
am scripting, since i was the only web apps developer, Ive learn...
  • JavaScript
  • Ajax(XMLHttpRequest object)
  • XML(for configuration, wiring and initialization of objects)
  • a little bit of CSS(theres a lot of free CSS from net that we can download).
  • and of course JSON.
see a lot of things to consider building the web world... whewww... but if feels good. I think these is now the trend for application now a days since theres a web 2.0 stuff like Jmaki, Echo2, JSF UI and other View framework that can make an application like more desktop apps.So for all of you PC Base developer right there try to jump to Web Apps.