Example usage for org.w3c.dom Element getAttributes

List of usage examples for org.w3c.dom Element getAttributes

Introduction

In this page you can find the example usage for org.w3c.dom Element getAttributes.

Prototype

public NamedNodeMap getAttributes();

Source Link

Document

A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.

Usage

From source file:com.nridge.core.base.io.xml.DocumentReplyXML.java

/**
 * Parses an XML DOM element and loads it into a document list.
 *
 * @param anElement DOM element./* w  w w.ja va2 s .c  o m*/
 * @throws java.io.IOException I/O related exception.
 */
@Override
public void load(Element anElement) throws IOException {
    Attr nodeAttr;
    Node nodeItem;
    Document document;
    Element nodeElement;
    DocumentXML documentXML;
    String nodeName, nodeValue;

    nodeName = anElement.getNodeName();
    if (StringUtils.equalsIgnoreCase(nodeName, IO.XML_REPLY_NODE_NAME)) {
        mField.clearFeatures();
        String attrValue = anElement.getAttribute(Doc.FEATURE_OP_STATUS_CODE);
        if (StringUtils.isNotEmpty(attrValue)) {
            mField.setName(Doc.FEATURE_OP_STATUS_CODE);
            mField.setValue(attrValue);
            NamedNodeMap namedNodeMap = anElement.getAttributes();
            int attrCount = namedNodeMap.getLength();
            for (int attrOffset = 0; attrOffset < attrCount; attrOffset++) {
                nodeAttr = (Attr) namedNodeMap.item(attrOffset);
                nodeName = nodeAttr.getNodeName();
                nodeValue = nodeAttr.getNodeValue();

                if (StringUtils.isNotEmpty(nodeValue)) {
                    if ((!StringUtils.equalsIgnoreCase(nodeName, Doc.FEATURE_OP_STATUS_CODE))
                            && (!StringUtils.equalsIgnoreCase(nodeName, Doc.FEATURE_OP_COUNT)))
                        mField.addFeature(nodeName, nodeValue);
                }
            }
        }
        NodeList nodeList = anElement.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            nodeItem = nodeList.item(i);

            if (nodeItem.getNodeType() != Node.ELEMENT_NODE)
                continue;

            // We really do not know how the node was named, so we will just accept it.

            nodeElement = (Element) nodeItem;
            documentXML = new DocumentXML();
            documentXML.load(nodeElement);
            document = documentXML.getDocument();
            if (document != null)
                mDocumentList.add(document);
        }
    }
}

From source file:com.amalto.core.storage.hibernate.MappingGenerator.java

@Override
public Element visit(ReferenceFieldMetadata referenceField) {
    if (referenceField.isKey()) {
        throw new UnsupportedOperationException("FK field '" + referenceField.getName() //$NON-NLS-1$
                + "' cannot be key in type '" + referenceField.getDeclaringType().getName() + "'"); // Don't support FK as key  //$NON-NLS-1$ //$NON-NLS-2$
    } else {/*w ww .  j a  v a 2  s  .  c o m*/
        boolean enforceDataBaseIntegrity = generateConstrains
                && (!referenceField.allowFKIntegrityOverride() && referenceField.isFKIntegrity());
        if (!referenceField.isMany()) {
            return newManyToOneElement(referenceField, enforceDataBaseIntegrity);
        } else {
            /*
            <list name="bars" table="foo_bar">
             <key column="foo_id"/>
             <many-to-many column="bar_id" class="Bar"/>
              </list>
             */
            Element propertyElement = document.createElement("list"); //$NON-NLS-1$
            Attr name = document.createAttribute("name"); //$NON-NLS-1$
            name.setValue(referenceField.getName());
            propertyElement.getAttributes().setNamedItem(name);
            Attr lazy = document.createAttribute("lazy"); //$NON-NLS-1$
            lazy.setValue("extra"); //$NON-NLS-1$
            propertyElement.getAttributes().setNamedItem(lazy);
            // fetch="select"
            Attr joinAttribute = document.createAttribute("fetch"); //$NON-NLS-1$
            joinAttribute.setValue("select"); // Keep it "select" (Hibernate tends to duplicate results when using "fetch") //$NON-NLS-1$
            propertyElement.getAttributes().setNamedItem(joinAttribute);
            // cascade="true"
            if (Boolean.parseBoolean(referenceField.<String>getData(SQL_DELETE_CASCADE))) {
                Attr cascade = document.createAttribute("cascade"); //$NON-NLS-1$
                cascade.setValue("lock, save-update, delete"); //$NON-NLS-1$
                propertyElement.getAttributes().setNamedItem(cascade);
            }
            Attr tableName = document.createAttribute("table"); //$NON-NLS-1$
            tableName.setValue(resolver.getCollectionTable(referenceField));
            propertyElement.getAttributes().setNamedItem(tableName);
            {
                // <key column="foo_id"/> (one per key in referenced entity).
                Element key = document.createElement("key"); //$NON-NLS-1$
                propertyElement.appendChild(key);
                for (FieldMetadata keyField : referenceField.getContainingType().getKeyFields()) {
                    Element elementColumn = document.createElement("column"); //$NON-NLS-1$
                    Attr columnName = document.createAttribute("name"); //$NON-NLS-1$
                    columnName.setValue(resolver.get(keyField));
                    elementColumn.getAttributes().setNamedItem(columnName);
                    key.appendChild(elementColumn);
                }
                // <index column="pos" />
                Element index = document.createElement("index"); //$NON-NLS-1$
                Attr indexColumn = document.createAttribute("column"); //$NON-NLS-1$
                indexColumn.setValue("pos"); //$NON-NLS-1$
                index.getAttributes().setNamedItem(indexColumn);
                propertyElement.appendChild(index);
                // many to many element
                Element manyToMany = newManyToManyElement(enforceDataBaseIntegrity, referenceField);
                propertyElement.appendChild(manyToMany);
            }
            return propertyElement;
        }
    }
}

