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:gov.sbs.blame.BlamePlugin.java

private Map<String, List<PmdViolation>> getPmdViolations(File pmdFile)
        throws SAXException, IOException, ParserConfigurationException {
    Map<String, List<PmdViolation>> vMap = new HashMap<String, List<PmdViolation>>();

    String fileRoot = new File("").getAbsolutePath();

    File fXmlFile = new File("target/pmd.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);

    // optional, but recommended
    // read this -
    // http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
    doc.getDocumentElement().normalize();

    NodeList filesList = doc.getElementsByTagName("file");

    for (int fileCounter = 0; fileCounter < filesList.getLength(); fileCounter++) {

        Element fileNode = (Element) filesList.item(fileCounter);
        String fileName = fileNode.getAttributes().getNamedItem("name").getNodeValue();

        // Modify the path to what GIT will understand
        fileName = fileName.replace(fileRoot + "/", "");

        Map<Integer, String> lineAndUser = getWhoDidIt("git blame " + fileName);

        if (!vMap.containsKey(fileName)) {
            vMap.put(fileName, new ArrayList<PmdViolation>());
        }/*from ww w  .j a  va2 s .com*/

        NodeList violationsList = fileNode.getElementsByTagName("violation");

        for (int violationCounter = 0; violationCounter < violationsList.getLength(); violationCounter++) {
            Node violationNode = violationsList.item(violationCounter);

            String startLine = violationNode.getAttributes().getNamedItem("beginline").getNodeValue();
            String endLine = violationNode.getAttributes().getNamedItem("endline").getNodeValue();
            String rule = violationNode.getAttributes().getNamedItem("rule").getNodeValue();
            String msg = violationNode.getTextContent();

            PmdViolation pmdViolation = new PmdViolation(fileName, new Integer(startLine), new Integer(endLine),
                    rule, msg);

            pmdViolation.setViolator(lineAndUser.get(pmdViolation.getStart()));
            vMap.get(fileName).add(pmdViolation);
        }
    }

    return vMap;
}

From source file:eu.scenari.gephi.importer.ScenariConnector.java

public boolean initConnection() {
    try {//  w w  w .  j a  v  a  2s  .  c  om
        String vXmlDocument = sendRequest(GET_WSP_LIST);
        Document vDoc = ImportUtils.getXMLDocument(new ByteArrayInputStream(vXmlDocument.getBytes()));
        Element vRootElement = vDoc.getDocumentElement();
        NodeList vNodeList = vRootElement.getChildNodes();
        fWorkspacesCodes = new ArrayList<String>();
        fWorkspacesLabels = new ArrayList<String>();

        for (int i = 0; i < vNodeList.getLength(); i++) {
            if (vNodeList.item(i).getNodeType() == Node.ELEMENT_NODE) {
                Element vElement = (Element) vNodeList.item(i);
                if (vElement.getNodeName() != null) {
                    if (vElement.getNodeName().equals("wspProviderProperties")) {
                        if (vElement.getAttributes().getNamedItem("backEnd").getNodeValue().equals("fs"))
                            fOdbBackend = false;
                        else
                            fOdbBackend = true;
                    }
                    if (vElement.getNodeName().equals("wsp")) {
                        String vCode = vElement.getAttributes().getNamedItem("code").getNodeValue();
                        String vLabel;
                        if (!fOdbBackend)
                            vLabel = new String(vCode);
                        else
                            vLabel = vElement.getAttributes().getNamedItem("title").getNodeValue();
                        vLabel += " ("
                                + vElement.getAttributes().getNamedItem("wspTypes").getNodeValue().split(" ")[0]
                                + ")";

                        fWorkspacesCodes.add(vCode);
                        fWorkspacesLabels.add(vLabel);
                    }
                }
            }
        }
        return true;
    } catch (Exception ex) {
        //Exceptions.printStackTrace(ex);            
        return false;
    }
}

From source file:com.espertech.esper.client.ConfigurationParser.java

private static void handlePlugInSingleRow(Configuration configuration, Element element) {
    String name = element.getAttributes().getNamedItem("name").getTextContent();
    String functionClassName = element.getAttributes().getNamedItem("function-class").getTextContent();
    String functionMethodName = element.getAttributes().getNamedItem("function-method").getTextContent();
    ConfigurationPlugInSingleRowFunction.ValueCache valueCache = ConfigurationPlugInSingleRowFunction.ValueCache.DISABLED;
    ConfigurationPlugInSingleRowFunction.FilterOptimizable filterOptimizable = ConfigurationPlugInSingleRowFunction.FilterOptimizable.ENABLED;
    String valueCacheStr = getOptionalAttribute(element, "value-cache");
    if (valueCacheStr != null) {
        valueCache = ConfigurationPlugInSingleRowFunction.ValueCache.valueOf(valueCacheStr.toUpperCase());
    }// w w  w . j av a  2s  . co m
    String filterOptimizableStr = getOptionalAttribute(element, "filter-optimizable");
    if (filterOptimizableStr != null) {
        filterOptimizable = ConfigurationPlugInSingleRowFunction.FilterOptimizable
                .valueOf(filterOptimizableStr.toUpperCase());
    }
    String rethrowExceptionsStr = getOptionalAttribute(element, "rethrow-exceptions");
    boolean rethrowExceptions = false;
    if (rethrowExceptionsStr != null) {
        rethrowExceptions = Boolean.parseBoolean(rethrowExceptionsStr);
    }
    configuration.addPlugInSingleRowFunction(name, functionClassName, functionMethodName, valueCache,
            filterOptimizable, rethrowExceptions);
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static Collection<Attr> listApplicationAttributes(Element element) {
    Collection<Attr> attrs = new ArrayList<Attr>();
    NamedNodeMap attributes = element.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Attr attr = (Attr) attributes.item(i);
        if (isApplicationAttribute(attr)) {
            attrs.add(attr);//from w ww .  ja  v a2  s.c  om
        }
    }
    return attrs;
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

/**
 * Returns map of all namespace declarations from specified element (prefix -> namespace).
 *//*ww  w .ja v a 2 s .  c o m*/
public static Map<String, String> getNamespaceDeclarations(Element element) {
    Map<String, String> nsDeclMap = new HashMap<String, String>();
    NamedNodeMap attributes = element.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Attr attr = (Attr) attributes.item(i);
        if (isNamespaceDefinition(attr)) {
            String prefix = getNamespaceDeclarationPrefix(attr);
            String namespace = getNamespaceDeclarationNamespace(attr);
            nsDeclMap.put(prefix, namespace);
        }
    }
    return nsDeclMap;
}

From source file:com.amalto.core.storage.record.XmlDOMDataRecordReader.java

private void _read(MetadataRepository repository, DataRecord dataRecord, ComplexTypeMetadata type,
        Element element) {
    // TODO Don't use getChildNodes() but getNextSibling() calls (but cause regressions -> see TMDM-5410).
    String tagName = element.getTagName();
    NodeList children = element.getChildNodes();
    NamedNodeMap attributes = element.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        if (!type.hasField(attribute.getNodeName())) {
            continue;
        }// ww  w  .  j  a  v a  2  s  . c  o  m
        FieldMetadata field = type.getField(attribute.getNodeName());
        dataRecord.set(field, StorageMetadataUtils.convert(attribute.getNodeValue(), field));
    }
    for (int i = 0; i < children.getLength(); i++) {
        Node currentChild = children.item(i);
        if (currentChild instanceof Element) {
            Element child = (Element) currentChild;
            if (METADATA_NAMESPACE.equals(child.getNamespaceURI())) {
                DataRecordMetadataHelper.setMetadataValue(dataRecord.getRecordMetadata(), child.getLocalName(),
                        child.getTextContent());
            } else {
                if (!type.hasField(child.getTagName())) {
                    continue;
                }
                FieldMetadata field = type.getField(child.getTagName());
                if (field.getType() instanceof ContainedComplexTypeMetadata) {
                    ComplexTypeMetadata containedType = (ComplexTypeMetadata) field.getType();
                    String xsiType = child.getAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "type"); //$NON-NLS-1$
                    if (xsiType.startsWith("java:")) { //$NON-NLS-1$
                        // Special format for 'java:' type names (used in Castor XML to indicate actual class name)
                        xsiType = ClassRepository.format(StringUtils
                                .substringAfterLast(StringUtils.substringAfter(xsiType, "java:"), ".")); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                    if (!xsiType.isEmpty()) {
                        for (ComplexTypeMetadata subType : containedType.getSubTypes()) {
                            if (subType.getName().equals(xsiType)) {
                                containedType = subType;
                                break;
                            }
                        }
                    }
                    DataRecord containedRecord = new DataRecord(containedType,
                            UnsupportedDataRecordMetadata.INSTANCE);
                    dataRecord.set(field, containedRecord);
                    _read(repository, containedRecord, containedType, child);
                } else if (ClassRepository.EMBEDDED_XML.equals(field.getType().getName())) {
                    try {
                        dataRecord.set(field, Util.nodeToString(element));
                    } catch (TransformerException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    _read(repository, dataRecord, type, child);
                }
            }
        } else if (currentChild instanceof Text) {
            StringBuilder builder = new StringBuilder();
            for (int j = 0; j < element.getChildNodes().getLength(); j++) {
                String nodeValue = element.getChildNodes().item(j).getNodeValue();
                if (nodeValue != null) {
                    builder.append(nodeValue.trim());
                }
            }
            String textContent = builder.toString();
            if (!textContent.isEmpty()) {
                FieldMetadata field = type.getField(tagName);
                if (field instanceof ReferenceFieldMetadata) {
                    ComplexTypeMetadata actualType = ((ReferenceFieldMetadata) field).getReferencedType();
                    String mdmType = element.getAttributeNS(SkipAttributeDocumentBuilder.TALEND_NAMESPACE,
                            "type"); //$NON-NLS-1$
                    if (!mdmType.isEmpty()) {
                        actualType = repository.getComplexType(mdmType);
                    }
                    if (actualType == null) {
                        throw new IllegalArgumentException("Type '" + mdmType + "' does not exist.");
                    }
                    dataRecord.set(field, StorageMetadataUtils.convert(textContent, field, actualType));
                } else {
                    dataRecord.set(field, StorageMetadataUtils.convert(textContent, field, type));
                }
            }
        }
    }
}

From source file:com.amalto.workbench.actions.XSDEditParticleAction.java

@Override
public IStatus doAction() {
    try {/* w w w .ja v a 2s  . c  o m*/
        IStructuredSelection selection = (IStructuredSelection) page.getTreeViewer().getSelection();

        String originalXpath = getOriginalXpath();
        String entity = originalXpath.substring(0, originalXpath.indexOf("/")); //$NON-NLS-1$

        selParticle = (XSDParticle) selection.getFirstElement();

        if (!(selParticle.getTerm() instanceof XSDElementDeclaration)) {
            return Status.CANCEL_STATUS;
        }

        XSDElementDeclaration decl = (XSDElementDeclaration) selParticle.getContent();

        XSDElementDeclaration ref = null;
        if (decl.isElementDeclarationReference()) {
            // it is a ref
            ref = decl.getResolvedElementDeclaration();
        }

        EList eDecls = decl.getSchema().getElementDeclarations();

        ArrayList<String> elementDeclarations = new ArrayList<String>();
        for (Iterator iter = eDecls.iterator(); iter.hasNext();) {
            XSDElementDeclaration d = (XSDElementDeclaration) iter.next();
            if (d.getTargetNamespace() != null
                    && d.getTargetNamespace().equals(IConstants.DEFAULT_NAME_SPACE)) {
                continue;
            }

            if (!d.getQName().equals(entity)) {
                elementDeclarations.add(
                        d.getQName() + (d.getTargetNamespace() != null ? " : " + d.getTargetNamespace() : "")); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }
        elementDeclarations.add(""); //$NON-NLS-1$

        XSDIdentityConstraintDefinition identify = null;

        XSDXPathDefinition keyPath = null;
        List<Object> keyInfo = Util.getKeyInfo(decl);
        boolean isPK = false;
        if (keyInfo != null && keyInfo.size() > 0) {
            identify = (XSDIdentityConstraintDefinition) keyInfo.get(0);
            keyPath = (XSDXPathDefinition) keyInfo.get(1);
            isPK = true;
        }
        initEleName = decl.getName();
        dialog = new BusinessElementInputDialog(this, page.getSite().getShell(),
                Messages.XSDEditParticleAction_InputDialogTitle, decl.getName(),
                ref == null ? null : ref.getQName(), elementDeclarations, selParticle.getMinOccurs(),
                selParticle.getMaxOccurs(), false, isPK);
        dialog.setBlockOnOpen(true);
        int ret = dialog.open();
        if (ret == Window.CANCEL) {
            return Status.CANCEL_STATUS;
        }
        if (keyPath != null) {
            identify.getFields().remove(keyPath);
        }
        // find reference
        XSDElementDeclaration newRef = null;
        if (!"".equals(refName.trim())) { //$NON-NLS-1$
            newRef = Util.findReference(refName, schema);
            if (newRef == null) {
                MessageDialog.openError(this.page.getSite().getShell(), Messages._Error,
                        Messages.bind(Messages.XSDEditParticleAction_ErrorMsg, refName));
                return Status.CANCEL_STATUS;
            }
        } // ref

        // update validation rule
        Set<String> paths = new HashSet<String>();
        Util.collectElementPaths((IStructuredContentProvider) page.getElementsViewer().getContentProvider(),
                page.getSite(), selParticle, paths, null);
        //

        decl.setName("".equals(this.elementName) ? null : this.elementName); //$NON-NLS-1$
        if (keyPath != null) {
            XSDFactory factory = XSDSchemaBuildingTools.getXSDFactory();
            XSDXPathDefinition field = factory.createXSDXPathDefinition();
            field.setVariety(keyPath.getVariety());
            field.setValue(elementName);
            identify.getFields().add(field);
        }

        if (newRef != null) {
            decl.setResolvedElementDeclaration(newRef);
            decl.setTypeDefinition(null);
            Element elem = decl.getElement();
            if (elem.getAttributes().getNamedItem("type") != null) {
                elem.getAttributes().removeNamedItem("type");//$NON-NLS-1$
            }
            decl.updateElement();
        } else if (ref != null) {
            // fliu
            // no more element declarations --> we create a new Declaration with String simpleType definition
            // instead
            // FIXME: dereferecning and element is buggy

            XSDFactory factory = XSDSchemaBuildingTools.getXSDFactory();
            XSDElementDeclaration newD = factory.createXSDElementDeclaration();
            newD.setName(this.elementName);
            newD.updateElement();
            XSDSimpleTypeDefinition stringType = ((SchemaTreeContentProvider) page.getTreeViewer()
                    .getContentProvider()).getXsdSchema().getSchemaForSchema()
                            .resolveSimpleTypeDefinition(XSDConstants.SCHEMA_FOR_SCHEMA_URI_2001, "string"); //$NON-NLS-1$

            newD.setTypeDefinition(stringType);
            if (selParticle.getContainer() instanceof XSDModelGroup) {
                XSDModelGroup group = ((XSDModelGroup) selParticle.getContainer());
                ((XSDModelGroup) selParticle.getContainer()).getContents().remove(selParticle);
                selParticle = factory.createXSDParticle();
                selParticle.setContent(newD);
                group.getContents().add(selParticle);
            }
        }

        if (Util.changeElementTypeToSequence(decl, maxOccurs) == Status.CANCEL_STATUS) {
            return Status.CANCEL_STATUS;
        }

        selParticle.setMinOccurs(this.minOccurs);
        if (maxOccurs > -1) {
            selParticle.setMaxOccurs(this.maxOccurs);
        } else {
            if (selParticle.getElement().getAttributeNode("maxOccurs") != null) {
                selParticle.getElement().getAttributeNode("maxOccurs").setNodeValue("unbounded");//$NON-NLS-1$//$NON-NLS-2$
            } else {
                selParticle.getElement().setAttribute("maxOccurs", "unbounded");//$NON-NLS-1$//$NON-NLS-2$
            }
        }

        selParticle.updateElement();

        updateReference(originalXpath);

        if (elementExAdapter != null) {
            elementExAdapter.renameElement(decl.getSchema(), paths, decl.getName());
        }
        if (mapinfoExAdapter != null) {
            mapinfoExAdapter.renameElementMapinfo(paths, decl.getName());
        }

        page.refresh();
        page.markDirty();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        MessageDialog.openError(page.getSite().getShell(), Messages._Error,
                Messages.bind(Messages.XSDEditParticleAction_ErrorMsg1, e.getLocalizedMessage()));
        return Status.CANCEL_STATUS;
    }

    return Status.OK_STATUS;
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static void setNamespaceDeclaration(Element element, String prefix, String namespaceUri) {
    Document doc = element.getOwnerDocument();
    NamedNodeMap attributes = element.getAttributes();
    Attr attr;//from   w  ww  .  j av a  2s .co  m
    if (prefix == null || prefix.isEmpty()) {
        // default namespace
        attr = doc.createAttributeNS(W3C_XML_SCHEMA_XMLNS_URI, W3C_XML_SCHEMA_XMLNS_PREFIX);
    } else {
        attr = doc.createAttributeNS(W3C_XML_SCHEMA_XMLNS_URI, W3C_XML_SCHEMA_XMLNS_PREFIX + ":" + prefix);
    }
    checkValidXmlChars(namespaceUri);
    attr.setValue(namespaceUri);
    attributes.setNamedItem(attr);
}

From source file:eionet.gdem.conversion.odf.ODFSpreadsheetAnalyzer.java

/**
 * Finds the namespace prefixes associated with OpenDocument, Dublin Core, and OpenDocument meta elements.
 * This function presumes that all the namespaces are in the root element. If they aren't, this breaks.
 *
 * @param rootElement//from   ww  w  .  ja  v  a  2s  .c om
 *            the root element of the document.
 */
protected void findNamespaces(Element rootElement) {
    NamedNodeMap attributes;
    Node node;
    String value;

    attributes = rootElement.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        node = attributes.item(i);
        value = node.getNodeValue();

        if (value.equals(DC_URI)) {
            dcNamespace = extractNamespace(node.getNodeName());
        } else if (value.equals(TABLE_URI)) {
            tableNamespace = extractNamespace(node.getNodeName());
        } else if (value.equals(TEXT_URI)) {
            textNamespace = extractNamespace(node.getNodeName());
        } else if (value.equals(OPENDOCUMENT_URI)) {
            officeNamespace = extractNamespace(node.getNodeName());
        }
    }
}

From source file:com.sqewd.os.maracache.core.Config.java

private ConfigPath load(ConfigNode parent, Element elm) throws ConfigException {
    if (parent instanceof ConfigPath) {
        // Check if there are any attributes.
        // Attributes are treated as Value nodes.
        if (elm.hasAttributes()) {
            NamedNodeMap map = elm.getAttributes();
            if (map.getLength() > 0) {
                for (int ii = 0; ii < map.getLength(); ii++) {
                    Node n = map.item(ii);
                    ((ConfigPath) parent).addValueNode(n.getNodeName(), n.getNodeValue());
                }/*w w w .j  av a  2 s .  com*/
            }
        }
        if (elm.hasChildNodes()) {
            NodeList children = elm.getChildNodes();
            for (int ii = 0; ii < children.getLength(); ii++) {
                Node cn = children.item(ii);
                if (cn.getNodeType() == Node.ELEMENT_NODE) {
                    Element e = (Element) cn;
                    if (e.hasChildNodes()) {
                        int nc = 0;
                        for (int jj = 0; jj < e.getChildNodes().getLength(); jj++) {
                            Node ccn = e.getChildNodes().item(jj);
                            // Read the text node if there is any.
                            if (ccn.getNodeType() == Node.TEXT_NODE) {
                                String n = e.getNodeName();
                                String v = ccn.getNodeValue();
                                if (!StringUtils.isEmpty(v.trim()))
                                    ((ConfigPath) parent).addValueNode(n, v);
                                nc++;
                            }
                        }
                        // Make sure this in not a text only node.
                        if (e.getChildNodes().getLength() > nc) {
                            // Check if this is a parameter node. Parameters are treated differently.
                            if (e.getNodeName().compareToIgnoreCase(ConfigParams.NODE_NAME) == 0) {
                                ConfigParams cp = ((ConfigPath) parent).addParamNode();
                                setParams(cp, e);
                            } else {
                                ConfigPath cp = ((ConfigPath) parent).addPathNode(e.getNodeName());
                                load(cp, e);
                            }
                        }
                    }
                }
            }
        }
    }
    return (ConfigPath) parent;
}