Example usage for org.dom4j VisitorSupport VisitorSupport

List of usage examples for org.dom4j VisitorSupport VisitorSupport

Introduction

In this page you can find the example usage for org.dom4j VisitorSupport VisitorSupport.

Prototype

public VisitorSupport() 

Source Link

Usage

From source file:com.taobao.android.builder.tools.manifest.ManifestFileUtils.java

License:Apache License

/**
 * xml//  www  . jav a2  s. c om
 *
 * @param document
 * @throws IOException
 * @throws DocumentException
 */
private static void removeComments(Document document) throws IOException, DocumentException {
    Visitor visitor = new VisitorSupport() {

        public void visit(Comment comment) {
            comment.setText(" ");
        }
    };
    document.accept(visitor);
}

From source file:io.mashin.oep.hpdl.XMLReadUtils.java

License:Open Source License

public static Node schemaVersionParentNode(Node node) {
    Node[] parentNode = new Node[1];
    node.accept(new VisitorSupport() {
        @Override/*from ww w . j  a va 2 s.c  o  m*/
        public void visit(Attribute node) {
            if (node.getName().equalsIgnoreCase(XMLUtils.SCHEMA_VERSION_TAG)) {
                parentNode[0] = node.getParent();
            }
        }
    });
    return parentNode[0];
}

From source file:net.sf.eclipsecs.core.config.ConfigurationReader.java

License:Open Source License

private static List<Module> getModules(final Document document) {

    final List<Module> modules = new ArrayList<Module>();

    document.accept(new VisitorSupport() {

        @Override/*w w w  . jav  a 2  s.c om*/
        public void visit(final Element node) {

            if (XMLTags.MODULE_TAG.equals(node.getName())) {

                final String name = node.attributeValue(XMLTags.NAME_TAG);

                final RuleMetadata metadata = MetadataFactory.getRuleMetadata(name);
                Module module = null;
                if (metadata != null) {
                    module = new Module(metadata, true);
                } else {
                    module = new Module(name);
                }

                addProperties(node, module);
                addMessages(node, module);
                addMetadata(node, module);

                // if the module has not metadata attached we create some
                // generic metadata
                if (module.getMetaData() == null) {
                    MetadataFactory.createGenericMetadata(module);
                }

                modules.add(module);
            }
        }
    });
    return modules;
}

From source file:org.codehaus.cargo.util.Dom4JXmlFileBuilder.java

License:Apache License

/**
 * @param element to traverse and change namespace of
 * @param parent - who to match namespaces with.
 *//* w  w  w. j a  v  a 2  s . c o  m*/
private void setNamespaceOfElementToTheSameAsParent(Element element, Element parent) {
    final Namespace namespaceOfParent = parent.getNamespace();
    element.accept(new VisitorSupport() {
        @Override
        public void visit(Element node) {
            QName nameOfElementWithCorrectNamespace = new QName(node.getName(), namespaceOfParent);
            node.setQName(nameOfElementWithCorrectNamespace);
        }
    });
}

From source file:org.dentaku.gentaku.tools.cgen.plugin.GenGenPlugin.java

License:Apache License

