Docsity

Java Software Design Lab 1: XML Data Processing with JAXP - Prof. Jeff K. Salvage, Lab Reports of Computer Science

Toggle sidebar
bg1
CS 350
CS 350 –
–Software Design
Software Design
Lab 1
Lab 1 -
-Part II
Part II
ALMOST NO CODE CHANGES TO
ALMOST NO CODE CHANGES TO Scheduler.java
Scheduler.java
/*
/*
*
* Scheduler.java
Scheduler.java
* Copyright (c) 2007 Drexel University. All rights reserved.
* Copyright (c) 2007 Drexel University. All rights reserved.
*/
*/
package edu.drexel.cs350;
package edu.drexel.cs350;
import
import java.io.File
java.io.File;
;
import
import java.text.ParseException
java.text.ParseException;
;
import
import java.text.SimpleDateFormat
java.text.SimpleDateFormat;
;
import
import java.util.Scanner
java.util.Scanner;
;
/**
/**
* Main class
* Main class
*
*
* @author Sunny Huynh
* @author Sunny Huynh
* @version 1.0
* @version 1.0
* @since 1.0
* @since 1.0
*/
*/
public class Scheduler
public class Scheduler
{
{private static final
private static final SimpleDateFormat
SimpleDateFormat timeFormat
timeFormat =
=
new
new SimpleDateFormat("H:mm
SimpleDateFormat("H:mm");
");
private final School
private final School school
school;
;
private final Scanner
private final Scanner scanner
scanner;
;
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12

Partial preview of the text

Download Java Software Design Lab 1: XML Data Processing with JAXP - Prof. Jeff K. Salvage and more Lab Reports Computer Science in PDF only on Docsity!

CS 350

CS 350 –

  • Software Design

Software Design

Lab 1

Lab 1 -

  • Part II

Part II

ALMOST NO CODE CHANGES TO

ALMOST NO CODE CHANGES TO Scheduler.java

Scheduler.java

Scheduler.java

Scheduler.java

* Copyright (c) 2007 Drexel University. All rights reserved.* Copyright (c) 2007 Drexel University. All rights reserved.//

package edu.drexel.cs350;

package edu.drexel.cs350;

import

import

java.io.Filejava.io.File;

import

import

java.text.ParseExceptionjava.text.ParseException;

import

import

java.text.SimpleDateFormat;java.text.SimpleDateFormat

import

import

java.util.Scanner;java.util.Scanner

* Main class* Main class** * @author Sunny Huynh* @author Sunny Huynh* @version 1.0* @version 1.0* @since 1.0* @since 1.0//

public class Scheduler

public class Scheduler

private static final

private static final

SimpleDateFormat

SimpleDateFormat

timeFormattimeFormat

new

new

SimpleDateFormat("H:mm");SimpleDateFormat("H:mm

private final School

private final School

school

school;

private final Scanner

private final Scanner

scannerscanner;

CS 350 CS 350 –

  • Software Design

Software Design

Lab 1 Lab 1 -

  • Part II

Part II

The instantiation of school must change from a

The instantiation of school must change from a DatabaseSchool

DatabaseSchool to an

to an XMLSchool

XMLSchool.

public Scheduler()

throws

public Scheduler()

throws

SchedulerException

SchedulerException

// school = new

// school = new

DatabaseSchool

DatabaseSchool();

school = new

school = new

XmlSchool

XmlSchool();

scanner = new

scanner = new

Scanner(System.in);Scanner(System.in

public void run()

public void run()

boolean

boolean

quit = false;

quit = false;

while (!quit) {

while (!quit) {

try

try

quit =

quit =

processInput();processInput

catch (Exception ex) {

catch (Exception ex) {

System.out.println("Error

System.out.println("Error: " +

ex.getMessage());ex.getMessage

CS 350 CS 350 –

  • Software Design

Software Design

Lab 1 Lab 1 -

  • Part II

Part II

New Files

New Files

XmlConnection.java

XmlConnection.java

XMLCourseManager.java

XMLCourseManager.java

XMLDataSource.java

XMLDataSource.java

XMLSchedule.java

XMLSchedule.java

XMLSchool.java

XMLSchool.java

XMLStudentManager.java

XMLStudentManager.java

CS 350 CS 350 –

  • Software Design

Software Design

Lab 1 Lab 1 -

  • Part II

Part II

XmlConnection.java

XmlConnection.java //

XmlConnection.javaXmlConnection.java

Copyright

(c)

Drexel

University.

All

rights

reserved.

Copyright

(c)

Drexel

University.

All

rights

reserved.

package

edu.drexel.cs350;

package

edu.drexel.cs350;

importimport

java.util.logging.Logger;java.util.logging.Logger

Base

class

for

all

those

that

use

an

XML

data

source

Base

class

for

all

those

that

use

an

XML

data

source

@author

Sunny

Huynh

@author

Sunny

Huynh

@version

@version

@since

@since

public

abstract

class

public

abstract

class

XmlConnection XmlConnection

protected

final

protected

final

XmlDataSource XmlDataSource

data;data;

protected

Logger

protected

Logger

loggerlogger;

protected protected

XmlConnection(finalXmlConnection(final

XmlDataSourceXmlDataSource

data) data)

this.data this.data

data;

data;

this.logger this.logger

Logger.getLogger(getClass().getName());Logger.getLogger(getClass().getName

CS 350 CS 350 –

  • Software Design

Software Design

Lab 1 Lab 1 -

  • Part II

Part II

XmlDataSource.java

XmlDataSource.java import

org.w3c.dom.Document;

import

org.w3c.dom.Document;

import

org.w3c.dom.Element;

import

org.w3c.dom.Element;

import

org.w3c.dom.Node;

import

org.w3c.dom.Node;

import

org.w3c.dom.NodeList;

import

org.w3c.dom.NodeList;

importimport

org.xml.sax.InputSourceorg.xml.sax.InputSource;

importimport

org.xml.sax.SAXException;org.xml.sax.SAXException

FascadeFascade

to

XML

data

file

to

XML

data

file

@author

Sunny

Huynh

@author

Sunny

Huynh

@version

@version

@since

@since

public

class

public

class

XmlDataSource XmlDataSource

protected

final

Logger

protected

final

Logger

logger logger;

protected

final

File

protected

final

File

filefile;

protected

final

Document

data;

protected

final

Document

data;

protected

final

protected

final

XPath XPath

xpathxpath;

CS 350 CS 350 –

  • Software Design

Software Design

Lab 1 Lab 1 -

  • Part II

Part II

Interface with XML via JAVA using JAXP

Interface with XML via JAVA using JAXP –

  • Java API for XML Processing

Java API for XML Processing

Added in 1.

Added in 1.

Comes default with the standard JAVA

Comes default with the standard JAVA

Sunny states, that he is confident, but not sure that this metho

Sunny states, that he is confident, but not sure that this method is more efficient than using

d is more efficient than using

XStream

XStream and is more flexible.

and is more flexible.

Document

Document –

  • Within Java we must represent the XML as a tree of nodes. JAXP

Within Java we must represent the XML as a tree of nodes. JAXP does this by

does this by

building a document.

building a document.

To instantiate a document it is a two step process. First create

To instantiate a document it is a two step process. First create the document builder and

the document builder and

then instantiate the document itself.

then instantiate the document itself.

//Instantiates

a

Document

Builder

//Instantiates

a

Document

Builder

finalfinal

DocumentBuilder DocumentBuilder

builder

builder

DocumentBuilderFactory.newInstance().newDocumentBuilderDocumentBuilderFactory.newInstance().newDocumentBuilder();

//This

loads

the

XML

file

stored

in

file

//This

loads

the

XML

file

stored

in

file

data

data

builder.parse(filebuilder.parse(file);

CS 350 CS 350 –

  • Software Design

Software Design

Lab 1 Lab 1 -

  • Part II

Part II

Note, the table is called Students, the row is called student

Note, the table is called Students, the row is called student

@Attribute = value (any

@Attribute = value (any boolean

boolean logic) @Attribute = value

logic) @Attribute = value

What is returned is specified by /attribute list

What is returned is specified by /attribute list final

String

final

String

xpath xpath

String.format("%s String.format("%s/student"

/student"

"[@first "[@first-

-name

'%s'

and

@last

name

'%s'

and

@last-

-name

'%s']/@id",

XML_ROOT,

name

'%s']/@id",

XML_ROOT,

XmlDataSource.escapeXml(fname XmlDataSource.escapeXml(fname),

XmlDataSource.escapeXml(lname XmlDataSource.escapeXml(lname));

Our code in

Our code in XMLDataSource

XMLDataSource, provides

, provides getNodeList

getNodeList, a fa

, a faç

çade to allow us to perform the

ade to allow us to perform the

query. Once the values are stored in nodes, we can pull the out

query. Once the values are stored in nodes, we can pull the out one at a time and store

one at a time and store

them in an array.

them in an array.

i.e.

i.e.final final

NodeList NodeList

nodes

nodes

data.getNodeList(xpath);data.getNodeList(xpath

intint[]

ids

new

[]

ids

new

int[nodes.getLengthint[nodes.getLength()];

()];

for

for

(int

int

i

i

i

i

ids.length;ids.length

++i)

++i)

ids[iids[i]

]

Integer.parseInt(nodes.item(i).getNodeValueInteger.parseInt(nodes.item(i).getNodeValue());

CS 350 CS 350 –

  • Software Design

Software Design

Lab 1 Lab 1 -

  • Part II

Part II

Removing Items from XML

Removing Items from XML

You require a handle to the node you wish removed.

You require a handle to the node you wish removed.

Use a function we wrote to find that node

Use a function we wrote to find that node final

Element

node

final

Element

node

getStudentNode(id getStudentNode(id);

Ensure that the node is not empty

Ensure that the node is not empty if

(node

null)

if

(node

null)

throw

new

throw

new

SchedulerException("Student SchedulerException("Student

id

does

not

exist");

id

does

not

exist");

Get the parent node

Get the parent node final

Element

root

final

Element

root

(Element)data.getNode(XML_ROOT

Element)data.getNode(XML_ROOT);

Use the parent node to remove the node we wish deleted

Use the parent node to remove the node we wish deleted root.removeChild(noderoot.removeChild(node);

Perform other deletes that are part of the cascade, because the

Perform other deletes that are part of the cascade, because the Schedule is not part of the

Schedule is not part of the

Student tree. The delete will handle any cascading from the tree

Student tree. The delete will handle any cascading from the tree that is being deleted from.

that is being deleted from.

cascade

delete

cascade

delete

removeFromSchedule(idremoveFromSchedule(id);

CS 350

CS 350 –

– Software Design

Software Design

Lab 1

Lab 1 -

- Part II

Part II

Adding a Node in XML

Adding a Node in XML

Check that you do not

Check that you do notviolate key constraints

violate key constraints

Instantiate a new node

Instantiate a new node

Call the

Call the setAttribute

setAttribute

CS 350 CS 350 –

  • Software Design

Software Design

Lab 1 Lab 1 -

  • Part II

Part II

XmlDataSource.java

XmlDataSource.java

//If

a

filename

is

passed

as

a

string,

automatically

create

a

f

//If

a

filename

is

passed

as

a

string,

automatically

create

a

file

object

containing

the

ile

object

containing

the

filename

and

its

path

filename

and

its

path

//After

the

object

is

created,

the

alternate

constructor

i

//After

the

object

is

created,

the

alternate

constructor

is

called.

s

called.

public public

XmlDataSource(final XmlDataSource(final

String

path)

throws

String

path)

throws

SchedulerException SchedulerException

this(new this(new

File(pathFile(path));

public public

XmlDataSource(finalXmlDataSource(final

File

path)

throws

File

path)

throws

SchedulerExceptionSchedulerException

try

try

logger

logger

Logger.getLogger(getClass().getName());Logger.getLogger(getClass().getName

file

path;

file

path;

//Create

a

new

XML

document

in

memory

//Create

a

new

XML

document

in

memory

final final

DocumentBuilderDocumentBuilder

builder

builder

DocumentBuilderFactory.newInstance DocumentBuilderFactory.newInstance()

.newDocumentBuilder

newDocumentBuilder();

//Check

if

the

file

specified

in

the

file

obje

//Check

if

the

file

specified

in

the

file

object

exists

ct

exists

if

if

(file.exists

file.exists()

file.canReadfile.canRead())

//if

the

file

exists,

load

the

data

into

//if

the

file

exists,

load

the

data

into

the

document

the

document

data

data

builder.parse(file);builder.parse(file

else else

//otherwise

build

the

XML

structure

via

//otherwise

build

the

XML

structure

via

a

self

written

function

a

self

written

function

data

data

createDocument(builder);createDocument(builder

CS 350 CS 350 –

  • Software Design

Software Design

Lab 1 Lab 1 -

  • Part II

Part II

XmlDataSource.java

XmlDataSource.java

private

Document

private

Document

createDocument(finalcreateDocument(final

DocumentBuilderDocumentBuilder

builder)builder)

throws throws

SAXException SAXException,

IOExceptionIOException

final

String

xml

"<students

/><courses

final

String

xml

"<students

/><courses

"<offerings

/><schedule

/>";

"<offerings

/><schedule

/>";

return return

builder.parse(new builder.parse(new

InputSource(newInputSource(new

StringReader(xml)));StringReader(xml

The

XML

document

in

memory

is

stored

as

a

tree,

this

re

The

XML

document

in

memory

is

stored

as

a

tree,

this

returns

the

root

of

the

turns

the

root

of

the

tree. tree.

public

Document

public

Document

getDocument getDocument()

return

data;

return

data;

//Creates

a

node,

given

a

name,

that

can

be

added

to

the

t

//Creates

a

node,

given

a

name,

that

can

be

added

to

the

tree

ree

public

Element

public

Element

createNode(final createNode(final

String

name)

String

name)

return return

data.createElement(name);data.createElement(name

//Some

nodes

have

values,

like

Description.

This

creates

a

//Some

nodes

have

values,

like

Description.

This

creates

a

node,

with

a

value,

that

node,

with

a

value,

that

can

be

added

to

the

tree.

can

be

added

to

the

tree.

public

Element

public

Element

createNode(final createNode(final

String

name,

final

String

value)

String

name,

final

String

value)

final

Element

node

final

Element

node

data.createElement(name);data.createElement(name

node.setTextContent(value node.setTextContent(value);

return

node;

return

node;

CS 350 CS 350 –

  • Software Design

Software Design

Lab 1 Lab 1 -

  • Part II

Part II

XmlDataSource.java

XmlDataSource.java

//path

contains

the

//path

contains

the

Xpath Xpath,

aka

the

query.

aka

the

query.

getNodegetNode

returns

only

a

single

node

(from

the

returns

only

a

single

node

(from

the

root),

in

this

case

the

first

node

if

more

than

one

node

is

retu

root),

in

this

case

the

first

node

if

more

than

one

node

is

returned.

rned.

public

Node

public

Node

getNode(final getNode(final

String

path)

throws

String

path)

throws

XPathExceptionXPathException

//calls

the

"main"

//calls

the

"main"

getNode,getNode

passing

it

the

root

passing

it

the

root

return return

getNode(pathgetNode(path,

data);

data);

//path

contains

the

//path

contains

the

Xpath Xpath,

aka

the

query.

aka

the

query.

getNodegetNode

returns

only

a

single

node

(from

a

returns

only

a

single

node

(from

a

specified

node),

in

this

case

the

first

node

if

more

than

one

no

specified

node),

in

this

case

the

first

node

if

more

than

one

node

is

returned.

de

is

returned.

public

Node

public

Node

getNode(final getNode(final

String

path,

final

Node

root)

String

path,

final

Node

root)

throws throws

XPathExceptionXPathException

Compile

the

path

and

store

the

result

in

Compile

the

path

and

store

the

result

in

exprexpr

final final

XPathExpressionXPathExpression

exprexpr

xpath.compile(pathxpath.compile(path);

Perform

the

query

and

return

the

first

node

that

Perform

the

query

and

return

the

first

node

that

matches

the

criteria

matches

the

criteria

return

return

(Node)expr.evaluate(root

Node)expr.evaluate(root,

XPathConstants.NODE);XPathConstants.NODE

//path

contains

the

//path

contains

the

Xpath Xpath,

aka

the

query.

aka

the

query.

getNodegetNode

returns

only

a

collection

of

nodes

returns

only

a

collection

of

nodes

(from

the

root),

in

this

case

the

first

node

if

more

than

one

no

(from

the

root),

in

this

case

the

first

node

if

more

than

one

node

is

returned.

de

is

returned.

public public

NodeListNodeList

getNodeList(final getNodeList(final

String

path)

throws

String

path)

throws

XPathExceptionXPathException

return return

getNodeList(pathgetNodeList(path,

data);

data);