Final_PaperFall2010V1 - 91-527

advertisement
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
Abstract
There is a Java application called Java Applet Based Database Management
which can be deployed from within a web browser and can be utilized to create and
update compliant type databases remotely over a network. JDBC stands for Java
Database Connectivity. It is a specification and application programming interface (API)
of the JavaSoft division of Sun Microsystems released in May 1996.
With the implementation of JDBD in the system, developers can write either
applet program or application in Java language without worrying much about database
coding. In addition, Java is also one of the well-known language systems among system
languages and it is possible to download Java components dynamically from computers
over the Internet. Because of the application’s policy restriction, downloading
components are not always consistent. However, it is not easy for the developers or
application users to decide which policy can be used appropriately.
In this paper, I will first explore the implementation of JDBC driver with the ability
to connect and control the data in the server. There will be a discussion on both MS
Access database type (ODBC) connecting to the JDBC and a procedure how to set up
a programming task to utilize the concept of using JDBC. Secondly, there is a
discussion of a tool for creating the security policies for Java application.
Java Applet
I have decided to select Java as the primary system language on my final
project. It was a GUI (Graphical User Interface) database application design. This
application will fully use Swing packages. All should know by now that Java is the
internet language. Java is not only a programming language but it also has a powerful
library which can be used to write a useful portable program that serves as an operating
system itself. The strong security features of Java help to make learning the language
easier and quicker. The Java virtual machine is able to check many types of mistake
and report them correctly. Java compiler generates byte code instead of executable
code. In any given system where a Java run-time package was installed the byte code
of any Java program can fully execute on that system. Therefore, Java produces truly
portable programs.
Both World Wide Web and Java together are playing important roles in
information systems planning and implementation. The World Wide Web provides a
remarkable number of information to people using web browser. The Java applet is built
inside the HTM files and can use the web browser to run it. The applet code locates on
the web server can get downloaded in the browser whenever the applet web page is
requested by a browser user.
1
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
Relational database
A relational database is a database system in which the database is organized
and accessed according to the relationships between data items without the need for
any consideration of physical orientation and relationship. Relationships between data
items are expressed by means of tables. In a relational database, rows are sometimes
referred to as records, and columns are sometimes labeled as fields. The data is stored
in interconnected tables that consist of rows and columns. Each row is a record/tuple
and the columns correspond to attributes/fields in the record. A query language like
SQL (Structured Query Language) is used for data definition, data management and
data access and data retrieval. In short, a relational database can be thought of as a
collection of tables, queries, forms, reports, macros, all of which are inter-related.
Relational database table
JDBC
The Java Database Connectivity (JDBC) API lets java programs map to several types of
databases. It is a simple level API which takes advantage of the existing knowledge of database
APIs like ODBC (Open DataBase Connectivity). JDBC lets us create a statement and set them
in Java code. It offers a smooth transition between the database and Java application. Java
application is able to retrieve and display the returned results from database. A JDBC driver is
necessary to implement the JDBC protocol for a particular database engine. JDBC driver needs
to have an implementation of JDBC protocol for database engines. This project uses ODBC for
driver ShivaMorning.
2
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
JDBC-ODBC Bridge
The Driver manager
I have written functions in Java Applet that demonstrates the use of JDDC driver.
The sample of Java Apple is shown in the Figure below, with line numbers put at the
beginning of each line using as the reference. I select the ShivaMorning (data source
name under ODDC windows-XP as a database which comes under Access as my
target database. This program lets the users connect to the driver then make a
connection with the database file, inserts Last Name, First Name and much more into
the Employee’s table of ShivaMorning database, and executes a query that selects all
rows in the Employee table and returns them to the client’s browser. Figure 1 shows the
output sent back from the database when the ‘Next’ button in the browser is clicked by
the user.
3
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
Figure 1
To Make JDBC connection calls, “the package java.sql.*” needs to be imported
into the program, as shown by the program code at line 26. Then JDBC driver has to
register before using it. The way to register it is to send a message forName() to the
class as shown at the program below at line 116, line 172, line 195, line 222,
respectively. When the JDBC driver is already registered, then a connection needs to
be established to the database file (SQL server) by sending a message getConnection(
) as shown at the program below at line 117, line 173 line 196, line 223, respectively to
the object called DriverManager.
import java.awt.*;
import java.applet.*;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
java.awt.Container;
java.awt.GridLayout;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.sql.Connection;
java.sql.DriverManager;
java.sql.ResultSet;
java.sql.Statement;
javax.swing.BoxLayout;
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JOptionPane;
javax.swing.JPanel;
4
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
import javax.swing.JTextField;
26
import
import
import
import
import
import
import
import
java.awt.Color;
java.awt.BorderLayout;
java.awt.event.*;
java.applet.Applet;
javax.swing.*;
java.sql.*;
java.net.*;
java.io.*;
public class jdbcapp2 extends Applet implements ActionListener
{
// text box variables
TextField FName,LName,Address,DoB,SSNumber,Phone;
//TextField nameField;
Panel
p;
Label
display;
ResultSet rs;
Button Next,Update,Delete,Search,Add,btnClear;
public void init()
{
// create the panel for title
setLayout(new BorderLayout());
display = new Label ("91.527 Human Computer Interaction Fall 2010 with Dr.
Haim Levkowitz ");
add("North", display);
// create the panel for the form input
p = new Panel();
p.setLayout(new GridLayout(8,6));
// create all text input form
FName = new TextField(15);
LName = new TextField(15);
Address = new TextField(50);
Phone = new TextField(12);
p.add(new Label("First Name: ",Label.RIGHT));
p.add(FName);
p.add(new Label("Last Name: ",Label.RIGHT));
p.add(LName);
p.add(new Label("Address: ",Label.RIGHT));
p.add(Address);
p.add(new Label("Phone: ",Label.RIGHT));
p.add(Phone);
Add = new Button("Add");
p.add(Add);
Add.addActionListener(this);
Update = new Button("Update");
p.add(Update);
Update.addActionListener(this);
5
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
Delete = new Button("Delete");
p.add(Delete);
Delete.addActionListener(this);
p.add(new Button("Clear"));
Next = new Button("Next");
p.add(Next);
Next.addActionListener(this);
add("Center", p);
}
public void actionPerformed(ActionEvent evt) {
String action = evt.getActionCommand();
if (action.equals("Next"))
{
nextNavigation() ;
}
else if(action.equals("Update"))
{
updateOperation();
insertData();
}
else if(action.equals("Add"))
{
insertData();
}
else if(action.equals("Delete"))
{
deleteData();
}
116
}
void nextNavigation()
{
try{
if(rs == null)
{
//Load Jdbc Odbc Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
117
Connection con =
DriverManager.getConnection("jdbc:odbc:ShivaMorning");
119
String sql = "SELECT * FROM Employee";
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
124
rs = st.executeQuery(sql);
}
6
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
if(rs.next() && !rs.isAfterLast())//After Last was giving invalid cursor state
error
{
130
populateValue();
}
}catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Record Data Error.",
"Record Inserted",JOptionPane.INFORMATION_MESSAGE);
}
}
void populateValue() throws Exception
{
String fName = rs.getString("FName");
String lName = rs.getString("LName");
String add = rs.getString("Address");
String fone = rs.getString("Phone");
LName.setText(lName);
FName.setText(fName);
Address.setText(add);
Phone.setText(fone);
}
167 private void insertData()
{
Connection con;
try
{
172
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
173
con = DriverManager.getConnection("jdbc:odbc:ShiEvening");
174
String sql = "Insert Into Employee (FName,LName,Address,Phone)
('"+FName.getText()+"','"+LName.getText()
+"','"+Address.getText()+"','"+Phone.getText()+"')";
Statement statement = con.createStatement();
statement.execute();
clearControls();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Record Error",
}
}
7
"
+
"Values
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
189
private void updateOperation()
{
Connection con;
try
{
195
196
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:ShivaMorning");
198
String sql = "Update Employee Set LName='"+LName.getText()+"'," +
"Address='"+Address.getText()+"',Phone='"+
Phone.getText()+"' Where FName='"+FName.getText()+"'";
202
203
Statement statement = con.createStatement();
statement.execute(sql);
JOptionPane.showMessageDialog(null, "Record Update Succesfully.",
"Record Inserted",JOptionPane.INFORMATION_MESSAGE);
clearControls();
}catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Record Update Succesfully.",
"Record Inserted",JOptionPane.INFORMATION_MESSAGE);
}
}
private void deleteData()
{
Connection con;
try
{
222
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
223
con = DriverManager.getConnection("jdbc:odbc:ShivaMorning");
224
String sql = "delete from Employee where FName = '"+FName.getText()+"'";
Statement statement = con.createStatement();
225
statement.execute(sql);
clearControls();
JOptionPane.showMessageDialog(null, "Record Delete Succesfully.",
"Record Inserted",JOptionPane.INFORMATION_MESSAGE);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Record Delete UnSuccesfully.",
"Record Inserted",JOptionPane.INFORMATION_MESSAGE);
}
}
private void clearControls()
{
String empty = "";
FName.setText(empty);
LName.setText(empty);
Address.setText(empty);
Phone.setText(empty);
8
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
}
}
The Insert function starting at line 167 shows the actual manipulation of the SQL
database, after a connection has been built. Line 174 through 176 show the insertion of
a new record into the Employee table. An SQL insert statement along with the proper
values is used as the parameters to the execute() function that is sent to the object
statement. The nextNavigation(), Updateoperation ()and Deletedata () functions as
seen at line 119, 198 and 224 respectively also have a similarity of database execution
with Insert function. These functions also pass SQL Select, Update and Delete
statements along with the parameters to the Execute() function. The SQL database
then are processed with appropriate command actions and returned the results back.
Let’s exam the executeQuery( ) function as shown from line 119 through 124. It
takes an SQL select statement to the SQL data file. The result sent back from the SQL
database are then processed by the applet using populateValue() function at line 130 to
process the data one row/record at a time as shown in Figure 2.
Figure 2
About Java 2 Security
Most of programming languages are just application that need to have a security
to be implemented, not just the language itself. This is not the case in Java. Since the
9
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
beginning, Java has proved that it had all in the net. That is why Java is not just for the
applets any more. It seems very clear that the security mechanism is part of the
structure of Java, unlike other programming languages which don’t have the security
mechanism in the language package.
Java security has a history of going parallel with the releasing of Java version
package from JDK 1.0, JDK 1.1 and so on.
1. The security model of JDK1.0 was very restricted. Local code was able to grant
the access to all system resources, since a remote applet was not viewed as a
trusted object and could only be run with simple functions such as a decorated
Web page.
2. After the release of JDK 1.1, Java is still viewed as totally trusted local code with
all accessing rights to system resources. Yet, JDK 1.1 also provided Java
programmers with addition option of writing their code with the digital signature
application. With digital signature, the user on a client machine could make a
decision on remote code either trusted or not. If the code is trusted then it is
regarded as local code with full access to all of the system resources. Otherwise,
the remote code will only allow running within a limited environment. The JDK 1.1
security model was more attractive; however it still has some boundary limits. For
example, there is remote code which has a trusted signature giving full access to
all the system resources including the local code. Suppose that you want to grant
a read access to the signed remote code on a particular file in a specific folder
within your system then you have to give full read access to all files and folders.
Furthermore, that code was automatically given a green light to write on your
system, install other code, open a socket, and many more things. This happened
without your involvement or attention.
3. Java 2 security model apply a fine-grained access control, you can now classify
the Java code that is to run on your system base on your judgment on the
Uniform Resource Locator (URL) where that code locates and/or the code
ownership. The code ownerships can be recognized by their digital signatures. In
Java 2, it allows multiple signatures in a single piece of program code.
Possibilities are nonstop now. Suppose that there is a piece of code coming from
specific site and/or signed by a specific signers which can be granted access to
the file only reading and writing within that directory. From another site, another
code also was coming and signed by other entities to open only a specific socket,
at the same time other code can be still classified with a full access. Furthermore,
in Java 2, even local code can be considered as a subject to security-related
.
10
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
I will show you a simple example, and I will explain to you the concepts that are
involved. Let’s consider the following piece of code:
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import java.applet.Applet;
import javax.swing.*;
import java.sql.*;
import java.net.*;
import java.io.*;
public class DbaOdbAppl extends Applet implements ActionListener {
JLabel text, clicked;
JButton button, clickButton;
JTextField textField;
boolean _clickMeMode = true;
Connection c;
Connection con;
String _driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String _url = "jdbc:odbc:ShivaMorning";
public void init(){
setBackground(Color.white);
text = new JLabel("Text to save to file:");
clicked = new JLabel("Text retrieved from file:");
button = new JButton("Click Me");
button.addActionListener(this);
clickButton = new JButton("Click Again");
clickButton.addActionListener(this);
textField = new JTextField(20);
setLayout(new BorderLayout());
setBackground(Color.white);
add(BorderLayout.NORTH, text);
add(BorderLayout.CENTER, textField);
add(BorderLayout.SOUTH, button);
}
public void start(){
System.out.println("Applet starting.");
}
public void stop(){
System.out.println("Applet stopping.");
}
public void destroy(){
System.out.println("Destroy method called.");
}
public void actionPerformed(ActionEvent event){
11
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
try{
Class.forName(_driver);
con = DriverManager.getConnection(_url);
}catch (java.lang.ClassNotFoundException e){
System.out.println("Cannot find driver");
System.exit(1);
}catch (java.sql.SQLException e){
System.out.println("Cannot get connection");
System.exit(1);
}
Object source = event.getSource();
if(source == button){
if(_clickMeMode){
JTextArea displayText = new JTextArea();
try{
//Write to database
String theText = textField.getText();
// Statement stmt = con.createStatement();
Statement statement = con.createStatement();
// String updateString = "INSERT INTO dba VALUES ('" + theText + "')";
String updateString = "Insert Into Employee (LName) " + "Values ('"+theText+"')";
int count = statement.executeUpdate(updateString);
//statememt.execute(updateString);
//Read from database
ResultSet results = statement.executeQuery("SELECT LName FROM Employee ");
while(results.next()){
String s = results.getString("LName");
displayText.append(s + "\n");
}
statement.close();
}catch(java.sql.SQLException e){
System.out.println("Cannot create SQL statement");
System.exit(1);
}
//Display text read from database
text.setText("Text retrieved from file:");
button.setText("Click Again");
_clickMeMode = false;
//Display text read from database
} else {
text.setText("Text to save to file:");
textField.setText("");
button.setText("Click Me");
_clickMeMode = true;
}
}
}
}
12
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
Setup the JDBC-ODBC
Bridge with ODBC Driver in windows
Open DataBase Connectivity (ODBC) is Microsoft's programming interface for
accessing a large number of relational databases on numerous platforms. The JDBCODBC bridge is built into the Solaris and Windows versions of the Java platform so you
can do two things:
1.
2.
Use ODBC from a Java program
Load ODBC drivers as JDBC drivers. (Please see the ODBC setup at the end of
this paper)
Starting the Applet: To successfully run the DbaOdbAppl.java applet needs an
available database driver and a policy file. This section walks through the steps to get
everything set up. Here is the DbaAppl.html file for running the DbaOdb applet:
HTML>
<BODY>
<APPLET CODE=DbaOdbAppl.class
WIDTH=200
HEIGHT=100>
</APPLET>
</BODY>
</HTML>
Let’s run the applet now.
appletviewer DbaOdb.html
Locating the Database Driver: Supposing the driver is not mapped to the
DriverManager for some reason, the following error generates when you click the Click
Me button.
cannot find driver
This error means the DriverManager looked for the JDBC driver in the directory where
the applet HTML and class files are and could not find it. To correct this error, copy the
driver to the directory where the applet files are.
Once you have the driver in place, launch the applet again.
appletviewer DbaOdb.html
Reading a Stack Trace: If the DbaOdbAppl.java applet is launched without a policy file,
the following stack trace is generated when the end user clicks the Click Me button.
13
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
The first line in the stack trace below tells you your access is denied. This means this
stack trace was generated because the applet tried to access a system resource
without the proper permission. The second line means you need a RuntimePermission
that gives the applet access to the sun.jdbc.odbc package. This package provides the
JDBC-ODBC bridge functionality to the Java1 virtual machine (VM).
java.security.AccessControlException: access denied
(java.lang.RuntimePermission accessClassInPackage.sun.jdbc.odbc )
You can use the ASCII editor to make a policy file you need, or you can make it with a
Policy tool. Here is the policy file with the permission indicated by the stack trace:
grant {
permission java.lang.RuntimePermission
"accessClassInPackage.sun.jdbc.odbc";
};
Run the applet again, this time with a policy file named “policy” that has the above
permission in it:
appletviewer -J-Djava.security.policy=policy DbaOdb.html
14
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
You get a stack trace again, but this time it is a different error condition.
java.security.AccessControlException:
access denied (java.lang.RuntimePermission
file.encoding read)
The stack trace means the applet needs read permission to the encoded (binary) file.
Here is the DbaOdbPol policy file with the permission indicated by the stack trace added
to it:
The stack trace means the applet needs read permission to the encoded (binary) file.
Here is the “policy” policy file with the permission indicated by the stack trace added to
it:
grant {
permission java.lang.RuntimePermission
"accessClassInPackage.sun.jdbc.odbc";
permission java.util.PropertyPermission
"file.encoding", "read";
};
15
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
Run the applet again. If you use the above policy file with the Runtime and Property
permissions indicated, it works just fine.
appletviewer -J-Djava.security.policy=policy DbaOdb.html
Conclusion
The JDBC API gives Java programmers with a uniform interface to a wide range of
relational databases. All Java database related classes and interfaces are put together in
the API package of java.sql which consist of both the JDBC interfaces and the JDBC driver
manager. The use of JAVA applets and JDBC drivers is useful for the teaching of
database programming and web-based application development.
In this paper I have also discussed some basic ideas of Java and security and brought in
the new Java 2 security model. I have also demonstrated some basic code examples to
give a better knowledge of how Java can add more security layer to the fundamental
operating system, devoid of specific programming efforts.
16
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
References
 Marco Pistoia, Duane F. Reller, Deepak Gupta, Milind Nagnur, Ashok K. Ramani, Java 2 Network
