Sandeep & Vicky’s Archive » 2009 » April

Archive for April, 2009

Several years ago there was a trend in Java web frameworks to use XML processing as a foundation for the framework logic: take the data from database and present it as XML document (either convert it from relational data, or use XML capable database), and transform it to HTML using XSLT. There were some books written about it, and some frameworks created (like Cocoon). After some time the hype started to decline, and currently virtually no modern web framework apply this approach, I think.

Actually I’ve never used it on myself, but I liked the idea at that time. It seemed to be clear and powerful. Funny that only now I have a chance to check how it works in practice. And at least now I know why this approach failed.

For two weeks, I’m outsourced to help some company in their web project. They use their own, home-made web framework for this, to talk to their own, home-made document-repository system. Unfortunately, both seemed to be buggy and unstable, though they say that’s not the first project they use them in (I can’t believe it’s true, really). I guess they would be better off using standard Java Content Repository (JSR-170) for implementing documents repository, and some modern web framework instead of their own home-grown one. If they insisted on XML/XSLT transformations, they could use Cocoon. At least there would be more documentation available, and it would be well-tested and stable. But ok, that’s not the first company that suffers from NIH syndrome, or guys are simply too lazy or overloaded to look around for other stuff. The interesting point is: how the XML-based processing works in practice? The short answer is: very poor. And the weakest link in the whole chain is XSLT.

XSLT bloat

I won’t dare to say that XSLT is worthless – perhaps in some contexts it can be useful, especially for transforming one document tree into another (valid) document tree, i.e. from DOM to DOM. XSLT gives you guarantee that input and output documents will be valid XML – this is crucial e.g. in SOA applications, transforming one document into other documents, to be processed by machines. (X)HTML is a document tree too, at least formally, but from the point of view of web browser to have perfectly valid XHTML is good, but not crucial, and from the point of view of web designer or developer the DOM behind it doesn’t matter at all, and making the template valid XML is of no importance. For dynamic generation of HTML pages in most cases it is much easier if you treat the HTML code as a unformatted text, and make a web page template by embedding some special processing directives in such text. This approach was applied by JSP (first with scriptlets, and than with JSTL), Velocity, FreeMarker, and other technologies. Neither of those technologies use the strict XML as template. On the opposite side we have JSPX (JSP using strict XML) – it never caught on and I guess many Java developers have never met it; and XSLT.

I’ve used a lot of JSPs with JSTL. It wasn’t perfect, but it worked. Now I have to do the same with XSLT and it’s a nightmare. Things that took me half an hour to do with JSP take several hours in XSLT. This is a list of things I hate the most in XSLT:

1. Conditional arguments. For example: how to hide the row in table (using different CSS style), based on some CONDITION, with XSLT?

2. Nested loops. In JSTL the <for-each> tag has the var attribute, which is the variable that gets assigned the current element from the collection during looping.

3. Every XML-like fragment which is not an actual XML must be escaped.

4. The functional approach applied in XSLT design, instead of the well known (for all programmers) procedural one, makes “thinking in XSLT” very hard.

5. No formal XML schema for XSLT 1.0 exists. At least I couldn’t find it – there is only unofficial DTD somewhere. This ruins IDE code completion abilities.

Thanks

By Grzegorz Borkowski

21
Apr

java code to pop up a menu on a right click in a jtable

   Posted by: admin    in java

This one will really make your application more user friendly and easy to use.

CODE

import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;

