Enhance the day planner case study to allow the user to add a note as a child node of date. Use graphical user interface components to accept year, month, day, time and notes from the user. If no existing date node matches the date entered by the user, create a new date node within the appropriate year node and append a new note node. If no year node matches, create both the year node and the date node and append a new note node to it. View the new nodes by query.
What will be an ideal response?
```
34
import java.io.*;
5 import org.w3c.dom.*;
6 import org.xml.sax.*;
7 import javax.xml.parsers.*;
8 import com.sun.xml.tree.XmlDocument;
9
10 import java.io.*;
11 import java.awt.*;
12 import java.util.*;
13 import javax.swing.*;
14
15 public class DOMPlanner {
16
17 // variable to display output
18 private JTextArea display;
19
20 // variable to read from a file
21 private InputSource input;
22
23 private Document document;
24
25 // variables to store the query parameters and the result
26 private int year, month, day, timePeriod;
27 private String resultYear, resultDay;
28
29 public DOMPlanner( JTextArea output )
30 {
31 year = month = day = timePeriod = -1;
32 display = output;
33
34 try {
35
36 // obtain the default parser
37 DocumentBuilderFactory factory =
38 DocumentBuilderFactory.newInstance();
39 factory.setValidating( true );
40 DocumentBuilder builder = factory.newDocumentBuilder();
41
42 // set error handler for validation errors
43 builder.setErrorHandler( new MyErrorHandler() );
44
45 // obtain document object from XML document
46 document = builder.parse( new File( "planner.xml" ) );
47 }
48 catch ( SAXParseException spe ) {
49 System.err.println( "Parse error: " +
50 spe.getMessage() );
51 System.exit( 1 );
52 }
53 catch ( SAXException se ) {
54 se.printStackTrace();
55 }
56 catch ( FileNotFoundException fne ) {
57 System.err.println( "File \"planner.xml\" not found." );
58 System.exit( 1 );
59 }
60 catch ( Exception e ) {
61 e.printStackTrace();
62 }
63 }
64
65 // method to get the available years from the XML file
66 public String[] getYears()
67 {
68 String availableYears[];
69 StringTokenizer tokens;
70 String str = " ";
71 int i = 0;
72 Element root = document.getDocumentElement();
73 NodeList yearNodes =
74 root.getElementsByTagName( "year" );
75
76 // get value of attribute 'value' for each 'year' node
77 for ( i = 0; i < yearNodes.getLength(); i++ ) {
78 NamedNodeMap yearAttributes =
79 yearNodes.item( i ).getAttributes();
80 str += " " + yearAttributes.item( 0 ).getNodeValue();
81 }
82
83 tokens = new StringTokenizer( str );
84 availableYears = new String[ tokens.countTokens() + 1 ];
85 availableYears[ 0 ] = "ANY";
86
87 i = 1;
88
89 // form an array of strings containing available years
90 while ( tokens.hasMoreTokens() )
91 availableYears[ i++ ] = tokens.nextToken();
92
93 return availableYears;
94 }
95
96 // method to initialize the query
97 public void getQueryResult( int y, int m, int d, int t )
98 {
99 year = y;
100 month = m;
101 day = d;
102 resultYear = "";
103 resultDay = "";
104 timePeriod = t;
105
106 display.setText( "*** YOUR DAY PLANNER ***" );
107
108 getResult( document );
109 }
110
111 // method to output the result of query
112 public void getResult( Node node )
113 {
114
115 // process each type of node
116 // if it contains child nodes, process it recursively
117 // unil the deepest element
118 switch ( node.getNodeType() ) {
119
120 // if it is a Document node process its children
121 case Node.DOCUMENT_NODE:
122 Document doc = ( Document ) node;
123 getResult( doc.getDocumentElement() );
124 break;
125
126 // process element node according to its tag name
127 case Node.ELEMENT_NODE:
128 if ( node.getNodeName().equals( "planner" ) )
129 processChildNodes( node.getChildNodes() );
130 else if ( node.getNodeName().equals( "year" ) ) {
131
132 // find the attribute value for year and
133 // check if it matches the query
134 NamedNodeMap yearAttributes =
135 node.getAttributes();
136 Node value = yearAttributes.item( 0 );
137 if ( Integer.parseInt( value.getNodeValue() )
138 == year || year == -1 ) {
139 resultYear = " Y " +
140 Integer.parseInt( value.getNodeValue() );
141 processChildNodes( node.getChildNodes() );
142 }
143 else
144 return;
145 }
146 else if ( node.getNodeName().equals( "date" ) ) {
147 NamedNodeMap dateAttributes =
148 node.getAttributes();
149 Node nodeMonth = dateAttributes.item( 0 );
150 Node nodeDay = dateAttributes.item( 1 );
151 int m =
152 Integer.parseInt( nodeMonth.getNodeValue() );
153 int d =
154 Integer.parseInt( nodeDay.getNodeValue() ) ;
155
156 // check if the current 'date' node satifies the query
157 if ( ( m == month && d == day ) ||
158 ( month == -1 && d == day ) ||
159 ( m == month && day == -1 ) ||
160 ( month == -1 && day == -1 ) ) {
161 resultDay = "DATE: D " + d + " M " + m ;
162 processChildNodes( node.getChildNodes() );
163 }
164 else
165 return;
166 }
167 else if ( node.getNodeName().equals( "note" ) ) {
168
169 // fetch attributes for the note node and
170 // verify its attribute values with the query
171 NamedNodeMap noteAttributes =
172 node.getAttributes();
173 int scheduleTime;
174
175 if ( noteAttributes.getLength() != 0 ) {
176 Node nodeTime = noteAttributes.item( 0 );
177 scheduleTime =
178 Integer.parseInt( nodeTime.getNodeValue() );
179 }
180 else
181 scheduleTime = -1;
182
183 // if the time lies between the periods of the
184 // day display the value of node 'note'
185 if ( isBetween( scheduleTime ) ) {
186 Node child =
187 ( node.getChildNodes() ).item( 0 );
188 String s =
189 child.getNodeValue().trim();
190
191 display.append( "\n" + resultDay +
192 resultYear );
193
194 if ( scheduleTime != -1 )
195 display.append( "\nTIME: " +
196 scheduleTime +" > " + s );
197 else
198 display.append( "\nALL DAY > " + s );
199
200 display.append( "\n* * * * * * * * * *" );
201 }
202 else
203 return;
204 }
205 break;
206 }
207 }
208
209 // method to process child nodes
210 public void processChildNodes( NodeList children )
211 {
212 if ( children.getLength() != 0 )
213 for ( int i = 0; i < children.getLength(); i++ )
214 getResult( children.item( i ) );
215
216 return;
217 }
218
219 // method to compare the time with various periods
220 // of the day
221 public boolean isBetween( int time )
222 {
223 switch ( timePeriod ) {
224
225 case -1 :
226 return true;
227
228 case 0 : //morning
229 if ( time >= 500 && time < 1200 )
230 return true;
231 break;
232
233 case 1 : //afternoon
234 if ( time >= 1200 && time < 1800 )
235 return true;
236 break;
237
238 case 2 : //evening
239 if ( time >= 1800 && time < 2100 )
240 return true;
241 break;
242
243 case 3 : //night
244 if ( time >= 2100 || time < 500 )
245 return true;
246 break;
247
248 default:
249 System.out.println( "Illegal time in XML file" );
250 }
251 return false;
252 }
253
254 // methods to add a node
255 public void addNote( int y, int m, int d, int t, String s)
256 {
257
258 if ( m > 12 || m < 0 || d > 31 || d < 0 ) {
259 System.out.println( "Invalid date or month" );
260 return;
261 }
262
263 // first create a note node
264 Element note = document.createElement( "note" );
265 note.appendChild(document.createTextNode( s ) );
266
267 // create an attribute
268 Attr attrTime = document.createAttribute( "time" );
269
270 if ( t != -1 ) {
271 attrTime.setValue( Integer.toString( t ) );
272 note.setAttributeNode( attrTime );
273 }
274
275 Element eleYear = ( Element ) findYearNode( y );
276 Element eleday = ( Element ) findDateNode( eleYear, m, d );
277 eleday.appendChild( note );
278
279 try {
280 ( (XmlDocument) document).write(
281 new FileOutputStream( "planner.xml" ) );
282 }
283 catch ( Exception e ) {
284 e.printStackTrace();
285 }
286 }
287
288 public Node findYearNode( int y )
289 {
290 Element root = document.getDocumentElement();
291 NodeList yearNodes =
292 root.getElementsByTagName( "year" );
293
294 if ( yearNodes.getLength() != 0 ) {
295
296 // get value of attribute 'value' for each 'year' node
297 for ( int i = 0; i < yearNodes.getLength(); i++ ) {
298 NamedNodeMap yearAttributes =
299 yearNodes.item( i ).getAttributes();
300 int j = Integer.parseInt(
301 yearAttributes.item( 0 ).getNodeValue() );
302 if ( y == j )
303 return yearNodes.item( i );
304 }
305 }
306
307 // if year node not found create a new year node
308 Element yearNode = document.createElement( "year" );
309 Attr attrValue = document.createAttribute( "value" );
310 attrValue.setValue( Integer.toString( y ) );
311 yearNode.setAttributeNode( attrValue );
312 root.appendChild( yearNode );
313 return yearNode;
314 }
315
316 public Node findDateNode( Node eleYear, int m, int d )
317 {
318 NodeList dateNodes =
319 ( (Element) eleYear).getElementsByTagName( "date" );
320 if ( dateNodes.getLength() != 0 ) {
321
322 for ( int i = 0; i < dateNodes.getLength(); i++ ) {
323 NamedNodeMap dateAttributes =
324 dateNodes.item(i).getAttributes();
325 Node monthNode = dateAttributes.item( 0 );
326 Node dayNode = dateAttributes.item( 1 );
327
328 int monthNumber =
329 Integer.parseInt( monthNode.getNodeValue() );
330 int dateNumber =
331 Integer.parseInt( dayNode.getNodeValue() ) ;
332
333 // check if the current date and month satisfies the query
334 if ( monthNumber == m && dateNumber == d )
335 return dateNodes.item( i );
336 }
337 }
338
339 // if no date node matches, create a new date node
340 Element eleDate = document.createElement( "date" );
341 Attr attrMonth = document.createAttribute( "month" );
342 Attr attrDay = document.createAttribute( "day" );
343
344 attrMonth.setValue( Integer.toString( m ) );
345 attrDay.setValue( Integer.toString( d ) );
346
347 eleDate.setAttributeNode( attrMonth );
348 eleDate.setAttributeNode( attrDay );
349
350 // add the new Date node to year node
351 eleYear.appendChild( eleDate );
352 return eleDate;
353 }
354 }
358 import org.xml.sax.ErrorHandler;
359 import org.xml.sax.SAXException;
360 import org.xml.sax.SAXParseException;
361
362 public class MyErrorHandler implements ErrorHandler
363 {
364
365 // throw SAXException for fatal errors
366 public void fatalError( SAXParseException exception )
367 throws SAXException
368 {
369 throw exception;
370 }
371
372 public void error( SAXParseException e )
373 throws SAXParseException
374 {
375 throw e;
376 }
377
378 // print any warnings
379 public void warning( SAXParseException err )
380 throws SAXParseException
381 {
382 System.err.println( "Warning: " + err.getMessage() );
383 }
384 }
388 import java.awt.*;
389 import java.awt.event.*;
390 import javax.swing.*;
391 import javax.swing.event.*;
392
393 public class DayPlanner extends JFrame
394 implements ActionListener {
395
396 // GUI components
397 private JTextArea display;
398 private JComboBox year, month, day, time, mode;
399 private JTextField yearField, monthField;
400 private JTextField dayField, timeField, noteField;
401 private JButton query, save;
402 private JPanel panel1, panel2, editPanel, editor;
403 private JPanel modePanel, userInterface;
404 private DOMPlanner handler;
405 private Container c;
406
407 public DayPlanner()
408 {
409 super( "Day planner using DOM" );
410
411 // set the output font
412 Font font = new Font( "Monospaced",
413 java.awt.Font.BOLD, 16 );
414 display = new JTextArea();
415 display.setFont( font );
416 display.setEditable( false );
417
418 handler = new DOMPlanner( display );
421 year = new JComboBox( handler.getYears() );
422
423 String months[] = new String[ 13 ];
424 months[ 0 ] = "ANY";
425
426 for ( int i = 1; i < 13; i++ )
427 months[ i ] = "" + ( i );
428
429 month = new JComboBox( months );
430
431 String days[] = new String[ 32 ];
432 days[ 0 ] = "ANY";
433
434 for ( int i = 1; i < 32; i++ )
435 days[ i ] = "" + ( i );
436
437 day = new JComboBox( days );
438
439 String times[] = { "ANY", "Morning", "Afternoon",
440 "Evening", "Night" };
441 time = new JComboBox( times );
442
443 String modes[] = { "Query", "Add" };
444 mode = new JComboBox( modes );
445 mode.addActionListener( this );
446
447 query = new JButton( "Get Schedules" );
448 query
You might also like to view...
Which of the following statements is true about file storage on a FAT file system?
A. the clusters are organized as a linked-list B. if a file only uses part of a cluster, the next file uses the rest of the cluster C. the filename is stored in the first cluster occupied by the file D. the final cluster is filled in with all 0's to indicate the end of file
The accompanying figure illustrates the screen that appears when you type "word" in the text box. Which of the following is the title of this screen that is missing in this picture?
A. Search B. Start C. Programs D. Select