Security, IBM, June 1999.
 Parixit Dilip Parekh, Java Applet Based, Database Management Interface, The Florida State
University, Spring 2006.
 Andrew Yang, James Linn, David Quadrato, Developing Integrated Web and Database Applications
And Using JAVA Applets and JDBC Drivers.
 Haruhiko Kaiya, Hitoshi Furukawa and Kenji Kaijiri, SECURITY POLICY CHECKER AND GENERATOR FOR
JAVA MOBILE CODES
 Herbert Schildt, Java 2 5th Edition, McGraw-Hill/Osborn, 2002
 Cay Horstmann, Big Java, John Wiley & Son, Inc., 2002
Web References
 Essentials, Part 1, Lesson 7: Database Access and Permissions,
http://java.sun.com/developer/onlineTraining/Programming/BasicJava1/dba.html#applet
 The JDBC Connection,
http://aspen.ucs.indiana.edu/webtech/jdbc/overviewpaper/JDBCconn.html
 Java Tutorial- Grant the Required Permission,
http://download.oracle.com/javase/tutorial/security/tour1/wstep2.html
 JDBC Example with Microsoft Access in Swing, Next and Previous navigation,
http://shivasoft.in/blog/programming/java/jdbc-example-with-microsoft-access-in-swing/
Configure ODBC Data Source
17
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
18
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
19
91.527 - Human Computer Interaction - Fall 2010 with Dr. Haim Levkowitz
Final paper by Khang Nguyen
20
Download