public class PopUpMenuPanel extends JPanel {

private static final long serialVersionUID = 1L;

JScrollPane pane = new JScrollPane();

JPopupMenu popupMenu = new JPopupMenu();

JTable table;

private static String INSERT_CMD = “Insert Rows”;

private static String DELETE_CMD = “Delete Rows”;

public PopUpMenuPanel() {
super(new GridLayout(1, 0));

table = new JTable(new MyTableModel());
pane = new JScrollPane(table);
add(pane);

JMenuItem menuItem = new JMenuItem(INSERT_CMD);
menuItem.addActionListener(new ActionAdapter(this));
popupMenu.add(menuItem);
menuItem = new JMenuItem(DELETE_CMD);
menuItem.addActionListener(new ActionAdapter(this));
popupMenu.add(menuItem);

MouseListener popupListener = new PopupListener();
table.addMouseListener(popupListener);
table.getTableHeader().addMouseListener(popupListener);
}

private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame(“TableDemo”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create and set up the content pane.
PopUpMenuPanel popUp = new PopUpMenuPanel();
popUp.setOpaque(true); // content panes must be opaque
frame.setContentPane(popUp);

// Display the window.
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application’s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

public void insertColumn(ActionEvent e) {
JOptionPane.showMessageDialog(this, “Insert Column here.”);
// insert new column here
}

public void deleteColumn(ActionEvent e) {
JOptionPane.showMessageDialog(this, “Delete Column here.”);
// delete column here
}

private class MyTableModel extends AbstractTableModel {
private String[] columnNames = { “First Name”, “Last Name”, “Sport”,
“# of Years”, “Vegetarian” };

private Object[][] data = {
{ “Mary”, “Campione”, “Snowboarding”, new Integer(5),
new Boolean(false) },
{ “Alison”, “Huml”, “Rowing”, new Integer(3), new Boolean(true) },
{ “Kathy”, “Walrath”, “Knitting”, new Integer(2),
new Boolean(false) },
{ “Sharon”, “Zakhour”, “Speed reading”, new Integer(20),
new Boolean(true) },
{ “Philip”, “Milne”, “Pool”, new Integer(10),
new Boolean(false) } };

public final Object[] longValues = { “Sharon”, “Campione”,
“None of the above”, new Integer(20), Boolean.TRUE };

public int getColumnCount() {
return columnNames.length;
}

public int getRowCount() {
return data.length;
}

public String getColumnName(int col) {
return columnNames[col];
}

public Object getValueAt(int row, int col) {
return data[row][col];
}

/*
* JTable uses this method to determine the default renderer/ editor for
* each cell. If we didn’t implement this method, then the last column
* would contain text (“true”/”false”), rather than a check box.
*/
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}

/*
* This method is implemented if we want to make the cell editable.
*/
public boolean isCellEditable(int row, int col) {
if (col < 3) {
return false;
} else {
return true;
}
}

/*
* Implement this method, if your table data will change.
*/
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}
}

class PopupListener implements MouseListener {
public void mousePressed(MouseEvent e) {
showPopup(e);
}

public void mouseReleased(MouseEvent e) {
showPopup(e);
}

private void showPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}

public void mouseClicked(MouseEvent e) {
}

public void mouseEntered(MouseEvent e) {
}

public void mouseExited(MouseEvent e) {
}
}

} // end of class

class ActionAdapter implements ActionListener {
PopUpMenuPanel adapter;

ActionAdapter(PopUpMenuPanel adapter) {
this.adapter = adapter;
}

public void actionPerformed(ActionEvent e) {
JMenuItem item = (JMenuItem) e.getSource();
if (item.getText() == “Insert Rows”) {
adapter.insertColumn(e);
} else if (item.getText() == “Delete Rows”) {
adapter.deleteColumn(e);
}

}
}
OUTPUT

jtaplerightclick.JPG

You must have used tables in microsoft word , excel, etc where in you just select a particular row and press delete and the entire row vanishes away.

Well even you can do that in your jtables. The following code illustrates this

CODE

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;

public class TableDelete{
JFrame frame;
Container con;
JScrollPane scr;
JTable table;
DefaultTableModel model;

String[] columnNames = {“First Name”,
“Last Name”,
“Sport”,
“# of Years”,
“Vegetarian”};

Object[][] data = {
{“Mary”, “Campione”,
“Snowboarding”, new Integer(5), new Boolean(false)},
{“Alison”, “Huml”,
“Rowing”, new Integer(3), new Boolean(true)},
{“Kathy”, “Walrath”,
“Knitting”, new Integer(2), new Boolean(false)},
{“Sharon”, “Zakhour”,
“Speed reading”, new Integer(20), new Boolean(true)},
{“Philip”, “Milne”,
“Pool”, new Integer(10), new Boolean(false)},
{“Anne”, “Campione”,
“Swimming”, new Integer(6), new Boolean(false)},
{“Michael”, “Huml”,
“Baseball”, new Integer(13), new Boolean(true)},
{“Wanda”, “Walrath”,
“Skating”, new Integer(8), new Boolean(false)},
{“Zdeh”, “Zakhour”,
“Football”, new Integer(11), new Boolean(true)},
{“Hornic”, “Milne”,
“Kayac”, new Integer(9), new Boolean(false)}
};

public TableDelete(){
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
con = frame.getContentPane();

model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
scr = new JScrollPane(table);
con.add(scr, BorderLayout.CENTER);

table.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int c = e.getKeyCode();
if (c == KeyEvent.VK_DELETE) {
int[] index = table.getSelectedRows();
e.consume();
for (int i=index.length – 1; i >= 0; –i){
model.removeRow(index[i]);
}
}
}
});