From source file:com.alfaariss.oa.util.configuration.ConfigurationManager.java

/**
 * @see com.alfaariss.oa.api.configuration.IConfigurationManager#getParams(org.w3c.dom.Element, java.lang.String)
 *//*from  w  w w  .  j a  v a  2  s  .c o  m*/
public synchronized List<String> getParams(Element eSection, String sParamName) throws ConfigurationException {
    if (eSection == null)
        throw new IllegalArgumentException("Suplied section is empty");
    if (sParamName == null)
        throw new IllegalArgumentException("Suplied parameter name is empty");

    List<String> listValues = new Vector<String>();

    try {
        //check attributes within the section tag
        if (eSection.hasAttributes()) {
            NamedNodeMap oNodeMap = eSection.getAttributes();
            Node nAttribute = oNodeMap.getNamedItem(sParamName);
            if (nAttribute != null) {
                String sAttributeValue = nAttribute.getNodeValue();
                if (sAttributeValue != null)
                    listValues.add(sAttributeValue);
            }
        }

        NodeList nlChilds = eSection.getChildNodes();
        for (int i = 0; i < nlChilds.getLength(); i++) {
            Node nTemp = nlChilds.item(i);
            if (nTemp != null && nTemp.getNodeName().equalsIgnoreCase(sParamName)) {
                String sValue = "";
                NodeList nlSubNodes = nTemp.getChildNodes();
                if (nlSubNodes.getLength() > 0) {
                    for (int iSub = 0; iSub < nlSubNodes.getLength(); iSub++) {
                        Node nSubTemp = nlSubNodes.item(iSub);
                        if (nSubTemp.getNodeType() == Node.TEXT_NODE) {
                            sValue = nSubTemp.getNodeValue();
                            if (sValue == null)
                                sValue = "";
                        }
                    }
                }

                listValues.add(sValue);
            }
        }

        if (listValues.isEmpty())
            return null;
    } catch (DOMException e) {
        _logger.error("Could not retrieve parameter: " + sParamName, e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_READ);
    }

    return listValues;
}

From source file:com.nridge.core.base.io.xml.DataBagXML.java

/**
 * Parses an XML DOM element and loads it into a bag/table.
 *
 * @param anElement DOM element.//  w  ww . ja v  a2 s. c  o m
 * @throws java.io.IOException I/O related exception.
 */
@Override
public void load(Element anElement) throws IOException {
    Node nodeItem;
    Attr nodeAttr;
    Element nodeElement;
    DataField dataField;
    String nodeName, nodeValue;

    String className = mBag.getClass().getName();
    String attrValue = anElement.getAttribute("type");
    if ((StringUtils.isNotEmpty(attrValue)) && (!IO.isTypesEqual(attrValue, className)))
        throw new IOException("Unsupported type: " + attrValue);

    attrValue = anElement.getAttribute("name");
    if (StringUtils.isNotEmpty(attrValue))
        mBag.setName(attrValue);
    attrValue = anElement.getAttribute("title");
    if (StringUtils.isNotEmpty(attrValue))
        mBag.setTitle(attrValue);

    NamedNodeMap namedNodeMap = anElement.getAttributes();
    int attrCount = namedNodeMap.getLength();
    for (int attrOffset = 0; attrOffset < attrCount; attrOffset++) {
        nodeAttr = (Attr) namedNodeMap.item(attrOffset);
        nodeName = nodeAttr.getNodeName();
        nodeValue = nodeAttr.getNodeValue();

        if (StringUtils.isNotEmpty(nodeValue)) {
            if ((StringUtils.equalsIgnoreCase(nodeName, "name"))
                    || (StringUtils.equalsIgnoreCase(nodeName, "type"))
                    || (StringUtils.equalsIgnoreCase(nodeName, "count"))
                    || (StringUtils.equalsIgnoreCase(nodeName, "title"))
                    || (StringUtils.equalsIgnoreCase(nodeName, "version")))
                continue;
            else
                mBag.addFeature(nodeName, nodeValue);
        }
    }

    NodeList nodeList = anElement.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        nodeItem = nodeList.item(i);

        if (nodeItem.getNodeType() != Node.ELEMENT_NODE)
            continue;

        nodeName = nodeItem.getNodeName();
        if (nodeName.equalsIgnoreCase(IO.XML_FIELD_NODE_NAME)) {
            nodeElement = (Element) nodeItem;
            dataField = mDataFieldXML.load(nodeElement);
            if (dataField != null)
                mBag.add(dataField);
        }
    }
}

