KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > xmlToJavaGUI > XMLToJavaGUI


1 package xmlToJavaGUI;
2
3 import java.io.BufferedInputStream JavaDoc;
4 import java.io.BufferedReader JavaDoc;
5 import java.io.File JavaDoc;
6 import java.io.FileInputStream JavaDoc;
7 import java.io.FileNotFoundException JavaDoc;
8 import java.io.FileReader JavaDoc;
9 import java.io.FileWriter JavaDoc;
10 import java.io.IOException JavaDoc;
11 import java.io.InputStreamReader JavaDoc;
12 import java.net.URL JavaDoc;
13 import java.util.ArrayList JavaDoc;
14 import java.util.StringTokenizer JavaDoc;
15
16 import org.eclipse.jface.dialogs.MessageDialog;
17 import org.eclipse.swt.SWT;
18 import org.eclipse.swt.events.MouseAdapter;
19 import org.eclipse.swt.events.MouseEvent;
20 import org.eclipse.swt.events.SelectionEvent;
21 import org.eclipse.swt.events.SelectionListener;
22 import org.eclipse.swt.graphics.Font;
23 import org.eclipse.swt.graphics.FontData;
24 import org.eclipse.swt.graphics.Image;
25 import org.eclipse.swt.layout.FillLayout;
26 import org.eclipse.swt.layout.GridData;
27 import org.eclipse.swt.layout.GridLayout;
28 import org.eclipse.swt.widgets.Button;
29 import org.eclipse.swt.widgets.Composite;
30 import org.eclipse.swt.widgets.Display;
31 import org.eclipse.swt.widgets.FileDialog;
32 import org.eclipse.swt.widgets.Group;
33 import org.eclipse.swt.widgets.Label;
34 import org.eclipse.swt.widgets.Shell;
35 import org.eclipse.swt.widgets.TabFolder;
36 import org.eclipse.swt.widgets.TabItem;
37 import org.eclipse.swt.widgets.Text;
38
39 /**
40  * @author boehm
41  *
42  * Purpose: Use this GUI to create Java classes out of a DTD with the Zeus (zeus.enhydra.org) - also create a test class to see usage
43  */

