Last
revision of this document: |
This
step of the tutorial integrates an externals JAR-file (jdom.jar) into
the buildpath and reads the parameters for the connection to the
database from a file in XML-format (XML = Extented Markup Language).
Preface:
The
code written in this tutorial is far away from being
optimized.
Emphasis of this tutorial is to develop the application
in small steps where the completion of each step allows the
application to be run eror-free and showing the result aimed by the
step.
Therefore the code is written to be understandable in favor
of being optimized.
Credits:
A
tutorial for reading a XML-structure in JAVA can be found under
http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/dom/index.html
.
JS_Base02, Step 2 – Adding an action: selectin the file with the SQL-commands completed – and its prerequisites too.
Basic knowledge of Java programming language; particular the usage of libraries.
Preparation:
Methods
for reading data out of XML-formated structures are contained in an
(external) Java-ARchive named 'jdom.jar'.
As a preparation this
lesoon, 'jdom.jar' has to be downloaded.
Depending on the
folder under which 'jdom.jar' should be stored, your user rights may
not be sufficient.
If you experience problems during saving the
file either do the download with 'root'-rights or save to a folder
you are allowed to save.
The
'jdom.jar' archive can be downloaded from the following
web-site:
http://www.jdom.org/dist/binary
:
Unfortunately,
the requiered file is in compressed format.
Click onto
'jdom-1.0.tar.gz' to inspect the contents.
Leave the prposed
application 'file-roller' and click the [ OK ] button.
Move
to the folder /jdom-1.0/build to see the requested 'jdom.jar'
Use
to pick the file for later 'paste'.>Edit>Copy
Use
the File Browser to 'paste' the file onto its final destination.
I
used the directory '/usr/java/j2sdk1.4.2_08/lib/extern' - and will
refer to it in further steps.
This directory can only be
write-accessed with rights as 'root'.
Now
it is time to incorporate the file into the libraries.
Mark the
project 'JS_Base02', right click with the mouse and select
.>Properties
On
the window that just openend select 'Java Build Path' (on the left
side) and the tab 'Libraries'.
Then click the button [ Add
External JARs... ].
Manouvre
to the directory '/usr/java/j2sdk1.4.2_08/lib/extern' and select the
file 'jdom.jar'.
Then click the button [ OK ].
The
incorporation of the selected JAR into the Java Build Path is shown.
Click the button [ OK ].
Code
to read a XML-structure:
In
the following explanations all new code is written in bold
letters.
Code generated by the template or entered in previous
steps (old code) is in italics.
Larger blocks of old code may be
skipped.
First,
as the text-area
txt_Report
should display the progress-status, it must allow to be called from
other methods within the package - i.e. it must
be defined as
.protected
.
At
the same time, the area will be set as not 'Editable'. This prevents
entering data by the user protected
JTextArea get_txt_Report {
/* The code of
this method auto-creates the element if it is not already defined
*/
if
(txt_Report ==
null) {
try
{
txt_Report
= new
JTextArea();
}txt_Report
.setName(“
);txt_Report
“
txt_Report
.setToolTipText(“Report“
);
txt_Report
.setMargin(new
Insets(3,3,3,3));txt_Report
.setEditable(false); catch
(Throwable Exc) {
The
next task is, to implement amethod to be called when the button
'Start SQL execution' is clicked.
protected
static void handleEvent(JS_DBLoad parmCallingFrame,
ActionEvent parmActionEvent){
/*
String
cmd = parmActionEvent.getActionCommand().trim();
*
Extract the action-command (in form of a String) that triggered the
Event from the Event */ /*
*
Compare the String with the action-command and call the adjacent
method */
if
(cmd.equals(„btn_Select“))
processSelectFile(parmCallingFrame);
}
if
(cmd.equals(„btn_Start“))
processDBLoad(parmCallingFrame);As
the code to be executed will get voluminous, the subtasks are coded
in several methods.
More calls will be added later on - first the
method to read the parameters from the XML-file is
coded.protected
static void
processDBLoad(
{JS_DBLoad
parmCallingFrame)/*
*
Define an array that holds the parameters for the database-access */
String[]
array_DBParms;
array_DBParms
= processGetDBParms(parmCallingFrame); }
To
explain the following code, some assumptions were made:
* The
XML-file with the parameters to connect to the database is in the
same directory as the input-file with the SQL-commands.
* The
file-name of the XML-file is 'DBParms.xml' with the exact
case-sensitivity.
protected
static
}String[]
processGetDBParm(
{JS_DBLoad
parmCallingFrame)/*
Define the return-value holding the parameters */
String
strDirectorySeparator = System.getProperty(
String[]
array_DBParms = new String[4];/*
Get the selected input-file to derive the directory in the next step
*/
String
strDirectory = parmCallingFrame.get_txt_InputFile().getText(); /*
Get the (system-specific) character that separates directories and
files */
„file.separator“
);
/*
Get the position of the last DirectorySeparator, the one were the
file-name is therafter */
int
intLastDirectorySeparator =
strDirectory
.lastIndexOf(strDirectorySeparator
);
/*
If there is not separator, e.g. no input-file selected
write
an error message to the text-area and return an empty array */
if
(intLastDirectorySeparator < 1)
{
parmCallingFrame.get_txt_Report().append(„Invalid
selection: “
+ strDirectory + „\n“
);
return
new String[0];
}
/*
Build the String with the complete directory and file-name and
display it in the text-area */
String
strDBParmDirectoryAndFile =
strDirectory.substring(1, intLastDirectorySwparator + 1) +
„DBParms.xml“
;
parmCallingFrame.get_txt_Report().append(
„DB-Parameters will be read from file: “
+ strDBParmDirectoryAndFile
+ „\n“
);
/*
Return the array with the parameters */ return
array_DBParms;
It
is a good time now to see an intermediate result before coding is
continued - but first:
Please remind to save the code just
typed.
Run
the application again by selecting
>Run>Run
As>Java Application.
The result of the shown screenshot is
after doing the following:
* First click the button 'Start SQL
execution' without previous selection of a file.
* Then selection
the correct input-file and click the button'Start
SQL execution' thereafter.
For
the next steps of coding, the import of some packages for
XML-handling have to be included.
package
js_base02.application;
import
java.awt.*;
import
java.awt.event.*;
import
org.jdom.*;
import
org.jdom.input.*;
/**
*
* @author kurt@javascout.biz
*
@date 2006-02-10
First
(as for every reading of a file ;-) ), the file has to be
opened.
The org.jdom package offers a simple method to open and
check a file with data in XML-format.
(If you do not fully
understand what is going on there - just take it as given that this
code has to be like it is ;-) )./*
Build the String with the complete directory and file-name and
display it in the text-area /
String
strDBParmDirectoryAndFile =
strDirectory.substring(1, intLastDirectorySwparator + 1) +
„DBParms.xml“
;
parmCallingFrame.get_txt_Report().append(
„DB-Parameters will be read from file: “
+ strDBParmDirectoryAndFile
+ „\n“
);/*
*
Open the file with methods provided by the org.jdom.input package
*/
try
{
SAXBuilder
parser = new
SAXBuilder();
Document
document =
parser.build(strDBParmDirectoryAndFile);
Element
XML_RootElement =
document.getRootElement();
}
catch(JDOMException
e)
{
parmCallingFrame.get_txt_Report().append(„'Not well formed exception' opening: „ + strDBParmDirectoryAndFile + „\n“);
return
new String[0];
catch(Exception
e)
{
}
parmCallingFrame.get_txt_Report().append(„'Unknown error' opening: „ + strDBParmDirectoryAndFile + „\n“);
return
new String[0];
}/*
*
File could be opened and contains a 'well-formed' XML-structure
*/ parmCallingFrame.get_txt_Report().append(„XML-Root-Element found in: „ +
strDBParmDirectoryAndFile + „\n“);
/*
Return the array with the parameters */
return
array_DBParms;
}
To
see what happens at this point you may save and run the application
again by selecting
>Run>Run
As>Java Application.
As a result you will see, that a 'Not
well formed exception' occured when opening the file.
The reason
is, that the file is empty; i.e. the data does not represent a
XML-structure.
To
save some space, a screenshot is not included.
Enter
the database-parameters in the file DBParms.xml:
Open
the file DBParms.xml in
the folder src/Input by double-clicking onto it (if not already
opened).
Enter the following text with the parameters for the
access to the database:
The
values assume that the database is set up as described in the
Tutorial JS_DB01 - Set up the MySQL
database for access by JAVA-applications .<DataBaseParameters>
<DataBaseDriverName>com.mysql.jdbc.driver
</DataBaseDriverName><DataBaseName>
</DataBaseParameters>jdbc:mysql://192.168.0.62:3306/js_tutorial/
</DataBaseName
><DataBaseUserID>
mysql
</DataBaseUserID
><DataBasePassword>
drowssap
</DataBasePassword
>If
you are operating on a machine with another TCP/IP-ID (which I
assume that your machine is not running with 192.168.0.62),
using another database, database-name, user-ID or password, adapt
the values according to it.
Code
the derivation of the values from the XML-structure in DBParms.xml:
After
the file was opened and the XML-structure was read, the values for
the individual parameters are extracted and stored in the array
passed as parameter.
This array is then read by the calling
method and the values are used for the connection to the database
later on./*
*
File could be opened and contains a 'well-formed' XML-structure
*/
parmCallingFrame.get_txt_Report().append(„XML-Root-Element found in: „ + strDBParmDirectoryAndFile + „\n“);
parmCallingFrame.get_txt_Report().append(„XML-Root-Element name: „ +
XML_RootElement.getName() + „\n“);
/*
*
The methods of package org.jdom.* are used to extract the elements
by parameter-name
* and get the values of them
*/
Element
elementSingleParm;
/*
Get the value for the name of the JAR file with the Database-Driver
*/
elementSingleParm
= XML_RootElement.getChild(
parmCallingFrame.get_txt_Report().append(„„DataBaseDriverName„
);
if
(elementSingleParm
== null
)
{
parmCallingFrame.get_txt_Report().append(„Element
'
);DataBaseDriverName
'
not found \n“
return
new String[0];
}
array_DBParms[0]
=
elementSingleParm.getText();
parmCallingFrame.get_txt_Report().append(„
DataBaseDriverName
: „ + array_DBParms[0] + „\n“);
/*
*
Get the value for the name of the Database
*/ elementSingleParm
= XML_RootElement.getChild(
„DataBaseName„
);
if
(elementSingleParm
== null
)
{
parmCallingFrame.get_txt_Report().append(„Element
'DataBaseName' not found \n“
);
return
new String[0];
}
array_DBParms[1]
=
elementSingleParm.getText();
parmCallingFrame.get_txt_Report().append(„DataBaseName: „ +
array_DBParms[1] + „\n“);
/*
*
Get the value for the user-ID with access rights to the database
*/ elementSingleParm
= XML_RootElement.getChild(
„DataBaseUserID„
);
if
(elementSingleParm
== null
)
{
parmCallingFrame.get_txt_Report().append(„Element
'
);DataBaseUserID
'
not found \n“
return
new String[0];
}
array_DBParms[2]
=
elementSingleParm.getText();
parmCallingFrame.get_txt_Report().append(„
DataBaseUserID
: „ + array_DBParms[2] + „\n“);
/*
*
Get the value for the password of the user-ID with access rights to
the database */ elementSingleParm
= XML_RootElement.getChild(
„DataBasePassword„
);
if
(elementSingleParm
== null
)
{
parmCallingFrame.get_txt_Report().append(„Element
'
);DataBasePassword
'
not found \n“
return
new String[0];
}
array_DBParms[3]
=
elementSingleParm.getText();
DataBasePassword
exists \n“
);
/*
* Return the array with the parameters */
return
array_DBParms;
}
}
To
see what happens at this point you may save and run the application
again by selecting
>Run>Run
As>Java Application.
As
a result you should see the following result:
Next
Step:
Code
the connect to the database which is specified by the just read
parameters.
JS_Base02e,
Step 4 - Connect to the database.