From source file:betullam.xmlmodifier.XMLmodifier.java

/**
 * @param args// ww  w.ja  v a2s.  c o m
 * @throws ParserConfigurationException 
 * @throws IOException 
 * @throws SAXException 
 * @throws XPathExpressionException 
 * @throws TransformerException 
 */
public void modify(String mdFolder, String fileName, String condStructureType, String condMdNameFile,
        String condMdValueFile, String condMdNameElement, String condMdValueElement, String newMdName,
        String newMdValue) {

    // Get the files that should be modified:
    Set<File> filesToModify = getFilesToModify(mdFolder, fileName, condStructureType, condMdNameFile,
            condMdValueFile);

    // Backup XML-files before modifing them:
    makeBackupFiles(filesToModify);

    // Iterate over all files in given directory and it's subdirectories. Works with Apache commons-io library (FileUtils).
    for (File xmlFile : filesToModify) {

        // DOM Parser:
        String filePath = xmlFile.getAbsolutePath();
        DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
        Document xmlDoc = null;
        try {
            DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
            xmlDoc = documentBuilder.parse(filePath);

            // Get the elements to change. The name-attribute of the <goobi:metadata ...>-tag is important.
            // E. g. to change metadata "AccessLicense", the value of "mdName" must be the same as the name-attribute: <goobi:metadata name="AccessLicense">
            List<Node> nodeArrayList = getElementsToModify(condMdNameElement, condMdValueElement, xmlDoc);

            // Set the metadata (modMdName) to the given value (modMdValue):
            //for (int i = 0; i < node.getLength(); i++) {
            for (Node node : nodeArrayList) {
                Element xmlElement = (Element) node;

                // Change element text content:
                if (!newMdValue.equals("null")) {
                    xmlElement.setTextContent(newMdValue);
                }

                // Change element content
                if (!newMdName.equals("null")) {
                    NamedNodeMap attributes = xmlElement.getAttributes();
                    for (int j = 0; j < attributes.getLength(); j++) {
                        //Element attributeElement = (Attribute)attributes.item(j);
                        //xmlElement.setAttribute(attributes.item(j).getNodeName(), newMdName);
                        xmlElement.setAttribute("name", newMdName);
                    }
                }
            }

            // Save modifications to XML file:
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(xmlDoc);
            StreamResult streamResult = new StreamResult(new File(filePath));
            transformer.transform(domSource, streamResult);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }

        System.out.println("File modified: " + xmlFile.getAbsoluteFile());
    }
}

From source file:com.amalto.core.storage.hibernate.MappingGenerator.java

private static void addFieldTypeAttribute(FieldMetadata field, Element columnElement, Element propertyElement,
        RDBMSDataSource.DataSourceDialect dialect) {
    Document document = columnElement.getOwnerDocument();
    Document propertyDocument = propertyElement.getOwnerDocument();
    Attr elementType = propertyDocument.createAttribute("type"); //$NON-NLS-1$
    TypeMetadata fieldType = field.getType();
    String elementTypeName;// w ww .j a  v  a2  s. c  o m

    boolean isMultiLingualOrBase64Binary = Types.MULTI_LINGUAL.equalsIgnoreCase(fieldType.getName())
            || Types.BASE64_BINARY.equalsIgnoreCase(fieldType.getName());
    Object maxLength = CommonUtil.getSuperTypeMaxLength(fieldType, fieldType);

    if (isMultiLingualOrBase64Binary) {
        elementTypeName = TypeMapping.SQL_TYPE_TEXT;
    } else {
        Object sqlType = fieldType.getData(TypeMapping.SQL_TYPE);
        if (sqlType != null) { // SQL Type may enforce use of "CLOB" iso. "LONG VARCHAR"
            elementTypeName = String.valueOf(sqlType);
            if (dialect == RDBMSDataSource.DataSourceDialect.DB2) {
                Attr length = document.createAttribute("length"); //$NON-NLS-1$
                length.setValue("1048576"); //$NON-NLS-1$ 1MB CLOB limit for DB2
                columnElement.getAttributes().setNamedItem(length);
            }
        } else if (maxLength != null) {
            String maxLengthValue = String.valueOf(maxLength);
            int maxLengthInt = Integer.parseInt(maxLengthValue);
            if (maxLengthInt > dialect.getTextLimit()) {
                elementTypeName = TypeMapping.SQL_TYPE_TEXT;
            } else {
                Attr length = document.createAttribute("length"); //$NON-NLS-1$
                length.setValue(maxLengthValue);
                columnElement.getAttributes().setNamedItem(length);
                elementTypeName = HibernateMetadataUtils.getJavaType(fieldType);
            }
        } else if (fieldType.getData(MetadataRepository.DATA_TOTAL_DIGITS) != null
                || fieldType.getData(MetadataRepository.DATA_FRACTION_DIGITS) != null) { // TMDM-8022

            Object totalDigits = fieldType.getData(MetadataRepository.DATA_TOTAL_DIGITS);
            Object fractionDigits = fieldType.getData(MetadataRepository.DATA_FRACTION_DIGITS);

            if (totalDigits != null) {
                int totalDigitsInt = Integer.parseInt(totalDigits.toString());
                totalDigitsInt = totalDigitsInt > dialect.getDecimalPrecision() ? dialect.getDecimalPrecision()
                        : totalDigitsInt;

                String totalDigitsValue = String.valueOf(totalDigitsInt);
                Attr length = document.createAttribute("precision"); //$NON-NLS-1$
                length.setValue(totalDigitsValue);
                columnElement.getAttributes().setNamedItem(length);
            }

            if (fractionDigits != null) {
                int fractionDigitsInt = Integer.parseInt(fractionDigits.toString());
                fractionDigitsInt = fractionDigitsInt >= dialect.getDecimalScale() ? dialect.getDecimalScale()
                        : fractionDigitsInt;

                String fractionDigitsValue = String.valueOf(fractionDigitsInt);
                Attr length = document.createAttribute("scale"); //$NON-NLS-1$
                length.setValue(fractionDigitsValue);
                columnElement.getAttributes().setNamedItem(length);
            }
            elementTypeName = HibernateMetadataUtils.getJavaType(fieldType);
        } else {
            elementTypeName = HibernateMetadataUtils.getJavaType(fieldType);
        }
    }
    // TMDM-4975: Oracle doesn't like when there are too many LONG columns.
    if (dialect == RDBMSDataSource.DataSourceDialect.ORACLE_10G
            && TypeMapping.SQL_TYPE_TEXT.equals(elementTypeName)) {
        if (field.getType().getData(LongString.PREFER_LONGVARCHAR) == null
                && isMultiLingualOrBase64Binary == false) {
            elementTypeName = TypeMapping.SQL_TYPE_CLOB;
        } else {// DATA_CLUSTER_POJO.X_VOCABULARY, X_TALEND_STAGING_ERROR, X_TALEND_STAGING_VALUES, and
                // Types.MULTI_LINGUAL, Types.BASE64_BINARY still use VARCHAR2(4000 CHAR)
            elementTypeName = "string"; //$NON-NLS-1$
            Attr length = document.createAttribute("length"); //$NON-NLS-1$
            length.setValue("4000"); //$NON-NLS-1$
            columnElement.getAttributes().setNamedItem(length);
        }
    }
    elementType.setValue(elementTypeName);
    propertyElement.getAttributes().setNamedItem(elementType);
}

