PatientXMLValidator.java
001 package examples.xml.xmlbean;
002 
003 import org.apache.xmlbeans.XmlError;
004 import org.apache.xmlbeans.XmlObject;
005 import org.apache.xmlbeans.XmlOptions;
006 import java.io.File;
007 import java.util.ArrayList;
008 import java.util.Arrays;
009 import java.util.Comparator;
010 import weblogic.utils.compiler.Tool;
011 import noNamespace.MedicalRecordsDocument;
012 
013 public class PatientXMLValidator extends Tool {
014   private static int count = 0;
015    boolean verbose = false;
016    boolean recursive = true;
017 
018    PatientXMLValidator() {  }
019 
020    PatientXMLValidator(String[] args) {
021      super(args);
022    }
023 
024    public void searchAndValidate(File fthrows Exception {
025      if (f.isDirectory()) {
026        File[] files = f.listFiles();
027        Arrays.sort(files, new Comparator<Object>() {
028                              public int compare(Object o1, Object o2) {
029                                String fname1 = ((File)o1).getName();
030                                String fname2 = ((File)o2).getName();
031                                int n1=fname1.length(), n2=fname2.length();
032                                for (int i1=0, i2=0; i1<n1 && i2<n2; i1++, i2++) {
033                                    char c1 = fname1.charAt(i1);
034                                    char c2 = fname2.charAt(i2);
035                                    if (c1 != c2) {
036                                        c1 = Character.toUpperCase(c1);
037                                        c2 = Character.toUpperCase(c2);
038                                        if (c1 != c2) {
039                                            c1 = Character.toLowerCase(c1);
040                                            c2 = Character.toLowerCase(c2);
041                                            if (c1 != c2) {
042                                                return c1 - c2;
043                                            }
044                                        }
045                                    }
046                                  }
047                                  return n1 - n2;
048                                }
049                            }
050        );
051 
052        for (int i=0; i<files.length; i++) {
053          File file = files[i];
054          if (file.isDirectory()) searchAndValidate(file);
055          else if (file.getName().equals("patientInfo.xml")) validate(file);
056        }
057      }
058    }
059 
060    public void prepare() throws Exception {
061      // tool options
062      opts.addFlag("version""version 0.1");
063      opts.addOption("verbose""true/false""");
064      opts.addOption("exampleDir""path""Full path of example.");
065      opts.addFlag("recursive""Generate tests for the given example "+
066        "and all sub directories: default recursive");
067 
068      // this tool does not implement these options
069      opts.removeOption("gui");
070      opts.removeOption("script");
071      opts.removeOption("savescript");
072    }
073 
074    public void runBody() throws Exception {
075      File exampleHomeDir = null;
076 
077      // verbose setting
078      if (opts.hasOption("verbose"))
079        verbose = opts.getBooleanOption("verbose"false);
080      // recursive setting
081      if (opts.hasOption("recursive"))
082        recursive = opts.getBooleanOption("recursive"false);
083      // set example path
084 
085      if (isNotEmpty(opts.getOption("exampleDir"))) {
086        debug("Example directory: "+opts.getOption("exampleDir")+"\n");
087        exampleHomeDir = new File(opts.getOption("exampleDir"));
088      else {
089        throw new IllegalArgumentException("Examples directory is required.");
090      }
091 
092      execute(exampleHomeDir);
093    }
094 
095    private void execute(File exampleHomeDir) {
096      try {
097        log("Validate xmlBean found at root "+exampleHomeDir.getPath()+"\n");
098        if (exampleHomeDir.isDirectory()) {
099          searchAndValidate(exampleHomeDir);
100        else if (exampleHomeDir.isFile()
101          && exampleHomeDir.getName().endsWith(".xml")) {
102          validate(exampleHomeDir);
103        }
104        log("\nValidated "+count+" meta-data files.");
105      catch (Exception e) {
106        err("Error occurred:");
107        e.printStackTrace();
108      }
109    }
110 
111    private XmlObject parse(File f) {
112      MedicalRecordsDocument exDoc = null;
113      try {
114        exDoc = MedicalRecordsDocument.Factory.parse(f);
115      catch (Exception e) {
116        System.err.println("Exception occurred: "+e.getMessage());
117      }
118      return exDoc;
119    }
120 
121    public boolean validate(File xmlFilethrows Exception {
122      log("Validating: "+xmlFile);
123      return validate(parse(xmlFile));
124    }
125 
126    public boolean validate(XmlObject xmlObj) {
127      boolean isValid = false;
128      try {
129        // Create an XmlOptions instance and set the error listener.
130        XmlOptions validateOptions = new XmlOptions();
131        ArrayList<XmlError> errorList = new ArrayList<XmlError>();
132        validateOptions.setErrorListener(errorList);
133        // Validate the XML.
134        isValid = xmlObj.validate(validateOptions);
135 
136        // If the XML isn't valid, loop through the listener's contents,
137        // printing contained messages.
138        if (!isValid) {
139          System.out.println("!! Invalidate XML !!");
140          for (int i = 0; i < errorList.size(); i++) {
141            XmlError error = (XmlError)errorList.get(i);
142            System.out.println("\n");
143            System.out.println("Message: "+error.getMessage()+"\n");
144            System.out.println("Location of invalid XML: "+
145              error.getCursorLocation().xmlText()+"\n");
146          }
147        }
148      catch (Exception e) {
149        System.err.println("Exception occurred: "+e.getMessage());
150      }
151      count++;
152      return isValid;
153    }
154 
155    private boolean isNotEmpty(String str) { return !isEmpty(str)}
156    private boolean isEmpty(String str) {
157      return (str == null || str.equals(""));
158    }
159    protected void log(String str) { System.out.println(str)}
160    protected void err(String str) { System.err.println(str)}
161    protected void debug(String str) { if (verboselog(str)}
162 
163    public static void main(String args[]) throws Exception {
164      new examples.xml.xmlbean.PatientXMLValidator(args).run();
165    }
166  }