Java Code Examples for org.w3c.dom.Node#getAttributes()

The following examples show how to use org.w3c.dom.Node#getAttributes() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private final void processRecordFilter(final Document doc) {

      final NodeList nodeList = doc.getElementsByTagName(NDCTEXTFILTER);

      // there is only one value stored
      final Node n = nodeList.item(0);
      // add check for backwards compatibility  as this feature was added in
      // version 1.2
      if (n == null) {
         return;
      }

      final NamedNodeMap map = n.getAttributes();
      final String text = getValue(map, NAME);

      if (text == null || text.isEmpty()) {
         return;
      }
      _monitor.setNDCLogRecordFilter(text);
   }
 
Example 2
private void mergeStandardTextNode(Node node)
    throws IIOInvalidTreeException {
    // Convert to comments.  For the moment ignore the encoding issue.
    // Ignore keywords, language, and encoding (for the moment).
    // If compression tag is present, use only entries with "none".
    NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        NamedNodeMap attrs = child.getAttributes();
        Node comp = attrs.getNamedItem("compression");
        boolean copyIt = true;
        if (comp != null) {
            String compString = comp.getNodeValue();
            if (!compString.equals("none")) {
                copyIt = false;
            }
        }
        if (copyIt) {
            String value = attrs.getNamedItem("value").getNodeValue();
            COMMarkerSegment com = new COMMarkerSegment(value);
            insertCOMMarkerSegment(com);
        }
    }
}
 
Example 3
Source Project: netbeans   File: DomainEditor.java    License: Apache License 2.0 6 votes vote down vote up
private boolean updateWithSampleDataSource(Document domainDoc){
    boolean sampleExists = false;
    NodeList dataSourceNodeList = domainDoc.getElementsByTagName(CONST_JDBC);
    for(int i=0; i<dataSourceNodeList.getLength(); i++){
        Node dsNode = dataSourceNodeList.item(i);
        NamedNodeMap dsAttrMap = dsNode.getAttributes();
        String jndiName = dsAttrMap.getNamedItem(CONST_JNDINAME).getNodeValue();
        if(jndiName.equals(SAMPLE_DATASOURCE)) {
            sampleExists = true;
        }
    }
    if(!sampleExists) {
        return createSampleDatasource(domainDoc);
    }
    return true;
}
 
Example 4
@Override
public String getText(Object element) {
    if(element instanceof Node){
        Node node = (Node) element;
        NamedNodeMap attributes = node.getAttributes();
        StringBuilder sb = new StringBuilder();
        sb.append("<");
        sb.append(node.getNodeName());
        for (int i = 0; i < attributes.getLength(); i++) {
            Node item = attributes.item(i);
            sb.append(' ');
            sb.append(item.getNodeName());
            sb.append("=\"");
            sb.append(item.getNodeValue());
            sb.append("\"");
        }
        sb.append(">");
        return "<"+node.getNodeName()+">";
    }else if (element instanceof NodeEnd) {
        return "</"+((NodeEnd) element).getStartNode().getNodeName()+">";
    }
    return super.getText(element);
}
 
Example 5
protected void walkDOMAttr(NodeList nodes, StringBuilder sb) {
    for (int i = 0; i < nodes.getLength(); i++) {
        Node n = nodes.item(i);
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            if (LOG.isDebugEnabled())
                LOG.debug(n.getNodeName());
        }
        if (n.hasAttributes()) {
            ArrayList<String> list = new ArrayList<String>();
            sb.append(n.getNodeName()).append("#\n");
            NamedNodeMap nnMap = n.getAttributes();
            for (int j = 0; j < nnMap.getLength(); j++) {
                Attr attr = (Attr) nnMap.item(j);
                String tmp = "@" + attr.getName() + "=" + attr.getValue();
                list.add(tmp);
                list.add("#isSpecified:" + attr.getSpecified() + "\n");
            }
            Collections.sort(list);
            sb.append(list.toString());
        }
        sb.append("\n");
        if (n.hasChildNodes()) {
            walkDOMAttr(n.getChildNodes(), sb);
        }
    }
}
 
