570 likes | 636 Views
What is XML?. XML stands for E X tensible M arkup L anguage XML is a markup language much like HTML, but all XML elements must have a closing tag XML tags are case sensitive All XML elements must be properly nested All XML documents must have a single root element
E N D
What is XML? • XML stands for EXtensible Markup Language • XML is a markup language much like HTML, but • all XML elements must have a closing tag • XML tags are case sensitive • All XML elements must be properly nested • All XML documents must have a single root element • Attribute values must always be quoted • XML was designed to describe data • XML tags are not predefined. You must define your own tags. Example: <note date="12/11/2002"> <to>Rob</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
Example <?xml version="1.0"?> <factory xSize="7" ySize="7"> <location> <floor/> </location> <location> <floor/> <walls north="true" east="false" south="false" west="false"/> </location> ... </factory>
XML Schema XML Schema is a language that can be used to describe the syntactical structure of XML documents. It is • expressed in XML, • self-describing and simple, • can be used to validate XML documents, • W3C approved (World Wide Web Consortium). An XML document may specify its schema using the schemaLocation attribute. <factory xSize="2" ySize="2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="...factory.xsd"> ... In Java XML parsers can be triggered to use a specific schema.
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:include schemaLocation="belt.xsd"/> ... <xs:element name="factory"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" ref="location"/> </xs:sequence> <xs:attribute name="xSize" use="required" type="xs:nonNegativeInteger"/> <xs:attribute name="ySize" use="required" type="xs:nonNegativeInteger"/> </xs:complexType> </xs:element> <xs:element name="location"> <xs:complexType> <xs:sequence> <xs:choice minOccurs="1" maxOccurs="1"> <xs:element ref="belt"/> ... </xs:choice> <xs:choice minOccurs="0" maxOccurs="1"> <xs:element ref="crusher"/> <xs:element ref="pusher"/> </xs:choice> <xs:element ref="walls" minOccurs="0" maxOccurs="1"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
Parsing XML In order to parse an XML source you’ll need: • javax.xml.parsers.DocumentBuilderFacory A factory creating DocumentBuilders. According to the parameters of the factory the generated DocumentBuilder will use certain XMLSchemas. • javax.xml.parsers.DocumentBuilder This class will parse the input and create a Document. • the input – an element of one of the following classes • File • org.xml.sax.InputSource • Reader • InputStream • String (url)
Interface Node • An XML document is represented by a tree structure, in which each tree node is a class implementing the interface org.w3c.dom.Node. • important methods • String getNodeName() • #document • #text • user defined tag • NamedNodeMap getAttributes() • Attr getNamedItem(String name) • Node getFirstChild() • Node getLastChild() • NodeList getChildNodes() • int length() • Node item(int i)
Example #document factory #text location #text floor #text #text location #text floor #text #walls #text #text ... The tree structure of the factory example with the name of each node.
Example in Java factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); try { factory.setAttribute(JAXP_SCHEMA_LANGUAGE,W3C_XML_SCHEMA); } catch (Exception ex) { ... }; String schema = "...factory.xsd"; String[] schemas = { schema }; factory.setAttribute(JAXP_SCHEMA_SOURCE,schemas); try { builder = factory.newDocumentBuilder(); } catch (Exception ex) { ... }; File f = new File("...factory.xml"); try { document = builder.parse(f); } catch (Exception ex) { ... };
COSC3P40.xml Package for easy creating and parsing XML code. public interface XMLObject { public String toXMLString(); } public interface XMLNodeConverter<E> { public E convertXMLNode(Node node); }
COSC3P40.xml.XMLReader public class XMLReader<E> { private static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; private static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; private static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; private DocumentBuilderFactory factory; private DocumentBuilder builder = null; private Document document = null; private XMLNodeConverter<E> converter = null;
public XMLReader() { factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); try { factory.setAttribute(JAXP_SCHEMA_LANGUAGE,W3C_XML_SCHEMA); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); }; } public void setXMLSchema(String schema) { String[] schemas = { schema }; factory.setAttribute(JAXP_SCHEMA_SOURCE,schemas); try { builder = factory.newDocumentBuilder(); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); }; }
public void setXMLNodeConverter(XMLNodeConverter<E> converter) { this.converter = converter; } public E readXML(File f) { checkStatus(); try { document = builder.parse(f); } catch (Exception ex) { ex.printStackTrace(); }; return converter.convertXMLNode(document.getFirstChild()); } ... private void checkStatus() { if (builder==null) { System.out.println("No XMLSchema set."); System.exit(1); }; if (converter==null) { System.out.println("No XMLNodeConverter set."); System.exit(1); }; }
COSC3P40.xml.XMLTools Collection of useful (static) methods. public static List<Node> getChildNodes(Node node) { List<Node> result = new LinkedList<Node>(); NodeList list = node.getChildNodes(); for(int i=0;i<list.getLength();i++) if (!list.item(i).getNodeName().equals("#text")) result.add(list.item(i)); return result; } public static int getIntAttribute(Node node, String name) { Attr attr = (Attr) node.getAttributes().getNamedItem(name); return Integer.valueOf(attr.getValue()); }
public static boolean getBoolAttribute(Node node, String name) { Attr attr = (Attr) node.getAttributes().getNamedItem(name); return Boolean.valueOf(attr.getValue()); } public static String getStringAttribute(Node node, String name) { Attr attr = (Attr) node.getAttributes().getNamedItem("name"); return attr.getValue(); } public static Enum getEnumAttribute(Class c, Node node, String name){ Attr attr = (Attr) node.getAttributes().getNamedItem(name); Class[] array = new Class[1]; array[0] = String.class; Object obj = null; try { obj = c.getMethod("valueOf",array).invoke(null,attr.getValue()); } catch (Exception e) { ... }; if (obj instanceof Enum) return (Enum) obj; return null; }
Example public class Factory implements XMLObject { ... public static Factory load(String fileName) { String xsd = "../XSD/factory.xsd"; XMLReader<Factory> reader = new XMLReader<Factory>(); reader.setXMLSchema(xsd); reader.setXMLNodeConverter(new FactoryReader()); return reader.readXML(new File(fileName)); } ... public String toXMLString() { String result = "<factory xSize=\"" + xSize + "\" ySize=\"" + ySize +"\">\n"; for(int i=0; i<xSize; i++) for(int j=0; j<ySize; j++) result += grid[i][j].toXMLString() + "\n"; return result + "</factory>"; }
public class FactoryReader implements XMLNodeConverter<Factory> { private LocationReader locReader; ... public Factory convertXMLNode(Node node) { Factory factory = null; if (node.getNodeName().equals("factory")) { int xSize = getIntAttribute(node,"xSize"); int ySize = getIntAttribute(node,"ySize"); Location[][] grid = new Location[xSize][ySize]; List<Node> list = getChildNodes(node); if (list.size() == xSize*ySize) { for(int i=0; i<xSize; i++) for(int j=0; j<ySize; j++) grid[i][j] = locReader.convertXMLNode(list.get(i*ySize+j)); factory = new Factory(xSize,ySize,grid); }; }; return factory; } }
Multithreading • multitasking Example: Downloading a file from the internet while writing a paper at the same time. • thread • single sequential flow of control • managed by the same Java virtual machine • share common memory space • thread versus process; process • managed by the operating system • no shared memory space • communication just via interprocess communication channels
Multithreading (cont.) • advantages • reactive systems • continuously monitor arrays of sensors and react according to the sensor readings • reactive GUI • allows to respond to user input immediately even if the application is engaged in a time-consuming task • multi-client servers • multiple processors • executing threads on different processors in parallel
Thread A Thread B Time Thread A starts Thread B starts Multithreading (cont.) • nondeterministic thread ordering • multi processors • time-sharing
Creating and Running Threads Three possibilities: • extending the Thread class • implementing the Runnable interface • using anonymous inner classes
Thread class • class for active objects • subclasses of Thread should override the run method • run hook method • implements the interface Runnable • implement run • start method • run should not invoked directly. Doing so would cause the method to be executed in the thread of the caller, not in a new thread. • use the start method to execute a thread
Extending the Thread Class public class MyThread extends Thread { public void run() { System.out.println(“Do something cool here.“); } } Thread myThread = new MyThread(); myThread.start();
Implementing the Runnable interface public class MyClass extends SomeOtherClass implements Runnable { public MyClass() { Thread thread = new Thread(this); thread.start(); } public void run() { System.out.println(“Do something cool here.“); } }
Using anonymous inner classes new Thread() { public void run() { System.out.println(“Do something cool here.“); } }.start();
Comparison of the methods • Extending the Thread class is easy but uses inheritance. • Use the Runnable interface if you want to have a class that extends another and can also run as a thread. • Use anonymous inner classes only if the code in the run method is very short.
Thread safety • Safety properties are conditions that should hold throughout the lifetime of a program. • stipulate that nothing bad should ever happen • interrupted threads may leave an object in an invalid state public class Maze { private int playerX; private int playerY; public boolean isAtExit() { return (playerX == 0 && playerY == 0); } public void setPosition(int x, int y) { playerX = x; playerY = y; } }
Initial state of p: playerX = 1 playerY = 0 Thread B Thread A p.setPosition(0,1); playerX = 0 playerY = 0 playerX = x; Thread A is pre-empted by Thread B p.isAtExit(); returns true playerX = 0 playerY = 1 playerY = y;
Controlling Threads • states of a thread • new • alive • runnable • blocked • dead • priorities • always runs highest priority thread • random choice, among those with same priority • preemptive, i.e., a thread of higher priority will preempt a thread with lower priority • use priorities only to tune the performance of programs
New Not interrupted Wait for target to finish Wait to be notified Sleeping Interrupted Dead Alive yield() Blocked Runnable wait() start() notify() notifyAll() join() interrupt() Target finish sleep() run() returns Time out interrupt()
Synchronization public class Maze { private int playerX; private int playerY; public synchronized boolean isAtExit() { return (playerX == 0 && playerY == 0); } public synchronized void setPosition(int x, int y) { playerX = x; playerY = y; } } This code is thread-safe.
Synchronization (cont.) When the JVM executes a synchronized method, it acquires a lock on that object. • if one synchronized method owns a lock, no other synchronized method can run until the lock is released • only one lock on an object at a time • lock is released when the method is finished
Synchronization (cont.) Do not oversynchronize! • synchronize if one or more threads will access the same object or field. • do not synchronize an entire method if only parts of the method need to be synchronized public void myMethod() { synchronize(this) { // code that needs to be synchronized } // code that is already thread-safe } • do not synchronize a method that uses only local variables: //a method which should not be synchronized public int square(int n) { int s = n * n; return s; }
Using sleep() sleep() is a static method of the class Thread. Thread.sleep(1000); • causes the currently running thread to sleep for 1000 (or any amount of time given as an argument) miliseconds (state blocked) • a sleeping thread does not consume any CPU time • when the specified duration of time expires the thread returns to the runnable state
Using wait() and notify() Problem: Thread A should wait on Thread B to send a message: Solution 1: //Thread A public void waitForMessage() { while (hasMessage == false) { Thread.sleep(100); } } //Thread B public void sendMessage(String message) { … hasMessage = true; }
Solution 2: //Thread A public synchronized void waitForMessage() { try { wait(); } catch (InterruptedException ex) {} } //Thread B public synchronized void sendMessage(String message) { … notify(); }
The wait(), notify() and notifyAll() methods are defined in the class Object. • the wait() method is used in synchronized blocks of code. • the lock is released and the thread waits to be notified (state blocked) • the notify() method is also used in synchronized blocks of code. • notifies on thread waiting on the same lock (randomly) • waiting thread becomes runnable • variants • wait for a maximum amount of time: wait(100); • there is no way to tell whether the wait() method returned because of a timeout or because the thread was notified • notify all threads waiting on the lock: notifyAll();
Using join() The join() method causes a thread to enter the blocked state and wait for another thread to finish, at which time it will be returned to the runnable state. • useful, when you want to make sure all threads are finished before you do some cleanup
public static void main(String[] args) { Thread playerA = new Thread() { public void run() { System.out.println("A started"); try { Thread.sleep(10000); } catch (InterruptedException e) {}; System.out.println("A terminated"); } }; Thread playerB = new Thread() { public void run() { System.out.println("B started"); try { Thread.sleep(15000); } catch (InterruptedException e) {}; System.out.println("B terminated"); } };
playerA.start(); playerB.start(); try { playerA.join(); playerB.join(); } catch (InterruptedException e) {}; System.out.println("Cleanup"); }
Deadlock Deadlock is the result of two threads that stall because they are waiting on each other to do something. General situation: • Thread A acquires lock 1. • Thread B acquires lock 2. • Thread B waits for lock 1 to be released. • Thread A waits for lock 2 to be released.
Deadlock - Example MessageHandler a; MessageHandler b; //Thread A //Thread B a.waitForMessage(); b.waitForMessage(); b.sendMessage(“...“); a.sendMessage(“...“); In general, detecting and preventing deadlock is difficult. • Using the deadlock detector. • run your program • press Ctrl+break (DOS box) • JVM displays a full thread dumb
Liveness Liveness properties stipulate that something positive will eventually happen. Examples: • A certain task will be completed eventually. • A thread should always respond to user input. • The status of certain systems must be displayed and updated constantly. Common types of liveness failures: • deadlock • contention • aka starvation or indefinite postponement • thread never gets a chance to run • sleep() or yield() • dormancy • blocked thread never released • failure to call notify() • premature termination
Example – Thread pool A thread pool is a group of threads designed to execute arbitrary tasks. • limits the number of threads on the system for processor-intensive tasks ThreadPool threadPool = new ThreadPool(3); for (int i=0; i < 8; i++) { threadPool.runTask(createTask(i)); } threadPool.join();
private static final Runnable createTask() { return new Runnable() { public void run() { System.out.println("Task " + taskID + ": start"); // simulate a long-running task try { Thread.sleep(500); } catch (InterruptedException ex) { }; System.out.println("Task " + taskID + ": end"); } };
Thread group ThreadPool uses the ThreadGroup class. A ThreadGroup is a group of threads and some methods to modify the threads. • setDaemon() - changes the daemon status of this thread group. A daemon thread group is automatically destroyed when its last thread is stopped. • interrupt() – interrupts all threads in this thread group. • activeCount() - returns an estimate of the number of active threads in this thread group. • enumerate() - copies into the specified array (argument) every active thread in this thread group.
public class ThreadPool extends ThreadGroup { private boolean isAlive; private LinkedList<Runnable> taskQueue; //Java 1.5 private static int threadID; private static int threadPoolID; public ThreadPool(int numThreads) { super("ThreadPool-" + (threadPoolID++)); setDaemon(true); isAlive = true; taskQueue = new LinkedList<Runnable>(); //Java 1.5 for (int i=0; i<numThreads; i++) { new PooledThread().start(); } }
private class PooledThread extends Thread { public PooledThread() { super(ThreadPool.this,"PooledThread-" + (threadID++)); } public void run() { while (!isInterrupted()) { Runnable task = null; // get a task to run try { task = getTask(); } catch (InterruptedException ex) { } if (task == null) { //if getTask() returned null return; //or was interrupted close this } //thread by returning. try { //run the task, and eat any task.run(); //exceptions it throws } catch (Throwable t) { uncaughtException(this, t); } } } }
public synchronized void runTask(Runnable task) { if (!isAlive) { throw new IllegalStateException(); } if (task != null) { taskQueue.add(task); notify(); } } protected synchronized Runnable getTask() throws InterruptedException { while (taskQueue.size() == 0) { if (!isAlive) { return null; } wait(); } return taskQueue.removeFirst(); //Java 1.5 }
public void join() { // notify all waiting threads that this ThreadPool is no // longer alive synchronized (this) { isAlive = false; notifyAll(); } // wait for all threads to finish Thread[] threads = new Thread[activeCount()]; int count = enumerate(threads); for (int i=0; i<count; i++) { try { threads[i].join(); } catch (InterruptedException ex) { } } }
public synchronized void close() { if (isAlive) { isAlive = false; taskQueue.clear(); interrupt(); } }