44 public class XMLToJavaGUI {
45
46   private static Composite step4Composite;
47   private static Text parentObjectText;
48   private static Text outputText;
49   private static Button ignoreIdButton;
50   private static Text packageStructureText;
51   private static Text rootText;
52   private static Button testClassesButton;
53   private static Button collapseSimpleButton;
54   private static TabFolder tabFolder;
55   private static Text dtdText;
56   final static Display display = new Display();
57
58   private static TabItem step1TabItem;
59   private static TabItem step2TabItem;
60   private static TabItem step3TabItem;
61   private static TabItem step4TabItem;
62   
63   private static String JavaDoc currPath = new File JavaDoc(".").getAbsolutePath().substring(0,new File JavaDoc(".").getAbsolutePath().length()-1);
64   private static String JavaDoc currFileName = "";
65   private static String JavaDoc zeusLocation = "";
66   private static String JavaDoc java14Location = "";
67   private static boolean generationOK = true;
68   private static boolean threadFinished = false;
69     
70   public static void main(String JavaDoc[] args) {
71     
72     final Shell shell = new Shell();
73     shell.setLayout(new FillLayout());
74     shell.setSize(800,600);
75     shell.setText("XML to Java for Zeus");
76     // try to set the image to a special one (from the JAR-File)
77
try {
78       URL JavaDoc path = (new Object JavaDoc()).getClass().getResource("/xmlIcon2.gif");
79       shell.setImage(new Image(display, path.openStream()));
80     } catch(Exception JavaDoc exc) {}
81     
82     {
83         tabFolder = new TabFolder(shell, SWT.NONE);
84       tabFolder.addSelectionListener(new SelectionListener() {
85         public void widgetDefaultSelected(SelectionEvent e) {}
86         public void widgetSelected(SelectionEvent e) {
87           // do not go to last tab manually!
88
if (tabFolder.getSelectionIndex() == tabFolder.getItemCount()-1) {
89             tabFolder.setSelection(tabFolder.getItemCount()-2);
90           }
91         }
92       });
93         {
94             step1TabItem = new TabItem(tabFolder, SWT.NONE);
95             step1TabItem.setText("Choose DTD");
96             {
97                 final Composite composite = new Composite(tabFolder, SWT.NONE);
98                 composite.setLayout(new GridLayout());
99                 step1TabItem.setControl(composite);
100                 {
101                     final Label loadLabel = new Label(composite, SWT.NONE);
102                     loadLabel.setText("Load DTD from file system - Attention: Java classes will be generated in the same folder where the DTD lies!");
103             FontData fData = new FontData("TimesNewRoman",9,SWT.BOLD);
104             loadLabel.setFont(new Font(display,fData));
105                 }
106                 {
107                     final Button loadButton = new Button(composite, SWT.NONE);
108                     loadButton.addMouseListener(new MouseAdapter() {
109                         public void mouseUp(MouseEvent e) {
110                 loadDTD(shell);
111                         }
112                     });
113                     loadButton.setText("&Load DTD");
114                 }
115                 {
116                     final Label infoLabel = new Label(composite, SWT.NONE);
117                     infoLabel.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_END | GridData.GRAB_VERTICAL | GridData.VERTICAL_ALIGN_END));
118                     infoLabel.setText("by Bernhard Böhm - KH Allgemeine Schwestern Linz, Austria");
119                 }
120             }
121         }
122         {
123             step2TabItem = new TabItem(tabFolder, SWT.NONE);
124             step2TabItem.setText("Review DTD");
125             {
126                 final Composite composite = new Composite(tabFolder, SWT.NONE);
127                 final GridLayout gridLayout = new GridLayout();
128                 composite.setLayout(gridLayout);
129                 step2TabItem.setControl(composite);
130                 {
131                     dtdText = new Text(composite, SWT.BORDER | SWT.H_SCROLL | SWT.MULTI | SWT.V_SCROLL);
132                     final GridData gridData = new GridData(GridData.FILL_BOTH);
133                     dtdText.setLayoutData(gridData);
134                     dtdText.setToolTipText("DTD definition from file");
135                 }
136                 {
137                     final Button saveButton = new Button(composite, SWT.NONE);
138                     saveButton.addMouseListener(new MouseAdapter() {
139                         public void mouseUp(MouseEvent e) {
140                 if (!dtdText.getText().equals("")) saveDTD(shell);
141                         }
142                     });
143                     saveButton.setToolTipText("If stored to a different directory this will also be taken to generate the Java classes!");
144                     saveButton.setText("&Save DTD changes");
145                 }
146             }
147         }
148         {
149             step3TabItem = new TabItem(tabFolder, SWT.NONE);
150             step3TabItem.setText("Choose Options for Java");
151             {
152                 final Composite composite = new Composite(tabFolder, SWT.NONE);
153                 final GridLayout gridLayout = new GridLayout();
154                 gridLayout.numColumns = 2;
155                 composite.setLayout(gridLayout);
156                 step3TabItem.setControl(composite);
157                 {
158                     final Label infoLabel = new Label(composite, SWT.NONE);
159                     final GridData gridData = new GridData();
160                     gridData.horizontalSpan = 2;
161                     infoLabel.setLayoutData(gridData);
162                     infoLabel.setText("The following possible settings are based on the underlying Zeus-Package for XML-to-Java generation and are all optional (except Java package structure)!");
163                 }
164                 {
165                     final Label sepLabel = new Label(composite, SWT.HORIZONTAL | SWT.SEPARATOR);
166                     final GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
167                     gridData.horizontalSpan = 2;
168                     sepLabel.setLayoutData(gridData);
169                 }
170                 {
171                     collapseSimpleButton = new Button(composite, SWT.CHECK);
172                     collapseSimpleButton.setSelection(true);
173                     collapseSimpleButton.setToolTipText("if selected elements that have no other attributes than #PCDATA can be accessed over one direct method (e.g. getName() instead of getName().getPCDATA())");
174                     final GridData gridData = new GridData();
175                     gridData.horizontalSpan = 2;
176                     collapseSimpleButton.setLayoutData(gridData);
177                     collapseSimpleButton.setText("collapse Simple Elements");
178                 }
179                 {
180                     ignoreIdButton = new Button(composite, SWT.CHECK);
181                     ignoreIdButton.setToolTipText("if selected an element is considered as simple when it has a text and an ID but nothing more");
182                     final GridData gridData = new GridData();
183                     gridData.horizontalSpan = 2;
184                     ignoreIdButton.setLayoutData(gridData);
185                     ignoreIdButton.setText("ignore ID attributes");
186                 }
187                 {
188                     final Label packageLabel = new Label(composite, SWT.NONE);
189                     packageLabel.setText("Java package structure:");
190                 }
191                 {
192                     packageStructureText = new Text(composite, SWT.BORDER);
193                     packageStructureText.setToolTipText("define the package structure under which all generated classes will be stored");
194                     final GridData gridData = new GridData();
195                     gridData.widthHint = 200;
196                     packageStructureText.setLayoutData(gridData);
197                 }
198                 {
199                     final Label rootLabel = new Label(composite, SWT.RIGHT);
200                     rootLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
201                     rootLabel.setText("Root element:");
202                 }
203                 {
204                     rootText = new Text(composite, SWT.BORDER);
205                     rootText.setToolTipText("explicetly define the root element to use (necessary if multiple root elements exists), by default it is determined by the DTD parser");
206                     final GridData gridData = new GridData();
207                     gridData.widthHint = 100;
208                     rootText.setLayoutData(gridData);
209                 }
210                 {
211                     final Group testGroup = new Group(composite, SWT.NONE);
212                     final GridLayout gridLayout_1 = new GridLayout();
213                     gridLayout_1.numColumns = 2;
214                     testGroup.setLayout(gridLayout_1);
215                     final GridData gridData = new GridData(GridData.VERTICAL_ALIGN_BEGINNING);
216                     gridData.horizontalSpan = 2;
217                     testGroup.setLayoutData(gridData);
218             {
219               testClassesButton = new Button(testGroup, SWT.CHECK);
220               final GridData gridDataTest = new GridData();
221               testClassesButton.setLayoutData(gridDataTest);
222               testClassesButton.setToolTipText("select if you want to see an example how to use the generated classes");
223               testClassesButton.setText("create Test Classes (does not effect Zeus generation!) -> parentObject needed:");
224             }
225                     {
226                         parentObjectText = new Text(testGroup, SWT.BORDER);
227                         parentObjectText.setToolTipText("define the parentObject (usually the first ELEMENT in your DTD)");
228                         final GridData gridData_1 = new GridData();
229                         gridData_1.widthHint = 100;
230                         parentObjectText.setLayoutData(gridData_1);
231                     }
232                 }
233                 {
234                     final Button generateButton = new Button(composite, SWT.NONE);
235                     final GridData gridData = new GridData();
236                     gridData.horizontalSpan = 2;
237                     generateButton.setLayoutData(gridData);
238                     generateButton.addMouseListener(new MouseAdapter() {
239                         public void mouseUp(MouseEvent e) {
240                 generateJavaClasses(shell);
241                         }
242                     });
243                     generateButton.setToolTipText("Java classes based on the last selected DTD will be created in the DTDs directory");
244                     generateButton.setText("&GENERATE Java Classes");
245                 }
246             }
247         }
248         {
249         step4TabItem = new TabItem(tabFolder, SWT.NONE);
250         step4TabItem.setText("View Code Generation");
251         {
252           step4Composite = new Composite(tabFolder, SWT.NONE);
253           step4Composite.setLayout(new FillLayout());
254           step4TabItem.setControl(step4Composite);
255           {
256             outputText = new Text(step4Composite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
257             outputText.setEditable(false);
258           }
259         }
260         }
261     }
262     // DESIGNER: Add controls before this line.
263
shell.open();
264     tabFolder.setSelection(0);
265     // now get all the properties from the property file
266
zeusLocation = XMLToJavaGUI.getPropertyFromFile("zeusLocation");
267     java14Location = XMLToJavaGUI.getPropertyFromFile("java1.4Location");
268     while (!shell.isDisposed()) {
269       if (!display.readAndDispatch())
270         display.sleep();
271     }
272   }
273   
274   private static void loadDTD(Shell shellIn) {
275     
276     FileDialog fileDialog = new FileDialog(shellIn,SWT.OPEN); // use SWT.OPEN to get a load-dialog
277

278     fileDialog.setFilterPath(currPath); // get the current path
279
fileDialog.setFilterNames(new String JavaDoc[] {"DTD-File"});
280     fileDialog.setFilterExtensions(new String JavaDoc[] {"*.dtd"});
281     fileDialog.open();
282     
283     // check if SAVE button was pressed (then fileNames != null)
284
if (fileDialog.getFileNames() != null) {
285       currPath = fileDialog.getFilterPath(); // reset to current DTD directory
286
currFileName = fileDialog.getFileName();
287       if (currFileName.indexOf(".") > -1) packageStructureText.setText(currFileName.substring(0,currFileName.indexOf(".")).toLowerCase());
288       else packageStructureText.setText(currFileName.toLowerCase());
289       ArrayList JavaDoc allDTDLines = readMyFile(currPath + File.separator + currFileName);
290       if (allDTDLines == null) return; // no valid file...
291
dtdText.setText("");
292       for(int i=0;i < allDTDLines.size();i++) {
293         dtdText.setText(dtdText.getText() + (String JavaDoc)allDTDLines.get(i) + "\r\n");
294       }
295       tabFolder.setSelection(1); // to see the DTD
296
}
297         
298   }
299   
300   private static void saveDTD(Shell shellIn) {
301     
302     FileDialog fileDialog = new FileDialog(shellIn,SWT.SAVE); // use SWT.SAVE to get a save-dialog
303

304     fileDialog.setFilterPath(currPath); // get the current path
305
fileDialog.setFilterNames(new String JavaDoc[] {"DTD-File"});
306     fileDialog.setFilterExtensions(new String JavaDoc[] {"*.dtd"});
307     fileDialog.open();
308     
309     if (fileDialog.getFileNames() != null) {
310
311       currPath = fileDialog.getFilterPath();
312       currFileName = fileDialog.getFileName();
313       if (!currFileName.endsWith(".dtd")) currFileName += ".dtd"; // this ending is necessary
314
if (currFileName.indexOf(".") > -1) packageStructureText.setText(currFileName.substring(0,currFileName.indexOf(".")).toLowerCase());
315       else packageStructureText.setText(currFileName.toLowerCase());
316       FileWriter JavaDoc fw = null;
317       String JavaDoc filename = currPath + File.separator + currFileName;
318       if (!filename.endsWith(".dtd")) filename += ".dtd";
319     
320       try {
321         fw = new FileWriter JavaDoc(filename);
322         fw.write(dtdText.getText().replaceAll("\r","")); // get UNIX style
323
} catch (IOException JavaDoc e) {
324         e.printStackTrace();
325       } finally {
326         try {
327           fw.close();
328         } catch (IOException JavaDoc e1) {
329           e1.printStackTrace();
330         }
331       }
332
333     }
334     
335   }
336   
337   private static ArrayList JavaDoc readMyFile(String JavaDoc fileName) {
338
339     ArrayList JavaDoc aList = new ArrayList JavaDoc();
340     BufferedReader JavaDoc br = null;
341     String JavaDoc record = null;
342     int recCount = 0;
343     
344     try {
345       
346       //URL filePath = (new Object()).getClass().getResource(fileName);
347
//BufferedInputStream bis = new BufferedInputStream(filePath.openStream()); // would use this if loaded from JAR only!
348
BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(fileName));
349       br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(bis));
350       
351       while ((record=br.readLine()) != null) {
352         // get each line
353
aList.add(record);
354       }
355            
356     }
357     catch (IOException JavaDoc e) {
358       // catch io errors from FileInputStream or readLine()
359
//System.out.println("IOException error! " + e.getMessage());
360
return null; // file does not exist
361
}
362     finally {
363       // if the file opened okay, make sure we close it
364
if (br != null) {
365         try {
366           br.close();
367         } catch(IOException JavaDoc ioe) {
368         }
369       }
370     } // finally
371