Example 6
void updateFromNativeNode(Node node, boolean fromScratch)
    throws IIOInvalidTreeException {
    NamedNodeMap attrs = node.getAttributes();
    int value = getAttributeValue(node, attrs, "process", 0, 2, false);
    tag = (value != -1) ? value+JPEG.SOF0 : tag;
    // If samplePrecision is present, it must be 8.
    // This just checks.  We don't bother to assign the value.
    value = getAttributeValue(node, attrs, "samplePrecision", 8, 8, false);
    value = getAttributeValue(node, attrs, "numLines", 0, 65535, false);
    numLines = (value != -1) ? value : numLines;
    value = getAttributeValue(node, attrs, "samplesPerLine", 0, 65535, false);
    samplesPerLine = (value != -1) ? value : samplesPerLine;
    int numComponents = getAttributeValue(node, attrs, "numFrameComponents",
                                          1, 4, false);
    NodeList children = node.getChildNodes();
    if (children.getLength() != numComponents) {
        throw new IIOInvalidTreeException
            ("numFrameComponents must match number of children", node);
    }
    componentSpecs = new ComponentSpec [numComponents];
    for (int i = 0; i < numComponents; i++) {
        componentSpecs[i] = new ComponentSpec(children.item(i));
    }
}
 
Example 7
protected void access() {
    if (!accessedMessage) {
        try {
            envelopeAttrs = sm.getSOAPPart().getEnvelope().getAttributes();
            Node body = sm.getSOAPBody();
            bodyAttrs = body.getAttributes();
            soapVersion = SOAPVersion.fromNsUri(body.getNamespaceURI());
            //cature all the body elements
            bodyParts = DOMUtil.getChildElements(body);
            //we treat payload as the first body part
            payload = bodyParts.size() > 0 ? bodyParts.get(0) : null;
            // hope this is correct. Caching the localname and namespace of the payload should be fine
            // but what about if a Handler replaces the payload with something else? Weel, may be it
            // will be error condition anyway
            if (payload != null) {
                payloadLocalName = payload.getLocalName();
                payloadNamespace = payload.getNamespaceURI();
            }
            accessedMessage = true;
        } catch (SOAPException e) {
            throw new WebServiceException(e);
        }
    }
}
 
Example 8
/**
 * Fills the Atributes of an EXISTING Record with the values received in XML
 * @param AttrsNode XML Node to import
 * @param R Record to fill
 * @return the Filled Record
 * @throws PDException  In any error
 */
static Record FillFromXML(Node AttrsNode, Record R) throws PDException
{
if (PDLog.isDebug())
    PDLog.Debug("Record.FillFromXML>:R="+R+"AttrsNode="+AttrsNode);        
NodeList AttrLst = AttrsNode.getChildNodes();
for (int j = 0; j < AttrLst.getLength(); j++)
    {
    Node Attr = AttrLst.item(j);
    if (Attr.getNodeName().equalsIgnoreCase("attr"))  
        {
        NamedNodeMap XMLattributes = Attr.getAttributes();
        Node XMLAttrName = XMLattributes.getNamedItem("Name");
        String AttrName=XMLAttrName.getNodeValue();
        String Value=DriverGeneric.DeCodif(Attr.getTextContent());        
        Attribute At=R.getAttr(AttrName);
        if (At!=null)
            At.ImportXML(Value);
        }
    }
if (PDLog.isDebug())
    PDLog.Debug("Record.FillFromXML<");        
return(R);
}
 