public void start() {
    System.out.println("Running " + getClass().getName());
    Collection metadata = mp.getJMIMetadata();
    for (Iterator it = metadata.iterator(); it.hasNext();) {
        Object o = (Object) it.next();
        if (o instanceof ModelElementImpl
                && ((ModelElementImpl) o).getStereotypeNames().contains("GenGenPackage")) {
            ModelElementImpl pkg = (ModelElementImpl) o;
            try {
                // get the two documents out of the model
                Document mappingDoc = DocumentHelper.parseText(
                        (String) pkg.getTaggedValue("gengen.mapping").getDataValue().iterator().next());
                final Document xsdDoc = DocumentHelper
                        .parseText((String) pkg.getTaggedValue("gengen.XSD").getDataValue().iterator().next());

                Collection generators = mappingDoc.selectNodes("/mapping/generator");
                final Map generatorMap = new HashMap();
                for (Iterator getIterator = generators.iterator(); getIterator.hasNext();) {
                    Element element = (Element) getIterator.next();
                    try {
                        Generator g = (Generator) Class.forName(element.attributeValue("canonicalName"))
                                .newInstance();
                        generatorMap.put(element.attributeValue("name"), g);
                    } catch (InstantiationException e) {
                        throw new RuntimeException(e);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    }//from w  w  w.  j a v  a2s.c om

                }

                // annotate XSD with mapping document
                mappingDoc.accept(new VisitorSupport() {
                    public void visit(Element node) {
                        String path = node.attributeValue("path");
                        if (path != null) {
                            LocalDefaultElement xsdVisit = (LocalDefaultElement) Util.selectSingleNode(xsdDoc,
                                    path);
                            xsdVisit.setAnnotation((LocalDefaultElement) node);
                        }
                        String key = node.attributeValue("ref");
                        if (node.getName().equals("generator") && key != null) {
                            if (generatorMap.keySet().contains(key)) {
                                ((LocalDefaultElement) node).setGenerator((Generator) generatorMap.get(key));
                            } else {
                                throw new RuntimeException(
                                        "generator key '" + key + "' not created or not found");
                            }
                        }
                    }
                });

                // create a new output document
                Document outputDocument = DocumentHelper.createDocument();

                // find element root of mapping document
                Element rootElementCandidate = (Element) Util.selectSingleNode(mappingDoc,
                        "/mapping/element[@location='root']");
                if (rootElementCandidate == null) {
                    throw new RuntimeException("could not find root element of XSD");
                }
                String rootPath = rootElementCandidate.attributeValue("path");
                LocalDefaultElement rootElement = (LocalDefaultElement) Util.selectSingleNode(xsdDoc, rootPath);

                // get the model root (there can be only one...)
                ModelImpl m = Utils.getModelRoot(mp.getModel());

                // pregenerate
                for (Iterator genIterator = generatorMap.values().iterator(); genIterator.hasNext();) {
                    Generator generator = (Generator) genIterator.next();
                    generator.preProcessModel(m);
                }

                // create a visitor and visit the document
                PluginOutputVisitor visitor = new PluginOutputVisitor(xsdDoc, mp.getModel());
                rootElement.accept(visitor, outputDocument, null, null);

                // postegenerate
                for (Iterator genIterator = generatorMap.values().iterator(); genIterator.hasNext();) {
                    Generator generator = (Generator) genIterator.next();
                    generator.postProcessModel(m);
                }

                // generate the output document
                File outputFile;
                Writer destination;
                if (getDestdir() != null) {
                    String dirPath = getDestdir();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                    outputFile = new File(dir, getDestinationfilename());
                    destination = new FileWriter(outputFile);
                } else {
                    outputFile = File.createTempFile("GenGen", ".xml");
                    outputFile.deleteOnExit();
                    destination = new OutputStreamWriter(System.out);
                }

                if (outputDocument.getRootElement() != null) {
                    generateOutput(outputFile, outputDocument, xsdDoc, destination, generatorMap);
                } else {
                    System.out.println("WARNING: no output generated, do you have root tags defined?");
                }

            } catch (DocumentException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (SAXException e) {
                throw new RuntimeException(e);
            } catch (RepositoryException e) {
                throw new RuntimeException(e);
            } catch (GenerationException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:org.dentaku.gentaku.tools.cgen.xmi.XMIGenTask.java

License:Apache License

public void execute() throws BuildException {
    System.out.println("Running " + getClass().getName());
    SAXReader reader = new SAXReader();

    Document outputDocument = DocumentHelper.createDocument();
    Branch content = createXMIDocument(outputDocument);

    Element model = createIdentifiedEmptyElement(content, "Model").addAttribute("name", "foo");

    // add the XSD and mapping documents as tagged values into the package
    Element gengenPackage = createPackageHierarchy("org.dentaku.gentaku.gengen", model);
    Element gengenOwnedElement = createOwnedElement(gengenPackage);

    // create the tag group
    Element groupStereotype = createIdentifiedEmptyElement(gengenOwnedElement, "Stereotype")
            .addAttribute("name", "tagGroup");
    groupStereotype.addElement("UML:Stereotype.baseClass", "omg.org/UML/1.4").setText("TagDefinition");
    Element groupTagdef = createTaggedValueDefinition(gengenOwnedElement, "Group", null,
            new String[] { "TagDefinition" }, "String", false);
    groupTagdef.addAttribute("stereotype", groupStereotype.attributeValue("xmi.id"));

    // create the gengen stereotype marker
    Element gengenStereotype = createIdentifiedEmptyElement(gengenOwnedElement, "Stereotype")
            .addAttribute("name", "GenGenPackage");
    gengenStereotype.addElement("UML:Stereotype.baseClass", "omg.org/UML/1.4").setText("Package");

    Element xsdTaggedValueDefinition = createTaggedValueDefinition(gengenOwnedElement, "gengen.XSD", null,
            new String[] { "Package" }, "String", false);
    Element mappingTaggedValueDefinition = createTaggedValueDefinition(gengenOwnedElement, "gengen.mapping",
            null, new String[] { "Package" }, "String", false);

    try {// www . j a v a 2  s .c  o  m
        for (Iterator it = antSpecifiedModules.iterator(); it.hasNext();) {
            visited.clear();
            Module module = (Module) it.next();
            if (module.getMapping() == null || module.getSchema() == null) {
                throw new BuildException(
                        "you must provide both a mapping and a schema argument to the XMIGenTask");
            }
            Document mappingDoc = reader.read(new File(module.getMapping()));
            final Document schemaDoc = reader.read(new File(module.getSchema()));

            // annotate XSD with mapping document
            mappingDoc.accept(new VisitorSupport() {
                public void visit(Element node) {
                    String path = node.attributeValue("path");
                    if (path != null) {
                        LocalDefaultElement xsdVisit = (LocalDefaultElement) Util.selectSingleNode(schemaDoc,
                                path);
                        xsdVisit.setAnnotation((LocalDefaultElement) node);
                    }
                }
            });

            String rootPath = ((Element) Util.selectSingleNode(mappingDoc,
                    "/mapping/element[@location='root']")).attributeValue("path");
            LocalDefaultElement rootNode = (LocalDefaultElement) Util.selectSingleNode(schemaDoc, rootPath);

            // create the location sets
            createLocationSets(rootNode, "root", new Stack());

            buildDocument(model, schemaDoc, mappingDoc, rootNode, groupTagdef, gengenStereotype,
                    xsdTaggedValueDefinition, mappingTaggedValueDefinition);
        }

        if (destdir == null)
            destdir = "./";
        File file = new File(destdir);
        file.mkdirs();
        writeFile(outputDocument, new File(file, filename));
    } catch (DocumentException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.dom4j.samples.CountDemo.java

License:Open Source License

protected void process(Document document) throws Exception {
    numCharacters = 0;/* w  w  w.  ja  v a 2  s . co m*/
    numComments = 0;
    numElements = 0;
    numAttributes = 0;
    numProcessingInstructions = 0;

    Visitor visitor = new VisitorSupport() {

        public void visit(Element node) {
            ++numElements;
        }

        public void visit(Attribute node) {
            ++numAttributes;
        }

        public void visit(Comment node) {
            ++numComments;
        }

        public void visit(ProcessingInstruction node) {
            ++numProcessingInstructions;
        }

        public void visit(Text node) {
            String text = node.getText();
            if (text != null) {
                numCharacters += text.length();
            }
        }
    };

    println("Document: " + document.getName() + " has the following");
    println("Elements\tAttributes\tComments\tPIs\tCharacters");

    document.accept(visitor);

    println(numElements + "\t\t" + numAttributes + "\t\t" + numComments + "\t\t" + numProcessingInstructions
            + "\t" + numCharacters);
}

From source file:org.dom4j.samples.VisitorDemo.java

License:Open Source License

protected void process(Document document) throws Exception {
    Visitor visitor = new VisitorSupport() {

        public void visit(Document document) {
            println(document.toString());
        }/*w w w  .ja  v a2  s . c  o  m*/

        public void visit(DocumentType documentType) {
            println(documentType.toString());
        }

        public void visit(Element node) {
            println(node.toString());
        }

        public void visit(Attribute node) {
            println(node.toString());
        }

        public void visit(CDATA node) {
            println(node.toString());
        }

        public void visit(Comment node) {
            println(node.toString());
        }

        public void visit(Entity node) {
            println(node.toString());
        }

        public void visit(Namespace node) {
            println(node.toString());
        }

        public void visit(ProcessingInstruction node) {
            println(node.toString());
        }

        public void visit(Text node) {
            println(node.toString());
        }
    };

    document.accept(visitor);
}

From source file:org.guzz.builder.HbmXMLBuilder.java

License:Apache License

public static POJOBasedObjectMapping parseHbmStream(final GuzzContextImpl gf, String dbGroupName,
        BusinessValidChecker checker, String businessName, Class overridedDomainClass, Class interpreterClass,
        InputStream is) throws DocumentException, IOException, SAXException, ClassNotFoundException {

    SAXReader reader = null;//from  w w  w  . j av a2  s . co m
    Document document = null;

    reader = new SAXReader();
    reader.setValidation(false);
    // http://apache.org/xml/features/nonvalidating/load-external-dtd"  
    reader.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);

    document = reader.read(is);
    final Element root = document.getRootElement();

    if (StringUtil.isEmpty(dbGroupName)) {
        dbGroupName = getDomainClassDbGroup(root);
    }
    if (StringUtil.isEmpty(dbGroupName)) {
        dbGroupName = "default";
    }

    final DBGroup dbGroup = gf.getDBGroup(dbGroupName);

    final SimpleTable st = new SimpleTable(dbGroup.getDialect());
    final POJOBasedObjectMapping map = new POJOBasedObjectMapping(gf, dbGroup, st);

    if (overridedDomainClass == null) {//hbm?className
        String m_class = HbmXMLBuilder.getDomainClassName(root);

        overridedDomainClass = ClassUtil.getClass(m_class);
    }

    if (checker != null && !checker.shouldParse(overridedDomainClass)) {
        return null;
    }

    if (StringUtil.isEmpty(businessName)) {
        businessName = getDomainClassBusinessName(root);
    }

    final Business business = gf.instanceNewGhost(businessName, dbGroup.getGroupName(), interpreterClass,
            overridedDomainClass);
    if (business.getInterpret() == null) {
        throw new GuzzException("cann't create new instance of business: " + business.getName());
    }

    business.setTable(st);
    business.setMapping(map);

    //?business??
    if (business.getName() != null) {
        st.setBusinessName(business.getName());
    } else {
        st.setBusinessName(business.getDomainClass().getName());
    }

    //properties defined.
    final LinkedList props = new LinkedList();

    Visitor visitor = new VisitorSupport() {

        private String packageName;

        public void visit(Element e) {

            //package
            if ("hibernate-mapping".equalsIgnoreCase(e.getName())
                    || "guzz-mapping".equalsIgnoreCase(e.getName())) {
                this.packageName = e.attributeValue("package");

            } else if ("class".equalsIgnoreCase(e.getName())) {
                String className = e.attributeValue("name");
                String tableName = e.attributeValue("table");
                String shadow = e.attributeValue("shadow");
                boolean dynamicUpdate = StringUtil.toBoolean(e.attributeValue("dynamic-update"), false);

                if (StringUtil.notEmpty(this.packageName)) {
                    className = this.packageName + "." + className;
                }

                //business????hbml.xml?class namebusinessclass
                Class cls = business.getDomainClass();
                if (cls == null) { //?business?domainClassName
                    cls = ClassUtil.getClass(className);
                }

                Assert.assertNotNull(cls, "invalid class name");
                Assert.assertNotEmpty(tableName, "invalid table name");

                JavaBeanWrapper configBeanWrapper = BeanWrapper.createPOJOWrapper(cls);
                business.setDomainClass(cls);
                business.setConfiguredBeanWrapper(configBeanWrapper);

                map.setBusiness(business);

                //shadow?tableName?
                if (StringUtil.notEmpty(shadow)) {
                    ShadowTableView sv = (ShadowTableView) BeanCreator.newBeanInstance(shadow);
                    sv.setConfiguredTableName(tableName);

                    //CustomTableViewShadowTableView
                    if (sv instanceof CustomTableView) {
                        CustomTableView ctv = (CustomTableView) sv;
                        ctv.setConfiguredObjectMapping(map);

                        st.setCustomTableView(ctv);
                    }

                    st.setShadowTableView(sv);
                    gf.registerShadowTableView(sv);
                }

                //TODO: ???
                st.setTableName(tableName);
                st.setDynamicUpdate(dynamicUpdate);

            } else if ("id".equalsIgnoreCase(e.getName())) {
                String name = e.attributeValue("name");
                String type = e.attributeValue("type");
                String column = null;

                Element columnE = (Element) e.selectSingleNode("column");
                if (columnE != null) {
                    column = columnE.attributeValue("name");
                }

                if (StringUtil.isEmpty(column)) {
                    column = e.attributeValue("column");
                }

                if (StringUtil.isEmpty(column)) {
                    column = name;
                }

                props.addLast(name);

                TableColumn col = ObjectMappingUtil.createTableColumn(gf, map, name, column, type, null);

                st.addPKColumn(col);

            } else if ("version".equalsIgnoreCase(e.getName())) {
                //see: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html 5.1.9. Version (optional)
                //TODO: annotation?version?

                String name = e.attributeValue("name");
                String type = e.attributeValue("type");
                boolean insertIt = StringUtil.toBoolean(e.attributeValue("insert"), true);
                String column = null;

                Element columnE = (Element) e.selectSingleNode("column");
                if (columnE != null) {
                    column = columnE.attributeValue("name");
                }

                if (StringUtil.isEmpty(column)) {
                    column = e.attributeValue("column");
                }

                if (StringUtil.isEmpty(column)) {
                    column = name;
                }

                props.addLast(name);

                TableColumn col = ObjectMappingUtil.createTableColumn(gf, map, name, column, type, null);
                col.setAllowInsert(insertIt);

                st.addVersionColumn(col);

            } else if ("property".equalsIgnoreCase(e.getName())) {
                String name = e.attributeValue("name");
                String type = e.attributeValue("type");
                String nullValue = e.attributeValue("null");
                String lazy = e.attributeValue("lazy");
                String loader = e.attributeValue("loader");

                boolean insertIt = StringUtil.toBoolean(e.attributeValue("insert"), true);
                boolean updateIt = StringUtil.toBoolean(e.attributeValue("update"), true);

                String column = null;

                Element columnE = (Element) e.selectSingleNode("column");
                if (columnE != null) {
                    column = columnE.attributeValue("name");
                }

                if (StringUtil.isEmpty(column)) {
                    column = e.attributeValue("column");
                }

                if (StringUtil.isEmpty(column)) {
                    column = name;
                }

                props.addLast(name);

                TableColumn col = ObjectMappingUtil.createTableColumn(gf, map, name, column, type, loader);
                col.setNullValue(nullValue);
                col.setAllowInsert(insertIt);
                col.setAllowUpdate(updateIt);
                col.setLazy("true".equalsIgnoreCase(lazy));

                st.addColumn(col);
            }
        }
    };

    root.accept(visitor);

    //?generator
    //?generator?
    List generator = root.selectNodes("//class/id/generator");
    if (generator.size() != 1) {
        throw new GuzzException("id generator is not found for business: " + business);
    }

    Element ge = (Element) generator.get(0);

    String m_clsName = ge.attributeValue("class");

    if ("native".equalsIgnoreCase(m_clsName)) { //nativegeneratordialect?
        m_clsName = dbGroup.getDialect().getNativeIDGenerator();
    }

    String realClassName = (String) IdentifierGeneratorFactory.getGeneratorClass(m_clsName);
    if (realClassName == null) {
        realClassName = m_clsName;
    }

    IdentifierGenerator ig = (IdentifierGenerator) BeanCreator.newBeanInstance(realClassName);

    //?generator??      
    List m_params = ge.selectNodes("param");
    Properties p = new Properties();
    for (int i = 0; i < m_params.size(); i++) {
        Element mp = (Element) m_params.get(i);
        p.put(mp.attributeValue("name"), mp.getTextTrim());
    }

    if (ig instanceof Configurable) {
        ((Configurable) ig).configure(dbGroup.getDialect(), map, p);
    }

    //register callback for GuzzContext's full starting.
    if (ig instanceof GuzzContextAware) {
        gf.registerContextStartedAware((GuzzContextAware) ig);
    }

    st.setIdentifierGenerator(ig);

    return map;
}

From source file:org.nuxeo.apidoc.documentation.XMLContributionParser.java

License:Apache License

protected static ContributionItem parseContrib(Element element) {

    final ContributionItem fragment = new ContributionItem();
    fragment.tagName = element.getName();

    fragment.nameOrId = element.attributeValue("name");
    if (fragment.nameOrId == null) {
        fragment.nameOrId = element.attributeValue("id");
    }/*from www .  ja v  a  2 s. c  o m*/

    Visitor docExtractor = new VisitorSupport() {
        @Override
        public void visit(Element node) {
            if ("documentation".equalsIgnoreCase(node.getName())) {
                fragment.documentation = getNodeAsString(node);
            } else if ("description".equalsIgnoreCase(node.getName())) {
                fragment.documentation = getNodeAsString(node);
            } else {
                super.visit(node);
            }
        }
    };
    element.accept(docExtractor);

    fragment.xml = element.asXML();

    return fragment;
}