From source file:com.amalto.workbench.providers.XSDTreeLabelProvider.java

@Override
public String getText(Object obj) {

    // log.info("getText   "+obj.getClass().getName());

    if (obj instanceof XSDElementDeclaration) {
        String name = ((XSDElementDeclaration) obj).getName();
        if (((XSDElementDeclaration) obj).isAbstract()) {
            name += Messages.XSDTreeLabelProvider_0;
        }/*w  w w  .j  a v a  2  s  .  c  om*/
        String tail = ((XSDElementDeclaration) obj).getTargetNamespace() != null ? " : "//$NON-NLS-1$
                + ((XSDElementDeclaration) obj).getTargetNamespace() : "";//$NON-NLS-1$
        return name + tail;
    }

    if (obj instanceof XSDParticle) {
        XSDParticle xsdParticle = (XSDParticle) obj;
        XSDParticleContent content = xsdParticle.getContent();
        XSDTerm xsdTerm = xsdParticle.getTerm();
        String name = "";//$NON-NLS-1$
        if (content instanceof XSDElementDeclaration) {
            XSDElementDeclaration decl = (XSDElementDeclaration) content;
            name += (decl.getName() == null ? "" : decl.getName());//$NON-NLS-1$
            if (decl.getTypeDefinition() == null) {
                name += " [" + ((XSDElementDeclaration) xsdTerm).getName() + "]";//$NON-NLS-1$//$NON-NLS-2$
            }
        } else if (content instanceof XSDModelGroup) {
            // log.info("SHOULD NOT HAPPEN????");
            if (xsdParticle.getContainer() instanceof XSDComplexTypeDefinition) {
                String ctdName = ((XSDComplexTypeDefinition) xsdParticle.getContainer()).getName();
                name = (ctdName != null ? ctdName : "");//$NON-NLS-1$
            }

        } else {
            name = "[Any]";//$NON-NLS-1$
        }
        if (!((xsdParticle.getMinOccurs() == 1) && (xsdParticle.getMaxOccurs() == 1))) {
            name += "  [";//$NON-NLS-1$
            name += xsdParticle.getMinOccurs();
            name += "...";//$NON-NLS-1$
            name += (xsdParticle.getMaxOccurs() == -1) ? "many" : "" + xsdParticle.getMaxOccurs();//$NON-NLS-1$//$NON-NLS-2$
            name += "]";//$NON-NLS-1$
        }
        return name;
    }

    if (obj instanceof XSDSimpleTypeDefinition) {
        return getSimpleTypeDefinition((XSDSimpleTypeDefinition) obj);
    }

    if (obj instanceof XSDModelGroup) {
        // return the name of the complex type definition
        XSDParticle particle = (XSDParticle) (((XSDModelGroup) obj).getContainer());
        XSDComplexTypeDefinition complexTypeDefinition = (XSDComplexTypeDefinition) particle.getContainer();
        String name = complexTypeDefinition.getName();
        if (name == null) {
            name = "anonymous type ";//$NON-NLS-1$
        }
        // return the occurrence
        if (!((particle.getMinOccurs() == 1) && (particle.getMaxOccurs() == 1))) {
            name += "  [";//$NON-NLS-1$
            name += particle.getMinOccurs();
            name += "...";//$NON-NLS-1$
            name += (particle.getMaxOccurs() == -1) ? "many" : "" + particle.getMaxOccurs();//$NON-NLS-1$//$NON-NLS-2$
            name += "]";//$NON-NLS-1$
        }
        // get extend type
        XSDTypeDefinition extendType = complexTypeDefinition.getBaseTypeDefinition();
        String extendTypeName = ""; //$NON-NLS-1$
        if (extendType != null && extendType != complexTypeDefinition
                && !"anyType".equals(extendType.getName())) { //$NON-NLS-1$
            extendTypeName = ":" + extendType.getName(); //$NON-NLS-1$
        }
        XSDSchema schema = particle.getSchema();
        String tail = ""; //$NON-NLS-1$
        if (schema != null && schema.getTargetNamespace() != null) {
            tail = " : "//$NON-NLS-1$
                    + schema.getTargetNamespace();
        }
        return name + tail + extendTypeName;

    }

    if (obj instanceof XSDFacet) {
        return ((XSDFacet) obj).getFacetName() + ": " + ((XSDFacet) obj).getLexicalValue();//$NON-NLS-1$
    }

    if (obj instanceof XSDIdentityConstraintDefinition) {
        return ((XSDIdentityConstraintDefinition) obj).getName();
    }

    if (obj instanceof XSDXPathDefinition) {
        XSDXPathDefinition xpath = (XSDXPathDefinition) obj;
        return xpath.getValue();
    }

    if (obj instanceof XSDAttributeGroupDefinition) {
        XSDAttributeGroupDefinition attributeGroupDefinition = (XSDAttributeGroupDefinition) obj;
        String name = (attributeGroupDefinition.getName() == null ? "" : attributeGroupDefinition.getName());//$NON-NLS-1$
        if (attributeGroupDefinition.getContents().size() == 0) {
            name += " [" + attributeGroupDefinition.getResolvedAttributeGroupDefinition().getName() + "]";//$NON-NLS-1$//$NON-NLS-2$
        }
        return name;
    }

    if (obj instanceof XSDAttributeUse) {
        XSDAttributeUse attributeUse = (XSDAttributeUse) obj;
        String name = attributeUse.getAttributeDeclaration().getName();
        if (name == null) {
            name = " [" + attributeUse.getAttributeDeclaration().getResolvedAttributeDeclaration().getName() //$NON-NLS-1$
                    + "]";//$NON-NLS-1$
        }
        return name;
    }

    if (obj instanceof XSDAttributeDeclaration) {
        XSDAttributeDeclaration attributeDec = (XSDAttributeDeclaration) obj;
        String name = attributeDec.getName();
        if (name == null) {
            name = attributeDec.getAliasName();
            if (name == null) {
                name = " [null]"; //$NON-NLS-1$
            }
        }
        return name;
    }

    if (obj instanceof XSDAnnotation) {
        // XSDAnnotation annotation = (XSDAnnotation) obj;
        return "Annotations";//$NON-NLS-1$
    }

    if (obj instanceof Element) {
        try {
            Element e = (Element) obj;
            if (e.getLocalName().equals("documentation")) {//$NON-NLS-1$
                return "Documentation: " + e.getChildNodes().item(0).getNodeValue();//$NON-NLS-1$
            } else if (e.getLocalName().equals("appinfo")) {//$NON-NLS-1$
                String source = e.getAttribute("source");//$NON-NLS-1$
                if (source != null) {
                    if (source.startsWith("X_Label_")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_1,
                                Util.iso2lang.get(source.substring(8).toLowerCase()),
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_ForeignKey")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_2,
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_ForeignKey_NotSep")) {//$NON-NLS-1$
                        Boolean v = Boolean.valueOf(e.getChildNodes().item(0).getNodeValue());
                        return Messages.bind(Messages.XSDTreeLabelProvider_3,
                                Messages.SimpleXpathInputDialog_sepFkTabPanel, v);
                    } else if (source.equals("X_Visible_Rule")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_4,
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_Default_Value_Rule")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_5,
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_ForeignKeyInfo")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_6,
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_ForeignKeyInfoFormat")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_20,
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_PrimaryKeyInfo")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_7,
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_SourceSystem")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_8,
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_TargetSystem")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_9,
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.startsWith("X_Description_")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_10,
                                Util.iso2lang.get(source.substring(14).toLowerCase()),
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_Write")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_11,
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_Deny_Create")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_12,
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_Deny_LogicalDelete")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_13,
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_Deny_PhysicalDelete")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_14,
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_Lookup_Field")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_15,
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_Workflow")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_16,
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_Hide")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_17,
                                e.getChildNodes().item(0).getNodeValue());
                        // add by ymli; bugId 0009157
                    } else if (source.equals("X_AutoExpand")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_18,
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.startsWith("X_Facet")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_19, source.substring(2, 7),
                                source.substring(8), e.getChildNodes().item(0).getNodeValue());
                        // made schematron show:Schematron: schematron
                    } else if (source.startsWith("X_Display_Format_")) {//$NON-NLS-1$
                        return source + ": " + e.getChildNodes().item(0).getNodeValue();//$NON-NLS-1$
                    } else if (source.equals("X_Schematron")) {//$NON-NLS-1$

                        String pattern = (String) e.getFirstChild().getUserData("pattern_name");//$NON-NLS-1$
                        if (pattern == null) {
                            Element el = Util.parse(e.getChildNodes().item(0).getNodeValue())
                                    .getDocumentElement();
                            if (el.getAttributes().getNamedItem("name") != null) { //$NON-NLS-1$
                                pattern = el.getAttributes().getNamedItem("name").getTextContent();//$NON-NLS-1$
                            }
                        }
                        return Messages.bind(Messages.XSDTreeLabelProvider_21,
                                (pattern == null ? Messages.XSDTreeLabelProvider_22 : pattern));// e.getChildNodes().item(0).getNodeValue();
                        // end
                    } else if (source.equals("X_Retrieve_FKinfos")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_23,
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_FKIntegrity")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_24,
                                e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_FKIntegrity_Override")) {//$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_25,
                                e.getChildNodes().item(0).getNodeValue());
                    }

                    if (source.equals("X_ForeignKey_Filter")) {//$NON-NLS-1$
                        String nodeValue = e.getChildNodes().item(0).getNodeValue();
                        if (nodeValue.startsWith("$CFFP:")) {//$NON-NLS-1$
                            nodeValue = StringEscapeUtils.unescapeXml(nodeValue).substring(6);
                        }
                        return Messages.bind(Messages.XSDTreeLabelProvider_26, nodeValue);
                    } else {
                        return source + ": " + Util.nodeToString((Element) obj);//$NON-NLS-1$
                    }
                } else {
                    return Util.nodeToString((Element) obj);
                }
            } else {
                return Util.nodeToString((Element) obj);
            }
        } catch (Exception e) {

            log.error(e.getMessage(), e);
        }
    }

    if (obj == null) {
        return "NULL";//$NON-NLS-1$
    }
    return "?? " + obj.getClass().getName() + " : " + obj.toString();//$NON-NLS-1$//$NON-NLS-2$

}

From source file:com.inbravo.scribe.rest.service.crm.ms.MSCRMMessageFormatUtils.java

public static final List<Element> createEntityFromBusinessObject(final BusinessEntity businessEntity)
        throws Exception {

    /* Create list of elements */
    final List<Element> elementList = new ArrayList<Element>();

    if (businessEntity != null) {
        final Node node = businessEntity.getDomNode();
        if (node.hasChildNodes()) {
            final NodeList nodeList = node.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {

                /* To avoid : 'DOM Level 3 Not implemented' error */
                final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                final Document document = builder.newDocument();
                final Element element = (Element) document.importNode(nodeList.item(i), true);

                if (element.getNodeName() != null && element.getNodeName().contains(":")) {
                    final String nodeName = element.getNodeName().split(":")[1];

                    /* Check for attributes */
                    final NamedNodeMap attributes = element.getAttributes();

                    if (attributes != null && attributes.getLength() != 0) {

                        /* Create new map for attributes */
                        final Map<String, String> attributeMap = new HashMap<String, String>();

                        for (int j = 0; j < attributes.getLength(); j++) {
                            final Attr attr = (Attr) attributes.item(j);

                            /* Set node name and value in map */
                            attributeMap.put(attr.getNodeName(), attr.getNodeValue());
                        }/*from   www  .j  av  a  2s .c  om*/

                        /* Create node with attributes */
                        elementList.add(MSCRMMessageFormatUtils.createMessageElement(nodeName,
                                element.getTextContent(), attributeMap));
                    } else {

                        /* Create node without attributes */
                        elementList.add(MSCRMMessageFormatUtils.createMessageElement(nodeName,
                                element.getTextContent()));
                    }
                }
            }
        }
        return elementList;
    } else {
        return null;
    }
}