Example 9
Source Project: L2jOrg   File: ItemEngine.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void parseWeapon(Node weaponNode) {
    var attrs = weaponNode.getAttributes();
    var weapon = new Weapon(parseInt(attrs, "id"), parseString(attrs, "name"), parseEnum(attrs, WeaponType.class, "type"), parseEnum(attrs, BodyPart.class, "body-part"));

    weapon.setIcon(parseString(attrs, "icon"));
    weapon.setDisplayId(parseInt(attrs, "display-id", weapon.getId()));
    weapon.setMagic(parseBoolean(attrs, "magic"));

    forEach(weaponNode,node ->{
        switch (node.getNodeName()) {
            case "attributes" -> parseWeaponAttributes(weapon, node);
            case "crystal" -> parseCrystalType(weapon, node);
            case "damage" -> parseWeaponDamage(weapon, node);
            case "consume" -> parseWeaponConsume(weapon, node);
            case "restriction" -> parseItemRestriction(weapon, node);
            case "conditions" -> parseItemCondition(weapon, node);
            case "stats" -> parseItemStats(weapon, node);
            case "skills"-> parseItemSkills(weapon, node);
        }
    });

    items.put(weapon.getId(), weapon);
}
 
Example 10
public List getRuleExtensionValues() {
    List extensionValues = new ArrayList();

    XPath xpath = XPathHelper.newXPath();
    try {
        NodeList nodes = getFields(xpath, getConfigXML(), new String[] { "ALL", "RULE" });
        for (int i = 0; i < nodes.getLength(); i++) {
            Node field = nodes.item(i);
            NamedNodeMap fieldAttributes = field.getAttributes();
            String fieldName = fieldAttributes.getNamedItem("name").getNodeValue();
            Map map = getParamMap();
            if (map != null && !org.apache.commons.lang.StringUtils.isEmpty((String) map.get(fieldName))) {
                RuleExtensionValue value = new RuleExtensionValue();
                value.setKey(fieldName);
                value.setValue((String) map.get(fieldName));
                extensionValues.add(value);
            }
        }
    } catch (XPathExpressionException e) {
        LOG.error("error in getRuleExtensionValues ", e);
        throw new RuntimeException("Error trying to find xml content with xpath expression", e);
    }
    return extensionValues;
}
 
Example 11
/**
 * Given a prefix and a Context Node, get the corresponding namespace.
 * Warning: This will not work correctly if namespaceContext
 * is an attribute node.
 * @param prefix Prefix to resolve.
 * @param namespaceContext Node from which to start searching for a
 * xmlns attribute that binds a prefix to a namespace.
 * @return Namespace that prefix resolves to, or null if prefix
 * is not bound.
 */
public String getNamespaceForPrefix(String prefix,
                                  org.w3c.dom.Node namespaceContext) {
    Node parent = namespaceContext;
    String namespace = null;

    if (prefix.equals("xml")) {
        namespace = S_XMLNAMESPACEURI;
    } else {
        int type;

        while ((null != parent) && (null == namespace)
            && (((type = parent.getNodeType()) == Node.ELEMENT_NODE)
                || (type == Node.ENTITY_REFERENCE_NODE))) {

            if (type == Node.ELEMENT_NODE) {
                NamedNodeMap nnm = parent.getAttributes();

                for (int i = 0; i < nnm.getLength(); i++) {
                    Node attr = nnm.item(i);
                    String aname = attr.getNodeName();
                    boolean isPrefix = aname.startsWith("xmlns:");

                    if (isPrefix || aname.equals("xmlns")) {
                        int index = aname.indexOf(':');
                        String p =isPrefix ?aname.substring(index + 1) :"";

                        if (p.equals(prefix)) {
                            namespace = attr.getNodeValue();
                            break;
                        }
                    }
                }
            }

            parent = parent.getParentNode();
        }
    }
    return namespace;
}
 