frame.pack();
frame.setVisible(true);
}

public static void main(String[] args){
new TableDelete();
}
}

Output :

tabledelete.JPG

Hello guys…..This one’s great. Well you people must be aware of the commonly used command line interpreter…some people call it console. Some call it shell. These are nothing but programs in an OS which take input from user in the form of a command, execute it  and display the results. One of the main features of these cmd’s (command line interpreter’s short form for windows) is that they maintain a linked list of the command’s typed by the user…one can navigate the list by using up and down arrow keys. This can be implemented in java as well… We would implement a command prompt in java which will take input database commands like INSERT, UPDATE, SELECT, etc and fire them on a database…..and we would also implement the  linked list part of the program as well.

So let’s go…..

There are two main classes

–> Query1.java……our main command prompt

–> DbConn.java…..class file to make a database connection

CODE

//——————–DbConn.java———-//

//Here we have used a mysql database named databasename

//all the commands interpreted from Query1.java would be fired on this database
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;

public class DbConn {
Statement s;
Connection c;
DbConn()
{

try {
Class.forName(“com.mysql.jdbc.Driver”);
c = DriverManager.getConnection(“jdbc:mysql:///databsename”,
“username”, “password”);

s=c.createStatement();

} catch(Exception e)
{
e.printStackTrace();
}
}
}

//—————Query.java———-//

//This is our main class….the interpreter

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;

class Query1 implements ActionListener,KeyListener
{
Frame f1;
TextField tf1;
Button b1,bd1;
Panel p;
TextArea ta1;
Connection c;
Statement s;
DbConn d;
boolean flag;
Dialog d1;
LinkedList l;
int index =0;
int currind=0;
Query1(boolean t)
{
flag=t;
f1= new Frame(“Convergence—-query”);
p=new Panel();
tf1= new TextField(30);
ta1=new TextArea();
b1= new Button(“Show”);
d1=new Dialog(f1,”Invalid query”);
bd1=new Button(“OK”);
l=new LinkedList();

Color tt=new Color(0,200,200);
f1.setBackground(tt);

d=new DbConn();
try
{
d.c.setReadOnly(true);
}
catch (Exception e)
{
e.printStackTrace();
}
d1.setSize(200,100);
d1.setLayout(new FlowLayout());

f1.setLayout(new BorderLayout());
p.setLayout(new BorderLayout());

p.add(tf1,BorderLayout.CENTER);
p.add(b1,BorderLayout.EAST);
f1.add(p,BorderLayout.NORTH);

ta1.setEditable(false);
f1.add(ta1,BorderLayout.CENTER);
f1.setSize(600,600);
f1.setVisible(true);
d1.add(bd1);
b1.addActionListener(this);
bd1.addActionListener(this);
tf1.addActionListener(this);
tf1.addKeyListener(this);
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_UP)
{
if(currind>0)
{
currind–;
tf1.setText(“”+l.get(currind));
}
}
if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
if(currind<l.size()-1)
{
currind++;
tf1.setText(“”+l.get(currind));
}
}
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==bd1)
{
d1.setVisible(false);
}
else
{
String s1=tf1.getText();
if(s1.equalsIgnoreCase(“exit”))
{
f1.dispose();
}
else if(s1.equalsIgnoreCase(“cls”))
{
ta1.setText(“”);
}
else
{

try{
ta1.append(“\n”);

ResultSet rs=d.s.executeQuery(s1);
ResultSetMetaData rsm=rs.getMetaData();
int col= rsm.getColumnCount();
String colnames[]=new String[col];

for (int i=1;i<=col ;i++ )
{
colnames[i-1]=rsm.getColumnName(i);
}
ta1.append(“Query was “+s1);
ta1.append(“\n”);
ta1.append(“\n”);
ta1.append(“The result is \n”);
ta1.append(” \n”);
for (int i=0;i<col ;i++ )
{
ta1.append(colnames[i]+”\t\t\t”);
}
ta1.append(“\n\n”);
l.addLast(s1);
currind=l.size();
tf1.setText(“”);
while(rs.next())
{
for(int b=1;b<=col;b++)
ta1.append(rs.getString(b).trim()+”\t\t\t” );
ta1.append(“\n”);
}
ta1.append(“operation done”);
}
catch(Exception m)
{
m.printStackTrace();
ta1.append(“”+m.toString());
l.addLast(s1);
currind=l.size();

// d1.setVisible(true);
}
}
}
}
public static void main(String a[])
{
Query1 q=new Query1(true);
}

}