From source file:eu.elf.license.LicenseQueryHandler.java

/**
 * Gets the price of the License Model/*ww w .j  av  a 2 s  . com*/
 *
 * @param lm     - LicenseModel object
 * @param userId - UserId
 * @throws Exception
 * @return         - ProductPriceSum as String
 */
public String getLicenseModelPrice(LicenseModel lm, String userId) throws Exception {
    StringBuffer buf = null;
    String productPriceSum = "";
    List<LicenseParam> lpList = lm.getParams();

    String productPriceQuery = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
            + "<wpos:WPOSRequest xmlns:wpos=\"http://www.conterra.de/wpos/1.1\" version=\"1.1.0\">"
            + "<wpos:GetPrice collapse=\"true\">" + "<wpos:Product id=\""
            + StringEscapeUtils.escapeXml10(lm.getId()) + "\">" + "<wpos:ConfigParams>";

    for (int i = 0; i < lpList.size(); i++) {
        if (lpList.get(i).getParameterClass().equals("configurationParameter")) {

            LicenseParam lp = (LicenseParam) lpList.get(i);

            String priceQuery = "<wpos:Parameter name=\"" + StringEscapeUtils.escapeXml10(lp.getName()) + "\">";

            if (lp instanceof LicenseParamInt) {
                LicenseParamInt lpi = (LicenseParamInt) lp;

                priceQuery += "<wpos:Value selected=\"true\">" + lpi.getValue() + "</wpos:Value>"
                        + "</wpos:Parameter>";
            } else if (lp instanceof LicenseParamBln) {
                LicenseParamBln lpBln = (LicenseParamBln) lp;

                priceQuery += "<wpos:Value selected=\"true\">" + lpBln.getValue() + "</wpos:Value>"
                        + "</wpos:Parameter>";
            } else if (lp instanceof LicenseParamDisplay) {
                LicenseParamDisplay lpd = (LicenseParamDisplay) lp;
                List<String> values = lpd.getValues();

                if (lp.getName().equals("LICENSE_USER_GROUP")) {
                    priceQuery += "<wpos:Value>Users</wpos:Value>";

                } else if (lp.getName().equals("LICENSE_USER_ID")) {
                    priceQuery += "<wpos:Value>" + userId + "</wpos:Value>";

                } else {
                    for (int l = 0; l < values.size(); l++) {
                        priceQuery += "<wpos:Value selected=\"true\">"
                                + StringEscapeUtils.escapeXml10(values.get(l)) + "</wpos:Value>";
                    }
                }

                priceQuery += "</wpos:Parameter>";
            } else if (lp instanceof LicenseParamEnum) {
                LicenseParamEnum lpEnum = (LicenseParamEnum) lp;

                List<String> tempOptions = lpEnum.getOptions();
                List<String> tempSelections = lpEnum.getSelections();

                if (tempSelections.size() == 0) {
                    priceQuery = "";
                } else {
                    String selectionsString = "";

                    for (int j = 0; j < tempSelections.size(); j++) {
                        if (j == 0) {
                            selectionsString = tempSelections.get(j);
                        } else {
                            selectionsString += ", " + tempSelections.get(j);
                        }
                    }

                    priceQuery += "<wpos:Value selected=\"true\">"
                            + StringEscapeUtils.escapeXml10(selectionsString) + "</wpos:Value>"
                            + "</wpos:Parameter>";
                }
            } else if (lp instanceof LicenseParamText) {
                LicenseParamText lpText = (LicenseParamText) lp;
                List<String> values = lpText.getValues();

                for (int k = 0; k < values.size(); k++) {
                    priceQuery += "<wpos:Value selected=\"true\">" + lpText.getValues() + "</wpos:Value>";
                }
                priceQuery += "</wpos:Parameter>";
            }

            productPriceQuery += priceQuery;
        }

    }

    productPriceQuery += "</wpos:ConfigParams>" + "</wpos:Product>" + "</wpos:GetPrice>"
            + "</wpos:WPOSRequest>";

    //System.out.println("query: "+productPriceQuery.toString());

    try {
        buf = doHTTPQuery(this.wposURL, "post", productPriceQuery, false);
        //System.out.println("response: "+buf.toString());

        // Get productPriceInfo from the response
        Document xmlDoc = LicenseParser.createXMLDocumentFromString(buf.toString());
        Element catalogElement = (Element) xmlDoc
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "catalog").item(0);
        NodeList productGroupElementList = catalogElement
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "productGroup");

        for (int m = 0; m < productGroupElementList.getLength(); m++) {
            Element productGroupElement = (Element) productGroupElementList.item(m);
            Element calculationElement = (Element) productGroupElement
                    .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "calculation").item(0);
            Element declarationListElement = (Element) calculationElement
                    .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "declarationList").item(0);
            Element referencedParametersElement = (Element) declarationListElement
                    .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "referencedParameters").item(0);
            NodeList referencedParametersParameterList = referencedParametersElement
                    .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "parameter");

            for (int n = 0; n < referencedParametersParameterList.getLength(); n++) {
                Element referencedParametersParameterElement = (Element) referencedParametersParameterList
                        .item(n);

                NamedNodeMap referencedParametersParameterAttributeMap = referencedParametersParameterElement
                        .getAttributes();

                for (int o = 0; o < referencedParametersParameterAttributeMap.getLength(); o++) {
                    Attr attrs = (Attr) referencedParametersParameterAttributeMap.item(o);

                    if (attrs.getNodeName().equals("name")) {
                        if (attrs.getNodeValue().equals("productPriceSum")) {
                            Element valueElement = (Element) referencedParametersParameterElement
                                    .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "value").item(0);

                            productPriceSum = valueElement.getTextContent();
                        }
                    }
                }

            }

        }

    } catch (Exception e) {
        throw e;
    }

    return productPriceSum;
}

