?? schematester.java
字號:
package org.jibx.schema;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.URL;import java.util.ArrayList;import java.util.Arrays;import java.util.Comparator;import java.util.Iterator;import java.util.Set;import org.eclipse.jdt.core.dom.AST;import org.jibx.binding.Loader;import org.jibx.binding.Utility;import org.jibx.binding.classes.BoundClass;import org.jibx.binding.classes.ClassCache;import org.jibx.binding.classes.ClassFile;import org.jibx.binding.classes.MungedClass;import org.jibx.binding.def.BindingDefinition;import org.jibx.extras.DocumentComparator;import org.jibx.runtime.BindingDirectory;import org.jibx.runtime.IBindingFactory;import org.jibx.runtime.IMarshallingContext;import org.jibx.runtime.IUnmarshallingContext;import org.jibx.runtime.JiBXException;import org.jibx.runtime.impl.UnmarshallingContext;import org.jibx.schema.codegen.ClassAssigner;import org.jibx.schema.codegen.NameConverter;import org.jibx.schema.codegen.PackageDirectory;import org.jibx.schema.codegen.PackageHolder;import org.jibx.schema.codegen.ReferenceCountMap;import org.jibx.schema.codegen.UsageFinder;import org.jibx.schema.elements.CommonTypeDefinition;import org.jibx.schema.elements.ElementElement;import org.jibx.schema.elements.SchemaBase;import org.jibx.schema.elements.SchemaElement;import org.jibx.schema.validation.PrevalidationVisitor;import org.jibx.schema.validation.RegistrationVisitor;import org.jibx.schema.validation.ValidationContext;import org.jibx.schema.validation.ValidationProblem;import org.jibx.schema.validation.ValidationVisitor;import org.jibx.util.InsertionOrderedSet;/** * Test class for working with a specified schema. */public class SchemaTester{ private static final String SCHEMA_CLASS = "org.jibx.schema.elements.SchemaElement"; private static final IBindingFactory m_bindingFactory; static { try { // set paths to be used for loading referenced classes URL[] urls = Loader.getClassPaths(); String[] paths = new String[urls.length]; for (int i = 0; i < urls.length; i++) { paths[i] = urls[i].getFile(); } ClassCache.setPaths(paths); ClassFile.setPaths(paths); // find the binding definition ClassLoader loader = SchemaTester.class.getClassLoader(); InputStream is = loader.getResourceAsStream("org/jibx/schema/binding.xml"); if (is == null) { throw new RuntimeException("Schema binding definition not found"); } // process the binding BoundClass.reset(); MungedClass.reset(); BindingDefinition.reset(); BindingDefinition def = Utility.loadBinding("binding.xml", "binding", is, null, false); def.generateCode(false); // output the modified class files MungedClass.fixChanges(true); // look up the mapped class and associated binding factory Class mclas = Class.forName(SCHEMA_CLASS); m_bindingFactory = BindingDirectory.getFactory(mclas); } catch (JiBXException e) { throw new RuntimeException("JiBXException: " + e.getMessage()); } catch (IOException e) { throw new RuntimeException("IOException: " + e.getMessage()); } catch (ClassNotFoundException e) { throw new RuntimeException("ClassNotFoundException: " + e.getMessage()); } } private static void delete(File file) { if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { delete(files[i]); } } file.delete(); } /** * Test a set of schemas. * * @param args * @throws Exception on error */ public static void main(String[] args) throws Exception { ValidationContext vctx = new ValidationContext(); File genroot = new File(args[0]); System.out.println("Generating to output directory " + genroot.getAbsolutePath()); if (genroot.exists()) { delete(genroot); } SchemaElement[] schemas = new SchemaElement[args.length-1]; for (int i = 1; i < args.length; i++) { // unmarshal document to construct schema structure IUnmarshallingContext uctx = m_bindingFactory.createUnmarshallingContext(); File file = new File(args[i]); uctx.setDocument(new FileInputStream(file), file.getAbsolutePath(), null); uctx.setUserContext(vctx); Object obj = uctx.unmarshalElement(); // list validation errors ArrayList probs = vctx.getProblems(); if (probs.size() > 0) { for (int j = 0; j < probs.size(); j++) { ValidationProblem prob = (ValidationProblem)probs.get(j); System.out.print(prob.getSeverity() >= ValidationProblem.ERROR_LEVEL ? "Error: " : "Warning: "); System.out.println(prob.getDescription()); } } else { // determine encoding of input document String enc = ((UnmarshallingContext)uctx).getInputEncoding(); if (enc == null) { enc = "UTF-8"; } // marshal root object back out to document in memory IMarshallingContext mctx = m_bindingFactory.createMarshallingContext(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); mctx.setIndent(2); mctx.marshalDocument(obj, enc, null, bos); // compare with original input document InputStreamReader brdr = new InputStreamReader (new ByteArrayInputStream(bos.toByteArray()), enc); InputStreamReader frdr = new InputStreamReader (new FileInputStream(args[i]), enc); DocumentComparator comp = new DocumentComparator(System.err); if (comp.compare(frdr, brdr)) { // report schema roundtripped successfully System.out.println("Roundtripped schema " + args[i]); // set resolver for use during schema processing SchemaElement schema = (SchemaElement)obj; URL url = new URL("file", "", file.getAbsolutePath()); schema.setResolver(new UrlResolver(url)); schemas[i-1] = (SchemaElement)obj; } else { // save file before returning failure try { File fout = new File("temp.xml"); fout.delete(); FileOutputStream fos = new FileOutputStream(fout); fos.write(bos.toByteArray()); fos.close(); } catch (IOException ex) { System.err.println("Error writing to temp.xml: " + ex.getMessage()); } } } } // validate the schemas and report any problems TreeWalker wlkr = new TreeWalker(vctx, vctx); System.out.println("** Beginning prevalidation **"); vctx.clearTraversed(); for (int i = 0; i < schemas.length; i++) { wlkr.walkSchema(schemas[i], new PrevalidationVisitor(vctx)); } System.out.println("** Beginning registration **"); vctx.clearTraversed(); for (int i = 0; i < schemas.length; i++) { wlkr.walkSchema(schemas[i], new RegistrationVisitor(vctx)); } System.out.println("** Beginning validation **"); vctx.clearTraversed(); for (int i = 0; i < schemas.length; i++) { wlkr.walkSchema(schemas[i], new ValidationVisitor(vctx)); } ArrayList probs = vctx.getProblems(); if (probs.size() > 0) { for (int j = 0; j < probs.size(); j++) { ValidationProblem prob = (ValidationProblem)probs.get(j); System.out.print(prob.getSeverity() >= ValidationProblem.ERROR_LEVEL ? "Error: " : "Warning: "); System.out.println(prob.getDescription()); } } // check usage of all schema elements System.out.println("** Beginning full usage counting **"); vctx.clearTraversed(); UsageFinder usage = new UsageFinder(); for (int i = 0; i < schemas.length; i++) { usage.countSchemaTree(schemas[i]); } // report reference counts for entire set of schemas ReferenceCountMap rcmap = usage.getUsageMap(); System.out.println("** Reference counts across all schemas **"); printReferenceCounts(rcmap); // check usage of closure from global definitions in top-level schema System.out.println("** Beginning subset closure usage counting **"); vctx.clearTraversed(); usage = new UsageFinder(); for (int i = 0; i < schemas.length; i++) { SchemaElement schema = schemas[i]; usage.setNameRegister(schema.getRegister()); usage.addReferenceClosure(schema.getTopLevelChildren()); } // report reference counts for schema subset rcmap = usage.getUsageMap(); System.out.println("** Reference counts from schema subset **"); printReferenceCounts(rcmap); // start with set of all global elements to drive class generation Set comps = new InsertionOrderedSet(); for (int i = 0; i < schemas.length; i++) { for (Iterator iter = schemas[i].getTopLevelChildren().iterator(); iter.hasNext();) { Object child = iter.next(); if (child instanceof ElementElement) { comps.add(child); } } } // add all multiple references to set for (Iterator iter = rcmap.iterator(); iter.hasNext();) { SchemaBase key = (SchemaBase)iter.next(); if (rcmap.getCount(key) > 1 && !(key instanceof CommonTypeDefinition && ((CommonTypeDefinition)key).isPredefinedType())) { comps.add(key); } } // assign class names for schema components, starting from set PackageDirectory pkgdir = new PackageDirectory(genroot, "org.opentravel.ota"); ClassAssigner assigner = new ClassAssigner(new NameConverter(), pkgdir); assigner.assign(rcmap, comps); // generate the classes in all packages AST ast = AST.newAST(AST.JLS3); ArrayList packs = pkgdir.getPackages(); for (int i = 0; i < packs.size(); i++) { PackageHolder pack = (PackageHolder)packs.get(i); pack.generate(ast); } } /** * Print ordered list of reference counts. * * @param rcmap */ private static void printReferenceCounts(ReferenceCountMap rcmap) { // get array of keys ordered by item name Object[] keys = rcmap.keyArray(); Arrays.sort(keys, new Comparator() { public int compare(Object arg0, Object arg1) { String name0 = ((INamed)arg0).getName(); String name1 = ((INamed)arg1).getName(); return name0.compareTo(name1); } }); // print the reference counts for (int i = 0; i < keys.length; i++) { SchemaBase key = (SchemaBase)keys[i]; System.out.println("Found " + rcmap.getCount(key) + " references to " + key.name() + " " + ((INamed)key).getName()); } }}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -