Example usage for org.dom4j Element content

List of usage examples for org.dom4j Element content

Introduction

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

Prototype

List<Node> content();

Source Link

Document

Returns the content nodes of this branch as a backed List so that the content of this branch may be modified directly using the List interface.

Usage

From source file:org.firesoa.common.jxpath.model.dom4j.Dom4JNodePointer.java

License:Open Source License

@Override
public void setValue(Object value) {
    if (value == null)
        value = "";//null??
    if ((node instanceof org.dom4j.CharacterData || node instanceof Attribute || node instanceof DocumentType
            || node instanceof Entity || node instanceof ProcessingInstruction)) {
        String string = (String) TypeUtils.convert(value, String.class);
        if (string != null && !string.equals("")) {
            ((Node) node).setText(string);
        } else {/*from  w w  w .  j a  v a  2s  .  co  m*/
            ((Node) node).getParent().remove((Node) node);
        }
    } else if (node instanceof Document) {
        Document theOriginalDoc = (Document) node;
        Element theOrigialRoot = theOriginalDoc.getRootElement();

        if (value instanceof Document) {//?document

            Document valueDoc = (Document) value;
            Element valueRoot = valueDoc.getRootElement();

            if (theOrigialRoot == null || valueRoot == null
                    || theOrigialRoot.getQName().equals(valueRoot.getQName())) {

                theOriginalDoc.clearContent();

                List content = valueDoc.content();
                if (content != null) {
                    for (int i = 0; i < content.size(); i++) {
                        Node dom4jNode = (Node) content.get(i);
                        Node newDom4jNode = (Node) dom4jNode.clone();
                        theOriginalDoc.add(newDom4jNode);
                    }
                }
            } else {
                throw new RuntimeException(
                        "Can NOT assign " + valueRoot.getQName() + " to " + theOrigialRoot.getQName());

            }

        } else if (value instanceof Element) {
            Element valueElem = (Element) value;
            if (valueElem.getQName().equals(theOrigialRoot.getQName())) {
                theOriginalDoc.clearContent();
                Element newValueElem = (Element) valueElem.clone();
                theOriginalDoc.setRootElement(newValueElem);
            } else {
                throw new RuntimeException(
                        "Can NOT assign " + valueElem.getQName() + " to " + theOrigialRoot.getQName());
            }
        } else {
            throw new RuntimeException("Can NOT assign " + value + " to " + theOrigialRoot.getQName());

        }
        //         else if (value instanceof Comment){
        //            Comment cmmt = (Comment)((Comment)value).clone();
        //            theOriginalDoc.add(cmmt);
        //            
        //         }else if (value instanceof ProcessingInstruction){
        //            ProcessingInstruction instru = (ProcessingInstruction)((ProcessingInstruction)value).clone();
        //            theOriginalDoc.add(instru);
        //         }

    } else if (node instanceof Element) {
        Element originalElem = ((Element) node);

        if (value != null && value instanceof Element) {
            Element valueElm = (Element) value;
            if (originalElem.getQName().equals(valueElm.getQName())) {
                originalElem.clearContent();
                List content = valueElm.content();
                if (content != null) {
                    for (int i = 0; i < content.size(); i++) {
                        Node dom4jNode = (Node) content.get(i);
                        Node newDom4jNode = (Node) dom4jNode.clone();
                        originalElem.add(newDom4jNode);
                    }
                }
            } else {
                throw new RuntimeException(
                        "Can NOT assign " + valueElm.getQName() + " to " + originalElem.getQName());
            }

        } else if (value != null && value instanceof Text) {
            originalElem.clearContent();
            Text txt = (Text) ((Text) value).clone();
            originalElem.add(txt);
        } else if (value != null && value instanceof CDATA) {
            originalElem.clearContent();
            CDATA cdata = (CDATA) ((CDATA) value).clone();
            originalElem.add(cdata);
        } else if (value != null && value instanceof java.util.Date) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = format.format((java.util.Date) value);
            originalElem.clearContent();
            originalElem.addText(dateStr);
        } else {
            String string = (String) TypeUtils.convert(value, String.class);
            originalElem.clearContent();
            originalElem.addText(string);
        }

    }

}

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

License:Apache License

protected Document loadFullConfigFile(Resource resource, String encoding)
        throws DocumentException, IOException, SAXException {
    SAXReader reader = null;// w  w w .  j a  v  a2 s  .  c  o 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);

    InputStreamReader isr = new InputStreamReader(resource.getInputStream(), encoding);

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

    List list = document.selectNodes("//import");

    for (int i = 0; i < list.size(); i++) {
        Element n = (Element) list.get(i);

        String file = n.attribute("resource").getValue();

        //load included xml file.
        FileResource fr = new FileResource(resource, file);
        Document includedDoc = null;

        try {
            includedDoc = loadFullConfigFile(fr, encoding);
        } finally {
            CloseUtil.close(fr);
        }

        List content = root.content();
        int indexOfPos = content.indexOf(n);

        content.remove(indexOfPos);

        //appends included docs
        Element ie = includedDoc.getRootElement();
        List ie_children = ie.content();

        for (int k = ie_children.size() - 1; k >= 0; k--) {
            content.add(indexOfPos, ie_children.get(k));
        }
    }

    return document;
}

From source file:org.hibernate.eclipse.launch.CodeGenXMLFactory.java

License:Open Source License

@SuppressWarnings("unchecked")
protected Element createRoot() {
    ExporterAttributes attributes = null;
    try {/*from   w ww  .  j a  v a  2 s .  c  o  m*/
        attributes = new ExporterAttributes(lc);
    } catch (CoreException e) {
        // ignore
    }
    if (attributes == null) {
        return null;
    }
    Properties props = new Properties();
    if (attributes.isReverseEngineer()) {
        props.setProperty(ConfigurationXMLStrings.ISREVENG, Boolean.toString(attributes.isReverseEngineer()));
        props.setProperty(ConfigurationXMLStrings.PACKAGENAME, attributes.getPackageName());
        props.setProperty(ConfigurationXMLStrings.PREFERBASICCOMPOSITEIDS,
                Boolean.toString(attributes.isPreferBasicCompositeIds()));
        props.setProperty(ConfigurationXMLStrings.DETECTMANYTOMANY,
                Boolean.toString(attributes.detectManyToMany()));
        props.setProperty(ConfigurationXMLStrings.DETECTONTTOONE,
                Boolean.toString(attributes.detectOneToOne()));
        props.setProperty(ConfigurationXMLStrings.DETECTOPTIMISTICLOCK,
                Boolean.toString(attributes.detectOptimisticLock()));
        props.setProperty(ConfigurationXMLStrings.REVERSESTRATEGY, attributes.getRevengStrategy());
        String revEngFile = getResLocation(attributes.getRevengSettings());
        props.setProperty(ConfigurationXMLStrings.REVENGFILE, revEngFile);
    }
    //
    final IPath pathPlace2Generate = isEmpty(place2Generate) ? null : new Path(getResLocation(place2Generate));
    final IPath pathWorkspacePath = isEmpty(workspacePath) ? null : new Path(getResLocation(workspacePath));
    //
    String consoleConfigName = attributes.getConsoleConfigurationName();
    ConsoleConfigurationPreferences consoleConfigPrefs = getConsoleConfigPreferences(consoleConfigName);
    final ConfigurationXMLFactory configurationXMLFactory = new ConfigurationXMLFactory(consoleConfigPrefs,
            props);
    configurationXMLFactory.setPlace2Generate(pathPlace2Generate);
    configurationXMLFactory.setWorkspacePath(pathWorkspacePath);
    Element rootConsoleConfig = configurationXMLFactory.createRoot();
    //
    String defaultTargetName = "hibernateAntCodeGeneration"; //$NON-NLS-1$
    Element el, root = DocumentFactory.getInstance().createElement(CodeGenerationStrings.PROJECT);
    root.addAttribute(CodeGenerationStrings.NAME, "CodeGen"); //$NON-NLS-1$
    root.addAttribute(CodeGenerationStrings.DEFAULT, defaultTargetName);
    //
    if (!isEmpty(place2Generate)) {
        el = root.addElement(CodeGenerationStrings.PROPERTY);
        el.addAttribute(CodeGenerationStrings.NAME, varCurrentDir);
        el.addAttribute(CodeGenerationStrings.LOCATION, getPlace2GenerateUID());
    }
    if (!isEmpty(workspacePath)) {
        el = root.addElement(CodeGenerationStrings.PROPERTY);
        el.addAttribute(CodeGenerationStrings.NAME, varWorkspaceDir);
        el.addAttribute(CodeGenerationStrings.LOCATION, getWorkspacePathUID());
    }
    //
    String location = getResLocation(attributes.getOutputPath());
    location = ConfigurationXMLFactory.makePathRelative(location, pathPlace2Generate, pathWorkspacePath);
    el = root.addElement(CodeGenerationStrings.PROPERTY);
    el.addAttribute(CodeGenerationStrings.NAME, varBuildDir);
    el.addAttribute(CodeGenerationStrings.LOCATION, location);
    //
    String hibernatePropFile = null;
    String generateHibernatePropeties = null;
    String connProfileName = consoleConfigPrefs == null ? null : consoleConfigPrefs.getConnectionProfileName();
    IConnectionProfile profile = getConnectionProfile(connProfileName);
    boolean bPropFile = profile != null;
    // update property with fake tm
    Properties propsTmp = null;
    String hibernateVersion = consoleConfigPrefs == null ? "3.5" : consoleConfigPrefs.getHibernateVersion();
    IService service = ServiceLookup.findService(hibernateVersion);
    IEnvironment environment = service.getEnvironment();
    if (consoleConfigPrefs != null && consoleConfigPrefs.getPropertyFile() != null) {
        propsTmp = consoleConfigPrefs.getProperties();
        String tmStrategy = propsTmp.getProperty(environment.getTransactionManagerStrategy());
        if (tmStrategy != null && StringHelper.isEmpty(tmStrategy)) {
            propsTmp.setProperty(environment.getTransactionManagerStrategy(),
                    ConfigurationFactory.FAKE_TM_LOOKUP);
            bPropFile = true;
        }
    }
    if (bPropFile) {
        Set<String> specialProps = new TreeSet<String>();
        specialProps.add(environment.getDriver());
        specialProps.add(environment.getURL());
        specialProps.add(environment.getUser());
        specialProps.add(environment.getPass());
        specialProps.add(environment.getDialect());
        //
        if (propsTmp == null) {
            propsTmp = new Properties();
        }
        StringBuilder propFileContent = new StringBuilder();
        String driverClass = getDriverClass(connProfileName);
        if (profile != null) {
            final Properties cpProperties = profile.getProperties(profile.getProviderId());
            //
            String url = cpProperties.getProperty(IJDBCDriverDefinitionConstants.URL_PROP_ID);
            //
            String user = cpProperties.getProperty(IJDBCDriverDefinitionConstants.USERNAME_PROP_ID);
            //
            String pass = cpProperties.getProperty(IJDBCDriverDefinitionConstants.PASSWORD_PROP_ID);
            //
            String dialectName = consoleConfigPrefs.getDialectName();
            //
            propsTmp.setProperty(environment.getDriver(), driverClass);
            propsTmp.setProperty(environment.getURL(), url);
            propsTmp.setProperty(environment.getUser(), user);
            propsTmp.setProperty(environment.getPass(), pass);
            if (StringHelper.isNotEmpty(dialectName)) {
                propsTmp.setProperty(environment.getDialect(), dialectName);
            }
        }
        // output keys in sort order
        Object[] keys = propsTmp.keySet().toArray();
        Arrays.sort(keys);
        //
        if (externalPropFile) {
            for (Object obj : keys) {
                addIntoPropFileContent(propFileContent, obj.toString(), propsTmp.getProperty(obj.toString()));
            }
        } else {
            for (Object obj : keys) {
                if (specialProps.contains(obj)) {
                    el = root.addElement(CodeGenerationStrings.PROPERTY);
                    el.addAttribute(CodeGenerationStrings.NAME, obj.toString());
                    el.addAttribute(CodeGenerationStrings.VALUE, propsTmp.getProperty(obj.toString()));
                    addIntoPropFileContent(propFileContent, obj.toString());
                } else {
                    addIntoPropFileContent(propFileContent, obj.toString(),
                            propsTmp.getProperty(obj.toString()));
                }
            }
        }
        if (externalPropFile) {
            hibernatePropFile = externalPropFileName;
        } else {
            hibernatePropFile = "hibernatePropFile"; //$NON-NLS-1$
            el = root.addElement(CodeGenerationStrings.PROPERTY);
            el.addAttribute(CodeGenerationStrings.NAME, hibernatePropFile);
            el.addAttribute(CodeGenerationStrings.VALUE,
                    "${java.io.tmpdir}${ant.project.name}-hibernate.properties"); //$NON-NLS-1$
            //
            generateHibernatePropeties = "generateHibernatePropeties"; //$NON-NLS-1$
            Element target = root.addElement(CodeGenerationStrings.TARGET);
            target.addAttribute(CodeGenerationStrings.NAME, generateHibernatePropeties);
            //
            hibernatePropFile = getVar(hibernatePropFile);
            Element echo = target.addElement(CodeGenerationStrings.ECHO);
            echo.addAttribute(CodeGenerationStrings.FILE, hibernatePropFile);
            echo.addText(getPropFileContentStubUID());
        }
        propFileContentPreSave = propFileContent.toString().trim();
    }
    // all jars from libraries should be here
    String toolslibID = "toolslib"; //$NON-NLS-1$
    Element toolslib = root.addElement(CodeGenerationStrings.PATH);
    toolslib.addAttribute(CodeGenerationStrings.ID, toolslibID);
    final URL[] customClassPathURLs = PreferencesClassPathUtils.getCustomClassPathURLs(consoleConfigPrefs);
    for (int i = 0; i < customClassPathURLs.length; i++) {
        if (customClassPathURLs[i] == null) {
            continue;
        }
        // what is right here: CodeGenerationStrings.PATH or CodeGenerationStrings.PATHELEMENT?
        // http://www.redhat.com/docs/en-US/JBoss_Developer_Studio/en/hibernatetools/html/ant.html
        // use CodeGenerationStrings.PATH - so may be error in documentation?
        Element pathItem = toolslib.addElement(CodeGenerationStrings.PATH);
        //Element pathItem = toolslib.addElement(CodeGenerationStrings.PATHELEMENT);
        String strPathItem = customClassPathURLs[i].getPath();
        try {
            strPathItem = (new java.io.File(customClassPathURLs[i].toURI())).getPath();
        } catch (URISyntaxException e) {
            // ignore
        }
        strPathItem = new Path(strPathItem).toString();
        strPathItem = ConfigurationXMLFactory.makePathRelative(strPathItem, pathPlace2Generate,
                pathWorkspacePath);
        pathItem.addAttribute(CodeGenerationStrings.LOCATION, strPathItem);
    }
    //
    Element target = root.addElement(CodeGenerationStrings.TARGET);
    target.addAttribute(CodeGenerationStrings.NAME, defaultTargetName);
    if (!isEmpty(generateHibernatePropeties)) {
        target.addAttribute(CodeGenerationStrings.DEPENDS, generateHibernatePropeties);
    }
    //
    Element taskdef = target.addElement(CodeGenerationStrings.TASKDEF);
    taskdef.addAttribute(CodeGenerationStrings.NAME, CodeGenerationStrings.HIBERNATETOOL);
    taskdef.addAttribute(CodeGenerationStrings.CLASSNAME, "org.hibernate.tool.ant.HibernateToolTask"); //$NON-NLS-1$
    taskdef.addAttribute(CodeGenerationStrings.CLASSPATHREF, toolslibID);
    //
    Element hibernatetool = target.addElement(CodeGenerationStrings.HIBERNATETOOL);
    hibernatetool.addAttribute(CodeGenerationStrings.DESTDIR, getVar(varBuildDir));
    if (attributes.isUseOwnTemplates()) {
        String templatePath = getResLocation(attributes.getTemplatePath());
        hibernatetool.addAttribute(CodeGenerationStrings.TEMPLATEPATH, templatePath);
    }
    if (rootConsoleConfig != null) {
        if (StringHelper.isNotEmpty(hibernatePropFile)) {
            rootConsoleConfig.addAttribute(ConfigurationXMLStrings.PROPERTYFILE, hibernatePropFile);
        }
        // add hibernate console configuration
        hibernatetool.content().add(rootConsoleConfig);
    }
    //
    // the path there are user classes
    Element classpath = hibernatetool.addElement(CodeGenerationStrings.CLASSPATH);
    Element path = classpath.addElement(CodeGenerationStrings.PATH);
    path.addAttribute(CodeGenerationStrings.LOCATION, getVar(varBuildDir));
    //
    Map<String, Map<String, AttributeDescription>> exportersDescr = ExportersXMLAttributeDescription
            .getExportersDescription();
    Map<String, Set<String>> exportersSetSubTags = ExportersXMLAttributeDescription.getExportersSetSubTags();
    //
    Properties globalProps = new Properties();
    // obligatory global properties
    globalProps.put(CodeGenerationStrings.EJB3, "" + attributes.isEJB3Enabled()); //$NON-NLS-1$
    globalProps.put(CodeGenerationStrings.JDK5, "" + attributes.isJDK5Enabled()); //$NON-NLS-1$
    List<ExporterFactory> exporterFactories = attributes.getExporterFactories();
    for (Iterator<ExporterFactory> iter = exporterFactories.iterator(); iter.hasNext();) {
        ExporterFactory ef = iter.next();
        if (!ef.isEnabled(lc)) {
            continue;
        }
        //Map<String, ExporterProperty> defExpProps = ef.getDefaultExporterProperties();
        //String expId = ef.getId();
        String expDefId = ef.getExporterDefinitionId();
        String expName = ef.getExporterTag();
        // mapping: guiName -> AttributeDescription
        Map<String, AttributeDescription> attributesDescrGui = exportersDescr.get(expName);
        if (attributesDescrGui == null) {
            attributesDescrGui = new TreeMap<String, AttributeDescription>();
        }
        // mapping: guiName -> set of sub tags
        Set<String> setSubTags = exportersSetSubTags.get(expName);
        if (setSubTags == null) {
            setSubTags = new TreeSet<String>();
        }
        // construct new mapping: name -> AttributeDescription
        Map<String, AttributeDescription> attributesDescrAnt = new TreeMap<String, AttributeDescription>();
        for (AttributeDescription ad : attributesDescrGui.values()) {
            attributesDescrAnt.put(ad.name, ad);
        }
        //
        Element exporter = hibernatetool.addElement(expName);
        Properties expProps = new Properties();
        expProps.putAll(globalProps);
        expProps.putAll(ef.getProperties());
        //
        Properties extractGUISpecial = new Properties();
        try {
            ExporterFactory.extractExporterProperties(expDefId, expProps, extractGUISpecial);
        } catch (CoreException e) {
            // ignore
        }
        // convert gui special properties names into Ant names
        for (Map.Entry<Object, Object> propEntry : extractGUISpecial.entrySet()) {
            Object key = propEntry.getKey();
            Object val = propEntry.getValue();
            AttributeDescription ad = attributesDescrGui.get(key);
            if (ad == null) {
                expProps.put(key, val);
                continue;
            }
            expProps.put(ad.name, val);
        }
        // to add attributes and properties in alphabetic order
        Map<String, Object> expPropsSorted = new TreeMap<String, Object>();
        for (Map.Entry<Object, Object> propEntry : expProps.entrySet()) {
            Object key = propEntry.getKey();
            Object val = propEntry.getValue();
            expPropsSorted.put(key.toString(), val);
        }
        // list2Remove - list to collect properties which put into attributes,
        // all other properties be ordinal property definition
        List<Object> list2Remove = new ArrayList<Object>();
        for (Map.Entry<String, Object> propEntry : expPropsSorted.entrySet()) {
            Object key = propEntry.getKey();
            Object val = propEntry.getValue();
            AttributeDescription ad = attributesDescrAnt.get(key);
            if (ad == null) {
                continue;
            }
            list2Remove.add(key);
            if (val == null || 0 == val.toString().compareTo(ad.defaultValue)) {
                continue;
            }
            String processedVal = processPropertyValue(val);
            if (setSubTags.contains(ad.guiName)) {
                Element subTag = exporter.addElement(ad.name);
                subTag.addText(processedVal);
            } else {
                exporter.addAttribute(ad.name, processedVal);
            }
        }
        for (Object obj : list2Remove) {
            expProps.remove(obj);
            expPropsSorted.remove(obj);
        }
        for (Map.Entry<String, Object> propEntry : expPropsSorted.entrySet()) {
            Object key = propEntry.getKey();
            Object val = propEntry.getValue();
            String processedVal = processPropertyValue(val);
            Element property = exporter.addElement(CodeGenerationStrings.PROPERTY);
            property.addAttribute(CodeGenerationStrings.KEY, key.toString());
            property.addAttribute(CodeGenerationStrings.VALUE, processedVal);
        }
    }
    return root;
}

From source file:org.hibernate.envers.configuration.internal.metadata.ToOneRelationMetadataGenerator.java

License:LGPL

@SuppressWarnings({ "unchecked" })
void addToOne(Element parent, PropertyAuditingData propertyAuditingData, Value value,
        CompositeMapperBuilder mapper, String entityName, boolean insertable) {
    final String referencedEntityName = ((ToOne) value).getReferencedEntityName();

    final IdMappingData idMapping = mainGenerator.getReferencedIdMappingData(entityName, referencedEntityName,
            propertyAuditingData, true);

    final String lastPropertyPrefix = MappingTools.createToOneRelationPrefix(propertyAuditingData.getName());

    // Generating the id mapper for the relation
    final IdMapper relMapper = idMapping.getIdMapper().prefixMappedProperties(lastPropertyPrefix);

    // Storing information about this relation
    mainGenerator.getEntitiesConfigurations().get(entityName).addToOneRelation(propertyAuditingData.getName(),
            referencedEntityName, relMapper, insertable, MappingTools.ignoreNotFound(value));

    // If the property isn't insertable, checking if this is not a "fake" bidirectional many-to-one relationship,
    // that is, when the one side owns the relation (and is a collection), and the many side is non insertable.
    // When that's the case and the user specified to store this relation without a middle table (using
    // @AuditMappedBy), we have to make the property insertable for the purposes of Envers. In case of changes to
    // the entity that didn't involve the relation, it's value will then be stored properly. In case of changes
    // to the entity that did involve the relation, it's the responsibility of the collection side to store the
    // proper data.
    boolean nonInsertableFake;
    if (!insertable && propertyAuditingData.isForceInsertable()) {
        nonInsertableFake = true;/* w w w  .j  av  a 2 s.  c om*/
        insertable = true;
    } else {
        nonInsertableFake = false;
    }

    // Adding an element to the mapping corresponding to the references entity id's
    final Element properties = (Element) idMapping.getXmlRelationMapping().clone();
    properties.addAttribute("name", propertyAuditingData.getName());

    MetadataTools.prefixNamesInPropertyElement(properties, lastPropertyPrefix,
            MetadataTools.getColumnNameIterator(value.getColumnIterator()), false, insertable);

    // Extracting related id properties from properties tag
    for (Object o : properties.content()) {
        final Element element = (Element) o;
        element.setParent(null);
        parent.add(element);
    }

    // Adding mapper for the id
    final PropertyData propertyData = propertyAuditingData.getPropertyData();
    mapper.addComposite(propertyData,
            new ToOneIdMapper(relMapper, propertyData, referencedEntityName, nonInsertableFake));
}

From source file:org.infoglue.cms.util.dom.DOMBuilder.java

License:Open Source License

/**
 * This method adds an element to a given parent element.
 *///from  w  w  w  .j a  v  a  2s  . c om

public void insertElement(Element element, Element childElement) {
    element.content().add(childElement);
}

From source file:org.jbpm.instantiation.Delegation.java

License:Open Source License

public void read(Element delegateElement, JpdlXmlReader jpdlReader) {
    processDefinition = jpdlReader.getProcessDefinition();
    className = delegateElement.attributeValue("class");
    if (className == null) {
        jpdlReader.addWarning("no class specified in " + delegateElement.asXML());
    }/* w  w w.  j  a v  a2s  . com*/

    configType = delegateElement.attributeValue("config-type");
    if (delegateElement.hasContent()) {
        try {
            StringWriter stringWriter = new StringWriter();
            // when parsing, it could be to store the config in the database, so we want to make the configuration compact
            XMLWriter xmlWriter = new XMLWriter(stringWriter, OutputFormat.createCompactFormat());
            Iterator iter = delegateElement.content().iterator();
            while (iter.hasNext()) {
                Object node = iter.next();
                xmlWriter.write(node);
            }
            xmlWriter.flush();
            configuration = stringWriter.toString();
        } catch (IOException e) {
            jpdlReader.addWarning("io problem while parsing the configuration of " + delegateElement.asXML());
        }
    }
}