From source file:com.amalto.core.storage.hibernate.MappingGenerator.java

@Override
public Element visit(ComplexTypeMetadata complexType) {
    if (complexType.getKeyFields().isEmpty()) {
        throw new IllegalArgumentException("Type '" + complexType.getName() + "' has no key."); //$NON-NLS-1$ //$NON-NLS-2$
    }/* w w  w  .ja  v  a 2  s. c  om*/
    if (!complexType.getSuperTypes().isEmpty()) {
        return null;
    }

    tableNames.push(resolver.get(complexType));
    Element classElement;
    {
        String generatedClassName = ClassCreator.getClassName(complexType.getName());
        classElement = document.createElement("class"); //$NON-NLS-1$
        Attr className = document.createAttribute("name"); //$NON-NLS-1$
        className.setValue(generatedClassName);
        classElement.getAttributes().setNamedItem(className);
        Attr classTable = document.createAttribute("table"); //$NON-NLS-1$
        classTable.setValue(tableNames.peek());
        classElement.getAttributes().setNamedItem(classTable);
        // Adds schema name (if set in configuration)
        String value = dataSource.getAdvancedProperties().get("hibernate.default_schema"); //$NON-NLS-1
        if (value != null) {
            Attr classSchema = document.createAttribute("schema"); //$NON-NLS-1$
            classSchema.setValue(value);
            classElement.getAttributes().setNamedItem(classSchema);
        }
        // dynamic-update="true"
        Attr dynamicUpdate = document.createAttribute("dynamic-update"); //$NON-NLS-1$
        dynamicUpdate.setValue("true"); //$NON-NLS-1$
        classElement.getAttributes().setNamedItem(dynamicUpdate);
        // dynamic-insert="true"
        Attr dynamicInsert = document.createAttribute("dynamic-insert"); //$NON-NLS-1$
        dynamicInsert.setValue("true"); //$NON-NLS-1$
        classElement.getAttributes().setNamedItem(dynamicInsert);
        // <cache usage="read-write" include="non-lazy"/>
        Element cacheElement = document.createElement("cache"); //$NON-NLS-1$
        Attr usageAttribute = document.createAttribute("usage"); //$NON-NLS-1$
        usageAttribute.setValue("read-write"); //$NON-NLS-1$
        cacheElement.getAttributes().setNamedItem(usageAttribute);
        Attr includeAttribute = document.createAttribute("include"); //$NON-NLS-1$
        includeAttribute.setValue("non-lazy"); //$NON-NLS-1$
        cacheElement.getAttributes().setNamedItem(includeAttribute);
        Attr regionAttribute = document.createAttribute("region"); //$NON-NLS-1$
        regionAttribute.setValue("region"); //$NON-NLS-1$
        cacheElement.getAttributes().setNamedItem(regionAttribute);
        classElement.appendChild(cacheElement);

        Collection<FieldMetadata> keyFields = complexType.getKeyFields();
        List<FieldMetadata> allFields = new ArrayList<FieldMetadata>(complexType.getFields());

        // Process key fields first (Hibernate DTD enforces IDs to be declared first in <class/> element).
        Element idParentElement = classElement;
        if (keyFields.size() > 1) {
            /*
            <composite-id>
                    <key-property column="x_enterprise" name="x_enterprise"/>
                    <key-property column="x_id" name="x_id"/>
                </composite-id>
             */
            compositeId = true;
            idParentElement = document.createElement("composite-id"); //$NON-NLS-1$
            classElement.appendChild(idParentElement);

            Attr classAttribute = document.createAttribute("class"); //$NON-NLS-1$
            classAttribute.setValue(generatedClassName + "_ID"); //$NON-NLS-1$
            idParentElement.getAttributes().setNamedItem(classAttribute);

            Attr mappedAttribute = document.createAttribute("mapped"); //$NON-NLS-1$
            mappedAttribute.setValue("true"); //$NON-NLS-1$
            idParentElement.getAttributes().setNamedItem(mappedAttribute);
        }
        for (FieldMetadata keyField : keyFields) {
            idParentElement.appendChild(keyField.accept(this));
            boolean wasRemoved = allFields.remove(keyField);
            if (!wasRemoved) {
                LOGGER.error(
                        "Field '" + keyField.getName() + "' was expected to be removed from processed fields."); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }
        compositeId = false;
        // Generate a discriminator (if needed).
        if (!complexType.getSubTypes().isEmpty() && !complexType.isInstantiable()) {
            // <discriminator column="PAYMENT_TYPE" type="string"/>
            Element discriminator = document.createElement("discriminator"); //$NON-NLS-1$
            Attr name = document.createAttribute("column"); //$NON-NLS-1$
            name.setValue(DISCRIMINATOR_NAME);
            discriminator.setAttributeNode(name);
            Attr type = document.createAttribute("type"); //$NON-NLS-1$
            type.setValue("string"); //$NON-NLS-1$
            discriminator.setAttributeNode(type);
            classElement.appendChild(discriminator);
        }
        // Process this type fields
        boolean wasGeneratingConstraints = generateConstrains;
        try {
            if (complexType.getName().startsWith("X_")) { //$NON-NLS-1$
                Integer usageNumber = complexType.<Integer>getData(TypeMapping.USAGE_NUMBER);
                // TMDM-8283: Don't turn on constraint generation even if reusable type is used only once.
                generateConstrains = generateConstrains && (usageNumber == null || usageNumber <= 1);
            }
            for (FieldMetadata currentField : allFields) {
                Element child = currentField.accept(this);
                if (child == null) {
                    throw new IllegalArgumentException(
                            "Field type " + currentField.getClass().getName() + " is not supported."); //$NON-NLS-1$ //$NON-NLS-2$
                }
                classElement.appendChild(child);
            }
        } finally {
            generateConstrains = wasGeneratingConstraints;
        }
        // Sub types
        generatorSubType(complexType, classElement);
    }
    tableNames.pop();

    return classElement;
}