372     return aList;
373   } // readMyFile
374

375   public static String JavaDoc getPropertyFromFile(String JavaDoc propertyName) {
376     // special parameter fromLog indicates that no logging is allowed, otherwise an endless loop would occur!!!!
377
String JavaDoc propertyValue = "propertyNotDefined";
378        
379     // open File and check for propertyName - stringTokenizer is equal sign (propertySeperator)
380
String JavaDoc line;
381     FileReader JavaDoc fr;
382     BufferedReader JavaDoc br;
383     boolean foundProperty = false;
384
385     try {
386       fr = new FileReader JavaDoc(currPath + "XMLToJavaGUI.cfg");
387       br = new BufferedReader JavaDoc(fr);
388       line = br.readLine();
389       while ((line != null) && (!foundProperty)) {
390         // check for current property
391
StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(line,"=",false);
392         // compare the first token with the property name
393
if (st.nextToken().equals(propertyName)) {
394           // property found => set values
395
propertyValue = st.nextToken(); // second token is propertyValue
396
foundProperty = true;
397         }
398         // get next line if not already found
399
if (!foundProperty) {
400           line = br.readLine();
401         }
402       }
403       br.close();
404       fr.close();
405     }
406     catch (FileNotFoundException JavaDoc fnfe) {
407       System.err.println("PorpertyFile [" + currPath + File.separator + "XMLToJavaGUI.cfg" + "] is missing!");
408     }
409     catch (Exception JavaDoc e) {
410       System.err.println("Problem occured when trying to read properties from file!");
411     }
412
413     // return the value from the property file
414
return propertyValue;
415     
416   }
417
418   private static void generateJavaClasses(Shell shellIn) {
419     
420     // now call the zeus package for java code generation with the options entered! First check some dependencies!
421
if (zeusLocation.equals("propertyNotDefined")) {
422       MessageDialog.openError(shellIn,"Missing Zeus Location","No Zeus location is defined in XMLToJavaGUI.cfg file!");
423       return;
424     }
425     if (java14Location.equals("propertyNotDefined")) {
426       MessageDialog.openError(shellIn,"Missing Java Location","The location of Java 1.4 is not defined in XMLToJavaGUI.cfg file!");
427       return;
428     }
429     if (currFileName.equals("")) {
430       MessageDialog.openError(shellIn,"No DTD defined","Please load a DTD file at tab \"Choose DTD\" first!");
431       return;
432     }
433     if (packageStructureText.getText().equals("")) {
434       MessageDialog.openError(shellIn,"No package structure defined","Please define a package structure under which to store the class files!");
435       return;
436     }
437     if (testClassesButton.getSelection() && parentObjectText.getText().equals("")) {
438       MessageDialog.openWarning(shellIn,"Please define parentObject element",
439                                 "If you like to have test classes generated, you have to define a parentObject element - usually this should be the root element!");
440       return;
441     }
442     
443     String JavaDoc javaPackageName = "";
444     String JavaDoc executeCommand = "\"" + zeusLocation + File.separator + "zeus.bat\" -constraints=\"" + currPath + File.separator + currFileName +
445                             "\" -outputDir=" + "\"" + currPath + "\"";
446                             
447     if (collapseSimpleButton.getSelection()) executeCommand += " -collapseSimpleElements=true";
448     else executeCommand += " -collapseSimpleElements=false";
449     
450     if (ignoreIdButton.getSelection()) executeCommand += " -ignoreIDAttributes=true";
451     else executeCommand += " -ignoreIDAttributes=false";
452     
453     if (!packageStructureText.getText().equals("")) {
454       javaPackageName = packageStructureText.getText();
455       executeCommand += " -javaPackage=" + javaPackageName;
456     }
457     
458     if (!rootText.getText().equals("")) executeCommand += " -root=" + rootText.getText();
459     
460     // now execute the command
461
tabFolder.setSelection(tabFolder.getItemCount()-1); // go to output section
462
outputText.setText("--->Starting Java class generation!<---\n");
463     outputText.append("\n- Generating the Source Files from DTD..");
464
465     final String JavaDoc command1 = executeCommand;
466     
467     Thread JavaDoc execThread1 = new Thread JavaDoc() {
468       public void run() {
469         Process JavaDoc getState = null;
470         try {
471           getState = Runtime.getRuntime().exec(command1);
472       
473           BufferedReader JavaDoc br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(getState.getErrorStream()));
474           String JavaDoc dosResult = "";
475       
476           while((dosResult = br.readLine()) != null) {
477             final String JavaDoc dosResultDisplay = dosResult;
478             display.asyncExec(new Runnable JavaDoc() {
479               public void run() {
480                 outputText.append("\n" + dosResultDisplay);
481                 generationOK = false;
482               }
483             });
484           }
485       
486         } catch(IOException JavaDoc ioe) {
487           System.err.println("Error in executing command: " + ioe.toString());
488         }
489
490         threadFinished = true;
491         this.stop();
492       }
493     };
494     // wait with next step until background generation has been done...
495
execThread1.start();
496     int counter = 0;
497     while (!threadFinished) {
498       // draw points to not "deactivate" the window
499
counter++;
500       if (counter == 50000000) {
501         outputText.append(".");
502         step4Composite.redraw();
503         counter = 0;
504       }
505     }
506     threadFinished = false; // reset
507