OUTPUT

query.JPG

20
Apr

Did you know : java can recognize html tags

   Posted by: admin    in java

Many JCompnents like JTable, JLabel, etc can recognize html tags

for example consider the following code

JLabel l=new JLabel(“memsaab”);

this will create a JLabel with its text set to “memsaab”

Now, Consider this one

JLabel l=new JLabel(“<html<h3>memsaab</h3></html>”);

this will create a JLabel and set it’s text to “memsaab” and also format this text according to the standard header tag of html .i.e. <h3>

20
Apr

java code to create a JOption pane of your choice

   Posted by: admin    in java

Hi guys. Didi you know this,…..You can create a JOptionpane with as many different compnents in it. Like, by default we have a JoptionPane that just has a label and a button. But you can integrate a Combobox, JTable, etc in a JoptionPane as well.

Here is an example in which I have made a JoptionPane with 5 lalbels, 5 textfields and a button along with validations on each text field

CODE
final JLabel len=new JLabel(“<html><h3> Opening balance </h3></html>”);
final JLabel lcash=new JLabel(“Cash on hand”);
final JLabel liob=new JLabel(“Balance in IOB”);
final JLabel lbcb=new JLabel(“Balance in BCB”);
final JLabel lsib=new JLabel(“Balance in SIB”);
final JLabel lpnb=new JLabel(“Balance in PNB”);

final JTextField tcash=new JTextField(sc); // cheque number
final JTextField tiob=new JTextField(sc1); // cheque number
final JTextField tbcb=new JTextField(sc2); // cheque number
final JTextField tsib=new JTextField(sc3); // cheque number
final JTextField tpnb=new JTextField(sc4); // cheque number
//                tfine.setEditable(false);

Object[] Jop={len,lcash,tcash,liob,tiob,lbcb,tbcb,lsib,tsib,lpnb,tpnb};

//    selstr=selstr+sel[i].toString()+” “;

boolean flago=true;

int nn=JOptionPane.CLOSED_OPTION+1;
String scash,siob,sbcb,ssib,spnb;

while (flago)
{

nn=JOptionPane.showConfirmDialog(null,Jop,”Please enter details”,JOptionPane.DEFAULT_OPTION,JOptionPane.QUESTION_MESSAGE);
scash = tcash.getText();
siob = tiob.getText();
sbcb = tbcb.getText();
ssib = tsib.getText();
spnb = tpnb.getText();

if (nn==JOptionPane.CLOSED_OPTION)
{
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, “You cannot close this window now.”, “Invalid Entry”, JOptionPane.ERROR_MESSAGE);

}
else
{
if(!validate(scash,”number”))
{
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, “Cash is invalid.”, “Invalid Entry”, JOptionPane.ERROR_MESSAGE);

}
else if(!validate(siob,”number”))
{
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, “Balance in IOB is invalid.”, “Invalid Entry”, JOptionPane.ERROR_MESSAGE);

}
else if(!validate(sbcb,”number”))
{
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, “Balance in BCB is invalid.”, “Invalid Entry”, JOptionPane.ERROR_MESSAGE);

}
else if(!validate(ssib,”number”))
{
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, “Balance in SIB is invalid.”, “Invalid Entry”, JOptionPane.ERROR_MESSAGE);

}
else if(!validate(spnb,”number”))
{
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, “Balance in PNB is invalid.”, “Invalid Entry”, JOptionPane.ERROR_MESSAGE);

}
else
{
try
{
si.updateOpeningBalance(month,year,Double.parseDouble(scash),Double.parseDouble(siob),Double.parseDouble(sbcb),Double.parseDouble(ssib),Double.parseDouble(spnb));
si.insertAudit(sessionusername,”Opening balance modified. Month : “+month+”, year : “+year);
}
catch (Exception zz)
{
zz.printStackTrace();
Toolkit.getDefaultToolkit().beep();

JOptionPane.showMessageDialog(null,”Server not found!”+”\n”+”Please check whether server in ON and restart the application”,”ERROR”,JOptionPane.INFORMATION_MESSAGE);
}
break;
}
}
}//while