Example 12
private static ModelProperty createModelProperty(Map<QName, Document> modelMap, Node propEl) {
	ModelProperty property = new ModelProperty();
	NamedNodeMap propAttrs = propEl.getAttributes();
	property.setName(propAttrs.getNamedItem("name").getNodeValue());
	Node isArrayNode = propAttrs.getNamedItem("array");
	if (isArrayNode != null) {
		property.setArray("yes".equals(isArrayNode.getNodeValue()));
	} else {
		property.setArray(false);
	}
	Node isPrimitiveNode = propAttrs.getNamedItem("primitive");
	boolean primitive;
	if (isPrimitiveNode != null) {
		primitive = "yes".equals(isPrimitiveNode.getNodeValue());
	} else {
		primitive = false;
	}
	Node isSimpleNode = propAttrs.getNamedItem("simple");
	boolean simple;
	if (isSimpleNode != null) {
		simple = "yes".equals(isSimpleNode.getNodeValue());
	} else {
		simple = false;
	}
	ModelBean type = null;
	if (!primitive && !simple) {
		type = createModelBean(modelMap,
				new QName(propAttrs.getNamedItem("nsuri").getNodeValue(), 
						propAttrs.getNamedItem("shorttypename").getNodeValue()));
	}
	if (type != null) {
		property.setType(type);
	} else {
		property.setSimpleType(propAttrs.getNamedItem("shorttypename").getNodeValue());
	}
	return property;
}
 
Example 13
Source Project: Hive-XML-SerDe   File: JavaXmlProcessor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the object value for the given field name and node
 * 
 * @param node
 *            the node
 * @param fieldName
 *            the field name
 * @return the object value for the given field name and node
 */
private Object getObjectValue(Node node, String fieldName) {
    // we have to take into account the fact that fieldName will be in the lower case
    if (node != null) {
        String name = node.getLocalName();
        switch (node.getNodeType()) {
            case Node.ATTRIBUTE_NODE:
                return name.equalsIgnoreCase(fieldName) ? node : null;
            case Node.ELEMENT_NODE: {
                if (name.equalsIgnoreCase(fieldName)) {
                    return new NodeArray(node.getChildNodes());
                } else {
                    NamedNodeMap namedNodeMap = node.getAttributes();
                    for (int attributeIndex = 0; attributeIndex < namedNodeMap.getLength(); ++attributeIndex) {
                        Node attribute = namedNodeMap.item(attributeIndex);
                        if (attribute.getLocalName().equalsIgnoreCase(fieldName)) {
                            return attribute;
                        }
                    }
                    return null;
                }
            }
            default:
                return null;
        }
    }
    return null;
}
 
Example 14
Qtable(Node node) throws IIOInvalidTreeException {
    if (node.getNodeName().equals("dqtable")) {
        NamedNodeMap attrs = node.getAttributes();
        int count = attrs.getLength();
        if ((count < 1) || (count > 2)) {
            throw new IIOInvalidTreeException
                ("dqtable node must have 1 or 2 attributes", node);
        }
        elementPrecision = 0;
        tableID = getAttributeValue(node, attrs, "qtableId", 0, 3, true);
        if (node instanceof IIOMetadataNode) {
            IIOMetadataNode ourNode = (IIOMetadataNode) node;
            JPEGQTable table = (JPEGQTable) ourNode.getUserObject();
            if (table == null) {
                throw new IIOInvalidTreeException
                    ("dqtable node must have user object", node);
            }
            data = table.getTable();
        } else {
            throw new IIOInvalidTreeException
                ("dqtable node must have user object", node);
        }
    } else {
        throw new IIOInvalidTreeException
            ("Invalid node, expected dqtable", node);
    }
}
 
Example 15
Source Project: onos   File: MockDriverHandler.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public MockDriverHandler(Class<? extends AbstractDriverLoader> loaderClass, String behaviorSpec,
        DeviceId mockDeviceId, CoreService mockCoreService, DeviceService mockDeviceService) {

    // Had to split into declaration and initialization to make stylecheck happy
    // else line was considered too long
    // and auto format couldn't be tweak to make it correct
    Map<Class<? extends Behaviour>, Class<? extends Behaviour>> behaviours;
    behaviours = new HashMap<Class<? extends Behaviour>, Class<? extends Behaviour>>();

    try {
        String data = Resources.toString(Resources.getResource(loaderClass, behaviorSpec), StandardCharsets.UTF_8);
        InputStream resp = IOUtils.toInputStream(data, StandardCharsets.UTF_8);
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document document = builder.parse(resp);

        XPath xp = XPathFactory.newInstance().newXPath();
        NodeList list = (NodeList) xp.evaluate("//behaviour", document, XPathConstants.NODESET);
        for (int i = 0; i < list.getLength(); i += 1) {
            Node node = list.item(i);
            NamedNodeMap attrs = node.getAttributes();
            Class<? extends Behaviour> api = (Class<? extends Behaviour>) Class
                    .forName(attrs.getNamedItem("api").getNodeValue());
            Class<? extends Behaviour> impl = (Class<? extends Behaviour>) Class
                    .forName(attrs.getNamedItem("impl").getNodeValue());
            behaviours.put(api, impl);
        }
        init(behaviours, mockDeviceId, mockCoreService, mockDeviceService);
    } catch (Exception e) {
        fail(e.toString());
    }
}
 