508     // now compile the generated source files!
509
executeCommand = "\"" + java14Location + File.separator + "javac\" -classpath %CLASSPATH%;" + "\"" +
510                      currPath + File.separator + javaPackageName.replace('.',File.separator.charAt(0)) + "\" " +
511                      currPath + File.separator + javaPackageName.replace('.',File.separator.charAt(0)) + File.separator + "*.java";
512     final String JavaDoc command2 = executeCommand;
513     outputText.append("\n\n- Compiling the generated Source Files..");
514     step4Composite.redraw();
515                   
516     Thread JavaDoc execThread2 = new Thread JavaDoc() {
517       public void run() {
518         Process JavaDoc getState = null;
519         try {
520           getState = Runtime.getRuntime().exec(command2);
521             
522           BufferedReader JavaDoc br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(getState.getErrorStream()));
523           String JavaDoc dosResult = "";
524       
525           while((dosResult = br.readLine()) != null) {
526             final String JavaDoc dosResultDisplay = dosResult;
527             display.asyncExec(new Runnable JavaDoc() {
528               public void run() {
529                 outputText.append("\n" + dosResultDisplay);
530                 generationOK = false;
531               }
532             });
533           }
534       
535         } catch(IOException JavaDoc ioe) {
536           System.err.println("Error in executing compile: " + ioe.toString());
537         }
538         
539         threadFinished = true;
540         this.stop();
541       }
542     };
543     // wait with next step until background generation has been done...
544
execThread2.start();
545     counter = 0;
546     while (!threadFinished) {
547       // draw points to not "deactivate" the window
548
counter++;
549       if (counter == 50000000) {
550         outputText.append(".");
551         step4Composite.redraw();
552         counter = 0;
553       }
554     }
555     threadFinished = false; // reset
556