Output:

joptionpane.JPG

You can use this code to display a digital watch or timer in your java application

CODE

dt=new JLabel(” “);

javax.swing.Timer z = new javax.swing.Timer(1000,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
//dt=new JLable(“”);

Calendar cz=Calendar.getInstance();
//String dtt1=(“”+cz.get(Calendar.DAY_OF_MONTH)+”/” +(cz.get(Calendar.MONTH)+1)+”/”+cz.get(Calendar.YEAR));

int th=cz.get(Calendar.HOUR_OF_DAY);   //d.getHours();
int tm=cz.get(Calendar.MINUTE);     //d.getMinutes();
int ts=cz.get(Calendar.SECOND);   //d.getSeconds();

dt.setText(dtt1+”   ” + th + “:” +tm);
}
});
z.start();

OUTPUT

timer.JPG

19
Apr

java code to connect a mysql database with java forms

   Posted by: admin    in java

You can connect any database with java. The only thig you need to do is download the drivers provided by your database service provider. Oracle provides four drivers for connection, mysql provides one connector, etc.

Here is a sample code to connect java to mysql database.

PLEASE NOTE THAT

This code requires mysql to be installed along with MYSQL CONNECTOR

CODE

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;

public class DbConn {
Statement s;
Connection c;
DbConn()
{

try {
Class.forName(“com.mysql.jdbc.Driver”);
c = DriverManager.getConnection(“jdbc:mysql:///databasename”,
“root”, “root”);

/*if(!con.isClosed())
System.out.println(“Successfully connected to ” +
“MySQL server using TCP/IP…”);
*/
s=c.createStatement();
//s.execute(“create table items(num number,wt number)”);
//ResultSet rs=s.executeQuery(“select count(1) from L_Anguthi”);
//rs.next();
//System.out.println(“”+rs.getInt(1));
c.setAutoCommit(false);

} catch(Exception e)
{
e.printStackTrace();
}
}
}

19
Apr

java code to connect a oracle database with java form

   Posted by: admin    in java

You can connect any database with java. The only thig you need to do is download the drivers provided by your database service provider. Oracle provides four drivers for connection, mysql provides one connector, etc.

Here is a sample code to connect java to oracle database.

PLEASE NOTE THAT

This code requires oracle to be installed along with its database  driver’s

CODE

import java.awt.*;
import java.sql.*;

public class DbConn

{
Statement s;
Connection c;

public DbConn()
{
try
{
Class.forName(“oracle.jdbc.driver.OracleDriver”);

//c=DriverManager.getConnection(“jdbc:odbc:ooad:@god:5620:orcl1″,”vicky”,”turion64″);
c=DriverManager.getConnection(“jdbc:oracle:thin:@god:1521:orcl1″,”vicky”,”turion64″);

s=c.createStatement();
s.execute(“spool abc;”);
s.execute(“create table studen (id number,name varchar2(15),addr varchar2(30))”);
s.execute(“spool off;”);
//s.execute(“exit”);
}
catch(Exception e)
{
e.printStackTrace();

}
}
public static void main(String a[])
{
DbConn d=new DbConn();
}
}

19
Apr

java code to display an html page in a JFrame

   Posted by: admin    in java

This code can be useful if you are planning to make a browser using java. The main functionality of a browser is to display an html page. The following code displays an html page in a jframe

CODE

import java.awt.event.*;
import java.awt.*;

import javax.swing.*;
import javax.swing.text.*;
import java.util.Vector;
import java.io.*;
import java.util.*;
import javax.swing.text.*;
import java.text.*;

class HTMLE
{
public static void main( String arg[])
{
JFrame frame=new JFrame(“Java browser”);
try {

String url = “http://google.com”;
JEditorPane editorPane = new JEditorPane(url);
editorPane.setEditable(false);
JScrollPane s=new JScrollPane(editorPane);
frame.getContentPane().add(s, BorderLayout.CENTER);

frame.setSize(800, 800);
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}

}
}

OUTPUT

htmle.JPG

Related Posts with Thumbnails