Example 16
Source Project: javaide   File: Svg2Vector.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Convert polygon element into a path.
 */
private static void extractPolyItem(SvgTree avg, SvgLeafNode child, Node currentGroupNode) {
    logger.log(Level.FINE, "Rect found" + currentGroupNode.getTextContent());
    if (currentGroupNode.getNodeType() == Node.ELEMENT_NODE) {

        NamedNodeMap a = currentGroupNode.getAttributes();
        int len = a.getLength();

        for (int itemIndex = 0; itemIndex < len; itemIndex++) {
            Node n = a.item(itemIndex);
            String name = n.getNodeName();
            String value = n.getNodeValue();
            if (name.equals(SVG_STYLE)) {
                addStyleToPath(child, value);
            } else if (presentationMap.containsKey(name)) {
                child.fillPresentationAttributes(name, value);
            } else if (name.equals(SVG_POINTS)) {
                PathBuilder builder = new PathBuilder();
                String[] split = value.split("[\\s,]+");
                float baseX = Float.parseFloat(split[0]);
                float baseY = Float.parseFloat(split[1]);
                builder.absoluteMoveTo(baseX, baseY);
                for (int j = 2; j < split.length; j += 2) {
                    float x = Float.parseFloat(split[j]);
                    float y = Float.parseFloat(split[j + 1]);
                    builder.relativeLineTo(x - baseX, y - baseY);
                    baseX = x;
                    baseY = y;
                }
                builder.relativeClose();
                child.setPathData(builder.toString());
            }
        }
    }
}
 
Example 17
private ItemHolder parseItemInfo(Node itemInfoNode) {
    var attributes = itemInfoNode.getAttributes();
    var itemId = parseInteger(attributes, "id");
    var count = parseInteger(attributes, "count");

    final ItemTemplate item = ItemEngine.getInstance().getTemplate(itemId);
    if (isNull(item)) {
        LOGGER.error("Item template does not exists for itemId: {} in product id {}", itemId, itemInfoNode.getAttributes().getNamedItem("id"));
        return null;
    }

    return new ItemHolder(itemId, count);
}
 
Example 18
private static String getAttribute(Node node, String attr){
	if( ! node.hasAttributes())
		return null;

	NamedNodeMap atts = node.getAttributes();

	if ( atts == null)
		return null;

	Node att = atts.getNamedItem(attr);
	if ( att == null)
		return null;

	String value = att.getTextContent();

	return value;

}
 
Example 19
/**
 * Merge the given DHT node into the marker sequence.  If there already
 * exist DHT marker segments in the sequence, then each table in the
 * node replaces the first table, in any DHT segment, with the same
 * table class and table id.  If none of the existing DHT segments contain
 * a table with the same class and id, then the table is added to the last
 * existing DHT segment.
 * If there are no DHT segments, then a new one is created and added
 * as follows:
 * If there are DQT segments, the new DHT segment is inserted immediately
 * following the last DQT segment.
 * If there are no DQT segments, the new DHT segment is inserted before
 * an SOF segment, if there is one.
 * If there is no SOF segment, the new DHT segment is inserted before
 * the first SOS segment, if there is one.
 * If there is no SOS segment, the new DHT segment is added to the end
 * of the sequence.
 */