From source file:org.jbpm.instantiation.Delegation.java

License:Open Source License

public void write(Element element) {
    element.addAttribute("class", className);
    element.addAttribute("config-type", configType);
    String configuration = this.configuration;
    if (configuration != null) {
        try {/*  w  w w  .ja  v a2  s.c o m*/
            Element actionElement = DocumentHelper.parseText("<action>" + configuration + "</action>")
                    .getRootElement();
            Iterator iter = new ArrayList(actionElement.content()).iterator();
            while (iter.hasNext()) {
                Node node = (Node) iter.next();
                node.setParent(null);
                element.add(node);
            }
        } catch (DocumentException e) {
            log.error("couldn't create dom-tree for action configuration '" + configuration + "'", e);
        }
    }
}

From source file:org.jetbrains.kotlin.projectsextensions.j2se.buildextender.KotlinBuildExtender.java

License:Apache License

private void insertWithKotlin(FileObject buildImpl) throws DocumentException, IOException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(buildImpl.toURL());
    Element target = null;/*ww w.java2 s  .c  o  m*/

    List<Element> elements = document.getRootElement().elements("target");
    for (Element el : elements) {
        if (el.attribute("name").getValue().equals("-init-macrodef-javac-with-processors")) {
            target = el;
        }
    }

    if (target == null) {
        return;
    }

    Element macrodef = target.element("macrodef");
    if (macrodef == null) {
        return;
    }

    Element sequential = macrodef.element("sequential");
    if (sequential == null) {
        return;
    }

    Element javac = sequential.element("javac");
    if (javac == null) {
        return;
    }

    if (javac.element("withKotlin") != null) {
        return;
    }

    DefaultElement withKotlin = new DefaultElement("withKotlin");

    List content = javac.content();
    if (content != null) {
        content.add(3, withKotlin);
    }

    OutputFormat format = OutputFormat.createPrettyPrint();
    FileWriter out = new FileWriter(buildImpl.getPath());
    XMLWriter writer;
    writer = new XMLWriter(out, format);
    writer.write(document);
    writer.close();
    out.close();
}

From source file:org.jetbrains.kotlin.projectsextensions.maven.buildextender.PomXmlModifier.java

License:Apache License

private Element createDependenciesElement(Element root) {
    QName qname = new QName("dependencies", root.getQName().getNamespace());
    DefaultElement dependenciesElement = new DefaultElement(qname);

    root.content().add(dependenciesElement);

    return root.element("dependencies");
}

From source file:org.jetbrains.kotlin.projectsextensions.maven.buildextender.PomXmlModifier.java

License:Apache License

private Element createBuildElement(Element root) {
    QName qname = new QName("build", root.getQName().getNamespace());
    DefaultElement buildElement = new DefaultElement(qname);

    root.content().add(buildElement);

    return root.element("build");
}