Archive for the ‘Programming’ Category
« Previous EntriesJava Rounding Decimal to 2 Places
Sunday, February 22nd, 2009Below is a Java Program containing a method round” to Round an Input Double Number to 2 Decimal Places. The same logic can be used for numbers of other Data Types. We can make use of 3 Built-in methods of the Math Function to achieve this.
[sourcecode language='java']
/*
public class JavaRoundingDemo {
private static double PI = 3.14159;
public static void main(String[] args) {
double piAfterRounding = round(PI, 2); //Rounding to 2 Decimal Places
System.out.println(”Simple Rounding Yeilds: ” + Math.round(PI));
System.out.println(”Rounded to 2 Decimal Places: ” + piAfterRounding);
}
public static double round(double input, int roundFactor) {
double p1 = (double) Math.pow(10, roundFactor); // Results in (100)
input = input * p1; // Results in 314.159
double temp = Math.round(input); // Results in 314.16
return temp / p1;
}
}
[/sourcecode]
How to create a JLabel with HyperLink in Java
Tuesday, October 14th, 2008Java Program: This program creates a JLabel with a HyperLink. If you click on this link, a browser will open with the adress embeded.
[sourcecode language='java']
package javaapplicationmodels;
import java.io.IOException;
import javax.swing.*;
import java.awt.*;
public class JLabelLink extends JFrame {
private static final long serialVersionUID = 1L;
public JLabelLink() {
super() ;
setTitle( “Click on the JLabel to start the webpage.” ) ;
setDefaultCloseOperation( EXIT_ON_CLOSE ) ;
JPanel pane = new JPanel();
setContentPane(pane);
setLayout(new FlowLayout());
JLabel label= new JLabel( “Visit iWebie” , JLabel.CENTER );
label.setBackground(Color.RED);
getContentPane().add(label) ;
label.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getClickCount() > 0){
try {
Process pc = Runtime.getRuntime().exec(”cmd.exe /c start http://www.iwebie.com”);
} catch (IOException ex) {
System.out.println(ex.getMessage());
System.out.println();
}
}
}
});
setSize( 400 , 100 );
setVisible( true );
}
public static void main(String[] args) {
new JLabelLink () ;
}
}
[/sourcecode]
Posted in Programming 5 Comments »Oracle JDBC Connection Tomcat 5.5
Monday, October 6th, 2008How to Setup or Configure Oracle JDBC Connection with Tomcat 5.5
Below are 3 Steps to Create a JDBC Connection for Tomcat using Oracle driver
Step 1: Copy The Necessary Jars
To begin with You need to copy the Jars namely classes12.jar and classes111.jar from your Oracle Installation to your Tomcat 5.5 Common Lib Folder.
Oracle 9i Path to the Jars

Tomcat 5.5 Path to where the Jars need to be copied

Step 2: Modify the Server.xml file
[sourcecode language='xml']
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
[/sourcecode]
Add the Below peice of code in your Server.xml file just after the closing Tag of the above shown Section;
[sourcecode language='xml']
url="jdbc:oracle:thin:@127.0.0.1:1521:bob"
username="scott" password="tiger" maxActive="20" maxIdle="10"
maxWait="-1"/>
[/sourcecode]
In the URL, “jdbc:oracle:thin:@127.0.0.1:1521:bob” (url=”jdbc:oracle:thin:@<host>:<port>:<sid>”);
127.0.0.1 is the hostname
1521 is the Port
and bob is the SID
Your Server.xml should look like this

Step 3: Test the Connection Class with the Servlet Code Example as Shown Below.
[sourcecode language='java']
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestConnection extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
Class.forName(”oracle.jdbc.driver.OracleDriver”);
Connection con = DriverManager.getConnection(
“jdbc:oracle:thin:@localhost:1521:bob”, “scott”, “tiger”);
// @machineName:port:SID, userid, password
out.println(”“);
out.println(”
out.println(”
out.println(”“);
out.println(”“);
out.println(”
Connection Established Successfully
“);out.println(”“);
out.println(”“);
} catch (ClassNotFoundException e1) {
out.println(”Connection Failed ” + e1.toString());
} catch (SQLException e2) {
out.println(”Connection Failed ” + e2.toString());
} catch (Exception e3) {
out.println(”Connection Failed ” + e3.toString());
}
}
}
[/sourcecode]
If all is well the Output should look like this;

Logical Programs in Java – Fibonacci Series, Prime Numbers
Monday, August 25th, 2008Fibonacci Series
This Program generates Fibonnaci Series for a given number of times.
Output: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
[sourcecode language='java']
public class FibonnaciSeries {
/*
* Generates the Fibonnaci Series
*/
public void generateSeries(int num) {
int f1, f2 = 0, f3 = 1;
System.out.println(”fib(0) = ” + f2);
for (int i = 1; i <= num; i++) {
System.out.println("fib(" + i + ") = " + f3);
f1 = f2;
f2 = f3;
f3 = f1 + f2;
}
}
public static void main(String[] args) {
System.out.println("*****Fibonnaci Series*****");
FibonnaciSeries fb = new FibonnaciSeries();
fb.generateSeries(10);
}
}
[/sourcecode]
Highest Prime Number
Given a number this program generates the highest prime number.
Output: If the input is 25, the highest prime number close to 25 is 23. It prints 23.
[sourcecode language='java']
public class PrimeNumber {
/*
* Given a number, finds the highest prime number.
*/
public static int highestPrime(int n) {
int value = 1;
for (int i = 2; i <= n; i++) {
// System.out.println("n: " + n + " i: " + i + " mod: " + n%i);
if (i == n) {
value = n;
break;
}
if (n % i == 0) {
n--;
}
}
return value;
}
public static void main(String[] args) {
int value = highestPrime(25);
System.out.println("Prime:" + value);
}
}
[/sourcecode]
Triangle Printing
Given a number, this program prints the numbers in the right angle manner.
Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14
[sourcecode language='java']
public class TrianglePrinting {
/*
* Prints the numbers in the right angle manner.
*/
public static void trianglePrinting(int n) {
int counter = 0, i = 1;
while (i <= n) {
counter++;
for (int j = 0; j < counter; j++) {
if (i > n)
break;
System.out.print(i + ” “);
i++;
}
System.out.println();
}
}
public static void main(String[] args) {
trianglePrinting(14);
}
}
[/sourcecode]
How to create a PopUpMenu on a JTable?
Sunday, August 17th, 2008Here is a Sample Program which creates a Context menu or a Popup menu on a JTable.
Features of this Program:
1) A PopUpMenu appears when you right click on the JTable on the rows and on the table header.
2) You can add a row and delete a row in the JTable from the PopUpMenu.
[sourcecode language='java']
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);
}
}
}
[/sourcecode]
Where can we find Servlet.jar
Sunday, August 10th, 2008To find the Servlet.jar on your system you need to download a Servlet container or a J2EE SDK Server.
You can download either of the following
J2EE SDK
Tomcat Container
WebLogic or any other Server
It is shipped as a part of the server and is not meant to be downloaded separately. If you are using Tomcat, you can find “Servlet.jar” in your tomcat installation folder (tomcat\common\lib)
You would either find the servlet.jar or servlet-api.jar
You can get latest Tomcat Version here;
http://jakarta.apache.org/tomcat/index.html
Java Swing JTree Tutorial
Sunday, July 27th, 2008Swing provides support for hierarchies using a tree structure implemented via the Swing class JTree. A tree is a collection of one or more nodes. Each node is the parent of zero or more children, which are also nodes. The node that is at the base of the tree is called the root.
A node with no children is a leaf. A tree may consist of many subtrees, in which each node acts as the root for its own subtree.
A tree can be expanded (expanded nodes show their children) or collapsed (children are hidden). The way in which a collapsed or expanded node is displayed depends on the Look and Feel. When a tree expansion event occurs, the method treeExpanded() is called, identifying the node that was expanded. When a tree collapse event occurs, treeCollapsed() is called instead.
A node is selected by clicking it; this click generates a TreeSelectionEvent. Likewise, expanding or collapsing a tree generates a TreeExpansionEvent. Selecting a new node causes all nodes in a previous selection to be deselected. When a tree selection event occurs, the method valueChanged() is called. Note that this method is called for both node selection and deselection.
A node’s path is represented by an object of type TreePath. A path is an array of Object components which together uniquely identify the path from the root of the tree to a specific node. The elements are stored in the array in order from the hierarchy’s root.
Posted in Programming 2 Comments »Java Swing GridBagLayout Example
Tuesday, July 15th, 2008Java Swing GridBagLayout is a Swing layout manager that is difficult to use and needs good practice to master it. GridBagLayout lay’s out components vertically and horizontally within a grid of rows and columns that can be of different sizes. To understand GridBagLayout, its essential to know what a GridBagConstraint is ?
GridBagConstraints are used to specify how a component must be positioned within the display area of your panel. It gives you complete control to set various parameters like coordinate positions (gridx & gridy), width, height, (gridwidth & gridheight) internal padding (ipadx & ipady), external padding (insets), anchor, weightx and weighty.
Below is a Swing GridBagLayout Example that demonstrates
- How to work with the GridBagLayout and GridBagConstraints classes.
- How to create and set a gridbag layout
- how to set gridbag constraints on each component that is added to the layout.
[sourcecode language='java']
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class JavaGridNagLayoutExample {
private JTextField jtfName;
private JTextField jtfAge;
private JTextArea jtaAddress;
private JTextField jtfState;
private JTextField jtfCity;
private JRadioButton jrbMale;
private JRadioButton jrbFemale;
private JButton jbtSubmit;
public void addComponentsToPane(JFrame frame) {
Container pane = frame.getContentPane();
ButtonGroup group = new ButtonGroup();
group.add(jrbMale);
group.add(jrbFemale);
GridBagConstraints gBC = new GridBagConstraints();
gBC.fill = GridBagConstraints.HORIZONTAL;
gBC.insets = new Insets(5, 5, 0, 5);
JLabel jlbName = new JLabel(”Name : “);
gBC.gridx = 0;
gBC.gridy = 0;
pane.add(jlbName, gBC);
jtfName = new JTextField(20);
gBC.gridx = 1;
gBC.gridy = 0;
gBC.gridwidth = 2;
pane.add(jtfName, gBC);
JLabel jlbAge = new JLabel(”Age : “);
gBC.gridx = 0;
gBC.gridy = 1;
gBC.gridwidth = 1;
pane.add(jlbAge, gBC);
jtfAge = new JTextField(5);
gBC.gridx = 1;
gBC.gridy = 1;
gBC.fill = GridBagConstraints.NONE;
gBC.anchor = GridBagConstraints.WEST;
gBC.gridwidth = 2;
pane.add(jtfAge, gBC);
gBC.fill = GridBagConstraints.HORIZONTAL;
JLabel jlbSex = new JLabel(”Sex : “);
gBC.gridx = 0;
gBC.gridy = 2;
gBC.gridwidth = 1;
pane.add(jlbSex, gBC);
jrbMale = new JRadioButton(”Male”);
gBC.gridx = 1;
gBC.gridy = 2;
pane.add(jrbMale, gBC);
jrbFemale = new JRadioButton(”Female”);
gBC.gridx = 2;
gBC.gridy = 2;
pane.add(jrbFemale, gBC);
JLabel jlbAddress = new JLabel(”Address : “);
gBC.gridx = 0;
gBC.gridy = 3;
pane.add(jlbAddress, gBC);
jtaAddress = new JTextArea(5, 10);
gBC.gridx = 1;
gBC.gridy = 3;
gBC.gridwidth = 2;
pane.add(jtaAddress, gBC);
JLabel jlbCity = new JLabel(”City : “);
gBC.gridx = 0;
gBC.gridy = 4;
gBC.gridwidth = 1;
pane.add(jlbCity, gBC);
jtfCity = new JTextField(10);
gBC.gridx = 1;
gBC.gridy = 4;
gBC.gridwidth = 2;
pane.add(jtfCity, gBC);
gBC.gridwidth = 1;
JLabel jlbState = new JLabel(”State : “);
gBC.gridx = 3;
gBC.gridy = 4;
gBC.insets.right = 0;
pane.add(jlbState, gBC);
gBC.insets.right = 5;
jtfState = new JTextField(10);
gBC.gridx = 4;
gBC.gridy = 4;
pane.add(jtfState, gBC);
jbtSubmit = new JButton(”Submit”);
gBC.gridx = 4;
gBC.gridy = 5;
pane.add(jbtSubmit, gBC);
}
public static void main(String[] args) {
JavaGridNagLayoutExample test = new JavaGridNagLayoutExample();
JFrame frame = new JFrame(”GridBagLayout Demo”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridBagLayout());
test.addComponentsToPane(frame);
frame.pack();
frame.setVisible(true);
}
}
[/sourcecode]
An advantage of the GridBagLayout over GridLayout is that we can layout out components in rows and columns of different sizes.
Check GridBagLayout Class Related API
java.awt.GridBagLayout Class
java.awt.GridBagConstraints Class
You may also want to check out How to Use GridBagLayout tutorial from the Sun Java Site .
Posted in Programming 3 Comments »Generate Checksum out of file contents – Java
Monday, July 14th, 2008Sometimes in programming world, there would be a requirement to generate a checksum out of the contents of a file. It would be for verifying if the contents of the file have been modified. Given a filepath [Any file type]. It generates a simple ‘SHA’ message digest.
[sourcecode language='java']
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
class MyDigest {
public MyDigest(String Filename) {
// reads a file and calculates a message digest for it
File f = new File(Filename);
if (!f.exists()) {
System.out.println(”The file does not to exist”);
System.exit(1);
}
// Specify the number of lines in the files. Default capacity is 10.
java.util.List text = new ArrayList(1000); // 1000 lines as input
// Get an object that can compute an SHA message digest
MessageDigest digester = null;
try {
digester = MessageDigest.getInstance(”SHA”);
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
// A stream to read bytes from the file f
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
// A stream that reads bytes from fis and computes an SHA message digest
DigestInputStream dis = new DigestInputStream(fis, digester);
// A stream that reads bytes from dis and converts them to characters
InputStreamReader isr = new InputStreamReader(dis);
// A stream that can read a line at a time
BufferedReader br = new BufferedReader(isr);
// Now read lines from the stream
try {
String line = “”;
while ((line = br.readLine()) != null
&& (line.indexOf(”")) != -1)
text.add(line);
} catch (IOException e3) {
e3.printStackTrace();
}
// Close the streams
try {
br.close();
} catch (IOException e4) {
e4.printStackTrace();
}
// Get the message digest
byte[] digest = digester.digest();
// warning: sun says to not use sun library methods
// there is no import because it is not available — just use library
String s = new sun.misc.BASE64Encoder().encode(digest);
System.out.println(s); // show user the encoded digest
System.exit(0);
// ==================================
}
public static void main(String[] args) {
MyDigest myDigest = new MyDigest(”C:\\COMLOG.txt”);
}
}
[/sourcecode]
Posted in Programming No Comments »Java XML DOM Example
Sunday, July 13th, 2008Below is a Java Xml DOM Tutorial program to demonstrate how to work with XML using Java API
This program will illustrate the following concepts;
- The Creation of an XML Document, element node, attribute node, comment node, processing instruction and a CDATA section
- How to use DOM to work with XML
- How to build a DOM Tree
- How to write a DOM tree to a file
- How to read a DOM tree from a file
- How to read the Nodes of a DOM tree
This example below creates a file “Employee.xml” in the same path as that of the source code path
[sourcecode language='java']
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
class Employees {
private String gender;
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Employees(String name, String gender, String name2) {
firstName = name;
this.gender = gender;
lastName = name2;
}
public String toString() {
return firstName + “\t” + gender + “\t” + lastName;
}
}
public class BuildXmlUsingDom {
private Document document;
public BuildXmlUsingDom() {
DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = dBF.newDocumentBuilder(); // java xml documentbuilder
document = builder.newDocument();
} catch (ParserConfigurationException parserException) {
parserException.printStackTrace();
}
Element root = document.createElement(”Employees”);
document.appendChild(root);
// add comment to XML document
Comment simpleComment = document.createComment(”Employee Details”);
root.appendChild(simpleComment);
// add Employee child elements
Node employeeNode = createEmployees(document);
root.appendChild(employeeNode);
// We can also add processing instructions and java xml cdata Sections as shown
/*
* ProcessingInstruction pi = document.createProcessingInstruction(
* “myInstruction”, “action silent”); root.appendChild(pi);
*
* CDATASection cdata = document .createCDATASection(”I can add <, >,
* and ?”); root.appendChild(cdata);
*/
// write the XML document to disk
try {
// create DOMSource for source XML document
Source xmlSource = new DOMSource(document);
// create StreamResult for transformation result
Result result = new StreamResult(new FileOutputStream(
“Employee.xml”));
// create TransformerFactory
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
// create Transformer for transformation
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(”indent”, “yes”); //Java XML Indent
// transform and deliver content to client
transformer.transform(xmlSource, result);
}
// handle exception creating TransformerFactory
catch (TransformerFactoryConfigurationError factoryError) {
System.err.println(”Error creating ” + “TransformerFactory”);
factoryError.printStackTrace();
} catch (TransformerException transformerError) {
System.err.println(”Error transforming document”);
transformerError.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
public Node createEmployees(Document document) {
// create FirstName and LastName elements
Element firstName = document.createElement(”FirstName”);
Element lastName = document.createElement(”LastName”);
// java xml text
firstName.appendChild(document.createTextNode(”Shawn”));
lastName.appendChild(document.createTextNode(”Michaels”));
// create employee element
Element employee = document.createElement(”Employee”);
// java xml attributes
Attr genderAttribute = document.createAttribute(”gender”);
genderAttribute.setValue(”M”);
// append attribute to contact element
employee.setAttributeNode(genderAttribute);
employee.appendChild(firstName);
employee.appendChild(lastName);
return employee;
}
// Function to read DOM Tree from File
public Document readingXMLFromFile() {
DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance();
dBF.setIgnoringComments(true); // Ignore the comments present in the
// XML File when reading the xml
DocumentBuilder builder = null;
try {
builder = dBF.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
InputSource input = new InputSource(”Employee.xml”);
Document doc = null;
try {
doc = builder.parse(input);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return doc;
}
/*
* Employee.xml
*
*
*
*
*/
public ArrayList CreateListOfObjects(Document doc) {
ArrayList
Element root = doc.getDocumentElement();
// Retrieve the list of Empolyee Nodes
NodeList employeeList = root.getElementsByTagName(”Employee”);
for (int i = 0; i < employeeList.getLength(); i++) {
Element employeeElement = (Element) employeeList.item(i);
String gender = employeeElement.getAttribute("gender");
// java xml nodelist
NodeList firstNameList = employeeElement
.getElementsByTagName("FirstName");
Element firstNameElement = (Element) firstNameList.item(0);
Text firstNameText = (Text) firstNameElement.getFirstChild();
String fName = firstNameText.getNodeValue();
NodeList lastNameList = employeeElement
.getElementsByTagName("LastName");
Element lastNameElement = (Element) lastNameList.item(0);
Text lastNameText = (Text) lastNameElement.getFirstChild();
String lName = lastNameText.getNodeValue();
Employees emp = new Employees(fName, gender, lName);
employeesList.add(emp);
}
return employeesList;
}
public static void main(String args[]) {
BuildXmlUsingDom buildXmlUsingDom = new BuildXmlUsingDom();
System.out
.println("Processing Employee.xml to create Employee Objects");
Document doc = buildXmlUsingDom.readingXMLFromFile();
ArrayList
.CreateListOfObjects(doc);
System.out.println(”The Employee Objects are”);
for (int i = 0; i < empList.size(); i++) {
System.out.println(empList.get(i));
}
}
}
[/sourcecode]
Posted in Programming No Comments » « Previous Entries