private void mergeDHTNode(Node node) throws IIOInvalidTreeException {
    // First collect any existing DQT nodes into a local list
    ArrayList oldDHTs = new ArrayList();
    Iterator iter = markerSequence.iterator();
    while (iter.hasNext()) {
        MarkerSegment seg = (MarkerSegment) iter.next();
        if (seg instanceof DHTMarkerSegment) {
            oldDHTs.add(seg);
        }
    }
    if (!oldDHTs.isEmpty()) {
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            NamedNodeMap attrs = child.getAttributes();
            int childID = MarkerSegment.getAttributeValue(child,
                                                          attrs,
                                                          "htableId",
                                                          0, 3,
                                                          true);
            int childClass = MarkerSegment.getAttributeValue(child,
                                                             attrs,
                                                             "class",
                                                             0, 1,
                                                             true);
            DHTMarkerSegment dht = null;
            int tableIndex = -1;
            for (int j = 0; j < oldDHTs.size(); j++) {
                DHTMarkerSegment testDHT = (DHTMarkerSegment) oldDHTs.get(j);
                for (int k = 0; k < testDHT.tables.size(); k++) {
                    DHTMarkerSegment.Htable testTable =
                        (DHTMarkerSegment.Htable) testDHT.tables.get(k);
                    if ((childID == testTable.tableID) &&
                        (childClass == testTable.tableClass)) {
                        dht = testDHT;
                        tableIndex = k;
                        break;
                    }
                }
                if (dht != null) break;
            }
            if (dht != null) {
                dht.tables.set(tableIndex, dht.getHtableFromNode(child));
            } else {
                dht = (DHTMarkerSegment) oldDHTs.get(oldDHTs.size()-1);
                dht.tables.add(dht.getHtableFromNode(child));
            }
        }
    } else {
        DHTMarkerSegment newGuy = new DHTMarkerSegment(node);
        int lastDQT = findMarkerSegmentPosition(DQTMarkerSegment.class, false);
        int firstSOF = findMarkerSegmentPosition(SOFMarkerSegment.class, true);
        int firstSOS = findMarkerSegmentPosition(SOSMarkerSegment.class, true);
        if (lastDQT != -1) {
            markerSequence.add(lastDQT+1, newGuy);
        } else if (firstSOF != -1) {
            markerSequence.add(firstSOF, newGuy);
        } else if (firstSOS != -1) {
            markerSequence.add(firstSOS, newGuy);
        } else {
            markerSequence.add(newGuy);
        }
    }
}
 
Example 20
JFIFExtensionMarkerSegment(Node node) throws IIOInvalidTreeException {
    super(JPEG.APP0);
    NamedNodeMap attrs = node.getAttributes();
    if (attrs.getLength() > 0) {
        code = getAttributeValue(node,
                                 attrs,
                                 "extensionCode",
                                 THUMB_JPEG,
                                 THUMB_RGB,
                                 false);
        if (code == THUMB_UNASSIGNED) {
        throw new IIOInvalidTreeException
            ("invalid extensionCode attribute value", node);
        }
    } else {
        code = THUMB_UNASSIGNED;
    }
    // Now the child
    if (node.getChildNodes().getLength() != 1) {
        throw new IIOInvalidTreeException
            ("app0JFXX node must have exactly 1 child", node);
    }
    Node child = node.getFirstChild();
    String name = child.getNodeName();
    if (name.equals("JFIFthumbJPEG")) {
        if (code == THUMB_UNASSIGNED) {
            code = THUMB_JPEG;
        }
        thumb = new JFIFThumbJPEG(child);
    } else if (name.equals("JFIFthumbPalette")) {
        if (code == THUMB_UNASSIGNED) {
            code = THUMB_PALETTE;
        }
        thumb = new JFIFThumbPalette(child);
    } else if (name.equals("JFIFthumbRGB")) {
        if (code == THUMB_UNASSIGNED) {
            code = THUMB_RGB;
        }
        thumb = new JFIFThumbRGB(child);
    } else {
        throw new IIOInvalidTreeException
            ("unrecognized app0JFXX child node", node);
    }
}