557     // ADDON - now check if a test class should be provided!
558
String JavaDoc testFileName = "";
559     if (testClassesButton.getSelection()) {
560       
561       testFileName = "Test" + parentObjectText.getText().toUpperCase();
562       outputText.append("\n\n- Now an example file (" + testFileName +
563                         ".java/class) will be created in the DTD directory.");
564       step4Composite.redraw();
565       FileWriter JavaDoc fw = null;
566       
567       try {
568         fw = new FileWriter JavaDoc(currPath + File.separator + testFileName + ".java");
569         String JavaDoc className = parentObjectText.getText().toUpperCase(); // root element has to be defined to get root class name
570

571         // now generate the sample java source code file
572
fw.write("import java.io.BufferedOutputStream;\n");
573         fw.write("import java.io.File;\n");
574         fw.write("import java.io.IOException;\n\n");
575         fw.write("import " + javaPackageName + "." + className + ";\n");
576         fw.write("import " + javaPackageName + "." + className + "Impl;\n\n");
577         fw.write("/* Purpose of this class is to test the Zeus-generated classes from XML!*/\n");
578         fw.write("public class " + testFileName + "{\n\n");
579         fw.write(" public static void main(String[] args) {\n\n");
580         fw.write(" // check if xml-file was given as a source\n");
581         fw.write(" if (args.length != 1) {\n");
582         fw.write(" System.out.println(\"Usage: java " + testFileName + " [xml-file location]\");\n");
583         fw.write(" return;\n");
584         fw.write(" }\n\n");
585         fw.write(" // now get the Parent object\n");
586         fw.write(" " + className + " parentObject = null;\n");
587         fw.write(" try {\n");
588         fw.write(" parentObject = " + className + "Impl.unmarshal(new File(args[0])); // get the Java objects from XML\n");
589         fw.write(" } catch(IOException ioe) {\n");
590         fw.write(" System.out.println(\"IOE-unmarhal: \" + ioe.toString());\n");
591         fw.write(" }\n\n");
592         fw.write(" if (parentObject == null) System.out.println(\"no valid parent object!\");\n");
593         fw.write(" else {\n");
594         fw.write(" System.out.println(\"Test-Class: \" + parentObject.getClass().getName());\n");
595         fw.write(" // IMPORTANT: take a look at the class definition to find sub elements that hold actual values\n");
596         fw.write(" // and also print them here to get familiar with the object handling!\n\n");
597         fw.write(" // now transform the whole Java object (that was read from sample file) back to XML\n");
598         fw.write(" try {\n");
599         fw.write(" parentObject.marshal(new BufferedOutputStream(System.out));\n");
600         fw.write(" } catch(IOException ioe) {\n");
601         fw.write(" System.out.println(\"IOE-marshal: \" + ioe.toString());\n");
602         fw.write(" }\n");
603         fw.write(" }\n");
604         fw.write(" }\n");
605         fw.write("}\n");
606       } catch(IOException JavaDoc ioe) {
607         System.err.println("Error creating test file: " + ioe.toString());
608       } finally {
609         try {
610           fw.close();
611         } catch (IOException JavaDoc e1) {
612           e1.printStackTrace();
613         }
614       }
615
616       // also immediately compile the Test File!
617
executeCommand = "\"" + java14Location + File.separator + "javac\" -classpath %CLASSPATH%;\"" + currPath + "\";\"" +
618                        currPath + File.separator + javaPackageName.replace('.',File.separator.charAt(0)) + "\" " +
619                        currPath + File.separator + testFileName + ".java";
620       final String JavaDoc command3 = executeCommand;
621                   
622       Thread JavaDoc execThread3 = new Thread JavaDoc() {
623         public void run() {
624           Process JavaDoc getState = null;
625           try {
626             getState = Runtime.getRuntime().exec(command3);
627           
628             BufferedReader JavaDoc br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(getState.getErrorStream()));
629             String JavaDoc dosResult = "";
630           
631             while((dosResult = br.readLine()) != null) {
632               final String JavaDoc dosResultDisplay = dosResult;
633               display.asyncExec(new Runnable JavaDoc() {
634                 public void run() {
635                   outputText.append("\n" + dosResultDisplay);
636                   generationOK = false;
637                 }
638               });
639             }
640           
641           } catch(IOException JavaDoc ioe) {
642             System.err.println("Error in executing compile: " + ioe.toString());
643           }
644
645           threadFinished = true;
646           this.stop();
647         }
648       };
649
650       // wait with next step until background generation has been done...
651
execThread3.start();
652       while (!threadFinished) {}
653     }
654     // redraw output from Threads...
655
step4Composite.redraw();
656
657     // set output window to finished
658
if (generationOK) {
659       outputText.append("\n\n---> Generation FINISHED SUCCESSFULLY! <---");
660       if (!testFileName.equals("")) {
661         outputText.append("\n\nUse \"java " + testFileName + " sampleXMLFile.xml\" to run it and take a look at the code (" +
662                           testFileName + ".java) how to use the XML-Classes!");
663         outputText.append("\nATTENTION: The CLASSPATH settings must be correct (including the current directory and the xerces.jar) when running the example," +
664                           "\nand you also have to use Java 1.4!");
665       }
666     } else outputText.append("\n---> Generation FINISHED with ERRORS (please take a look at the messages above)! <---");
667   }
668
669 }
670
Popular Tags