Example usage for org.w3c.dom Element hasAttribute

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

Introduction

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

Prototype

public boolean hasAttribute(String name);

Source Link

Document

Returns true when an attribute with a given name is specified on this element or has a default value, false otherwise.

Usage

From source file:com.microsoft.tfs.core.clients.sharepoint.WSSDocumentLibrary.java

private String calculateASCIIName(final TFSTeamProjectCollection connection, final Element node) {
    // Attempt to work out the ascii name of the document library. This
    // encapsulates the logic found in
    // Microsoft.TeamFoundation.Client.SharePoint.DocumentLibraryInfo.FromXmlElement
    // in the .NET OM

    String name = null;//from   ww  w  . j a  v  a  2 s.  c  o  m

    String defaultViewUrl = EMPTY;
    if (node.hasAttribute("DefaultViewUrl")) //$NON-NLS-1$
    {
        defaultViewUrl = node.getAttribute("DefaultViewUrl"); //$NON-NLS-1$
    }

    String webFullUrl = EMPTY;
    if (node.hasAttribute("WebFullUrl")) //$NON-NLS-1$
    {
        webFullUrl = node.getAttribute("WebFullUrl"); //$NON-NLS-1$
    }

    name = calculateASCIINameFromWebFullURL(defaultViewUrl, webFullUrl);
    if (name != null) {
        return name;
    }

    // We're now into back-compat territory - just return back label as that
    // is all the old client used to do
    return label;

    // TODO for full .NET OM compatibility do, however not sure that this is
    // needed due to back-compat behaviour in our catalog service layer
    // name = calculateAsciiNameFromRegistrationData(connection,
    // defaultViewUrl);
    // if (name != null)
    // {
    // return name;
    // }
    //
    // name = calculateAsciiNameFromTemplateUrl(defaultViewUrl);
    // if (name != null)
    // {
    // return name;
    // }
}

From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java

private static Object getValue(Element elt, boolean ignoreStepIds, boolean useType) throws JSONException {
    Object value = null;//from w  w w.java2s. co  m

    try {
        if (elt.hasAttribute("type")) {
            String type = elt.getAttribute("type");

            if (type.equals("object")) {
                JSONObject jsonObject = new JSONObject();

                NodeList nl = elt.getChildNodes();
                for (int i = 0; i < nl.getLength(); i++) {
                    Node node = nl.item(i);

                    if (node instanceof Element) {
                        Element child = (Element) node;
                        String childName = child.hasAttribute("originalKeyName")
                                ? child.getAttribute("originalKeyName")
                                : child.getTagName();
                        Object childValue = getValue(child, ignoreStepIds, useType);

                        if (childValue != null) {
                            jsonObject.put(childName, childValue);
                        } else {
                            handleElement(child, jsonObject, ignoreStepIds, useType);
                        }
                    }
                }
                value = jsonObject;
            } else if (type.equals("array")) {
                JSONArray array = new JSONArray();

                NodeList nl = elt.getChildNodes();
                for (int i = 0; i < nl.getLength(); i++) {
                    Node node = nl.item(i);

                    if (node instanceof Element) {
                        Element child = (Element) node;
                        Object childValue = getValue(child, ignoreStepIds, useType);

                        if (childValue != null) {
                            array.put(childValue);
                        } else {
                            JSONObject obj = new JSONObject();
                            array.put(obj);
                            handleElement(child, obj, ignoreStepIds, useType);
                        }
                    }
                }

                value = array;
            } else if (type.equals("string")) {
                value = elt.getTextContent();
            } else if (type.equals("boolean")) {
                value = Boolean.parseBoolean(elt.getTextContent());
            } else if (type.equals("null")) {
                value = JSONObject.NULL;
            } else if (type.equals("integer")) {
                value = Integer.parseInt(elt.getTextContent());
            } else if (type.equals("long")) {
                value = Long.parseLong(elt.getTextContent());
            } else if (type.equals("double")) {
                value = Double.parseDouble(elt.getTextContent());
            } else if (type.equals("float")) {
                value = Float.parseFloat(elt.getTextContent());
            }

            if (value != null) {
                elt.removeAttribute(type);
            }
        }
    } catch (Throwable t) {
        Engine.logEngine.debug("failed to convert the element " + elt.getTagName(), t);
    }

    return value;
}

From source file:de.xwic.appkit.core.config.XmlConfigLoader.java

/**
 * @param element/*from  ww w.  j a  v a 2 s  .  c  om*/
 * @throws ParseException 
 */
private void loadApps(Element elApps) throws ParseException {

    NodeList nl = elApps.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
            if (element.getNodeName().equals("app")) {
                if (!element.hasAttribute("id")) {
                    throw new ParseException("id must be specified for an App node");
                }
                String id = element.getAttribute("id");
                String title = getFirstChildValue(element, "title");
                setup.addApp(new App(id, title));
            }
        }
    }

}

From source file:de.xwic.appkit.core.config.XmlConfigLoader.java

/**
 * @param element//from  w  ww .j a v  a2 s .  c  om
 * @throws IOException 
 * @throws ParseException 
 */
private void loadProperties(Element elProp) throws IOException, ParseException {

    NodeList nl = elProp.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
            if (element.getNodeName().equals("property")) {
                if (!element.hasAttribute("key")) {
                    throw new ParseException("key must be specified for a property");
                }
                String key = element.getAttribute("key");
                String value = getNodeText(element);
                setup.setProperty(key, value);
            }
        }
    }

}

From source file:de.xwic.appkit.core.config.XmlConfigLoader.java

/**
 * @param element//from  w  ww.j  a  v a 2 s.c  om
 * @throws IOException 
 * @throws ParseException 
 */
private void loadDefaults(Domain domain, Element elProp) throws IOException, ParseException {

    NodeList nl = elProp.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
            if (element.getNodeName().equals("preference")) {
                if (!element.hasAttribute("key")) {
                    throw new ParseException("key must be specified for a preference");
                }
                String key = element.getAttribute("key");
                String value = getNodeText(element);
                domain.setPrefDefault(key, value);
            }
        }
    }

}

From source file:com.cburch.draw.shapes.SvgReader.java

public static AbstractCanvasObject createShape(Element elt) {
    String name = elt.getTagName();
    AbstractCanvasObject ret;/*  w ww  .  j ava 2  s  .c o m*/
    if (name.equals("ellipse")) {
        ret = createOval(elt);
    } else if (name.equals("line")) {
        ret = createLine(elt);
    } else if (name.equals("path")) {
        ret = createPath(elt);
    } else if (name.equals("polyline")) {
        ret = createPolyline(elt);
    } else if (name.equals("polygon")) {
        ret = createPolygon(elt);
    } else if (name.equals("rect")) {
        ret = createRectangle(elt);
    } else if (name.equals("text")) {
        ret = createText(elt);
    } else {
        return null;
    }
    List<Attribute<?>> attrs = ret.getAttributes();
    if (attrs.contains(DrawAttr.PAINT_TYPE)) {
        String stroke = elt.getAttribute("stroke");
        String fill = elt.getAttribute("fill");
        if (stroke.equals("") || stroke.equals("none")) {
            ret.setValue(DrawAttr.PAINT_TYPE, DrawAttr.PAINT_FILL);
        } else if (fill.equals("none")) {
            ret.setValue(DrawAttr.PAINT_TYPE, DrawAttr.PAINT_STROKE);
        } else {
            ret.setValue(DrawAttr.PAINT_TYPE, DrawAttr.PAINT_STROKE_FILL);
        }
    }
    attrs = ret.getAttributes(); // since changing paintType could change it
    if (attrs.contains(DrawAttr.STROKE_WIDTH) && elt.hasAttribute("stroke-width")) {
        Integer width = Integer.valueOf(elt.getAttribute("stroke-width"));
        ret.setValue(DrawAttr.STROKE_WIDTH, width);
    }
    if (attrs.contains(DrawAttr.STROKE_COLOR)) {
        String color = elt.getAttribute("stroke");
        String opacity = elt.getAttribute("stroke-opacity");
        if (!color.equals("none")) {
            ret.setValue(DrawAttr.STROKE_COLOR, getColor(color, opacity));
        }
    }
    if (attrs.contains(DrawAttr.FILL_COLOR)) {
        String color = elt.getAttribute("fill");
        if (color.equals(""))
            color = "#000000";
        String opacity = elt.getAttribute("fill-opacity");
        if (!color.equals("none")) {
            ret.setValue(DrawAttr.FILL_COLOR, getColor(color, opacity));
        }
    }
    return ret;
}

From source file:net.sourceforge.dita4publishers.impl.dita.DitaKeyDefinitionImpl.java

/**
 * @param document//from   w  w  w.  j av a 2  s  .  com
 * @param key 
 * @param keydefElem
 * @throws URISyntaxException 
 * @throws MalformedURLException 
 * @throws DitaApiException 
 */
public DitaKeyDefinitionImpl(Document document, String key, Element keydefElem) throws DitaApiException {
    this.keydefElem = keydefElem;
    String baseUriStr = keydefElem.getBaseURI();
    if (baseUriStr == null)
        throw new DitaApiException("keydef element has a null base URI.");
    try {
        this.baseUri = new URI(baseUriStr);
    } catch (URISyntaxException e) {
        throw new DitaApiException(e);
    }
    this.key = key;
    log.debug("DitaKeyDefinitionImpl(): key=" + key + ", bseUri=" + baseUri);
    if (keydefElem.hasAttribute(DitaUtil.DITA_HREF_ATTNAME)) {
        href = keydefElem.getAttribute(DitaUtil.DITA_HREF_ATTNAME);
        log.debug("DitaKeyDefinitionImpl(): href=\"" + href + "\"");
        try {
            this.absoluteUrl = new URL(baseUri.toURL(), href);
        } catch (MalformedURLException e) {
            throw new DitaApiException(e);
        }
        log.debug("DitaKeyDefinitionImpl(): absoluteUrl=\"" + absoluteUrl + "\"");
    }
    if (keydefElem.hasAttribute(DitaUtil.DITA_KEYREF_ATTNAME)) {
        keyref = keydefElem.getAttribute(DitaUtil.DITA_KEYREF_ATTNAME);
        log.debug("DitaKeyDefinitionImpl(): keyref=\"" + keyref + "\"");
    }
    if (keydefElem.hasAttribute(DitaUtil.DITA_FORMAT_ATTNAME)) {
        String format = keydefElem.getAttribute(DitaUtil.DITA_FORMAT_ATTNAME).toUpperCase();
        log.debug("DitaKeyDefinitionImpl(): format=\"" + format + "\"");
        try {
            this.format = DitaFormat.valueOf(format);
        } catch (Exception e) {
            this.format = DitaFormat.NONDITA;
        }

    }

    propsSpec = DitaUtil.constructPropsSpec(keydefElem);
}

From source file:hd3gtv.as5kpc.protocol.ProtocolHandler.java

/**
 * @return maybe null/*  w  ww  .j av  a  2  s. c o  m*/
 */
private ServerResponse send(Document document, ServerResponse response) throws IOException {
    byte[] message = null;
    try {
        DOMSource domSource = new DOMSource(document);
        StringWriter stringwriter = new StringWriter();
        StreamResult streamresult = new StreamResult(stringwriter);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();

        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.transform(domSource, streamresult);
        message = stringwriter.toString().getBytes("UTF-8");
    } catch (UnsupportedEncodingException uee) {
        throw new IOException("Encoding XML is not supported", uee);
    } catch (TransformerException tc) {
        throw new IOException("Converting error between XML and String", tc);
    }

    if (log.isTraceEnabled()) {
        log.trace("Raw send >> " + new String(message, "UTF-8"));
    }

    /**
     * Send XML request
     */
    os.write(message);
    os.flush();

    /**
     * Wait and recevied XML response
     */
    int bytesRead;
    byte[] bytes = new byte[4092];
    try {
        while (socket.isConnected()) {
            try {
                while ((bytesRead = is.read(bytes)) != -1) {
                    try {
                        if (log.isTraceEnabled()) {
                            log.trace("Raw receive << " + new String(bytes, 0, bytesRead, "UTF-8"));
                        }
                        /**
                         * Decode XML response
                         */
                        ByteArrayInputStream bais = new ByteArrayInputStream(bytes, 0, bytesRead);
                        DocumentBuilderFactory xmlDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder xmlDocumentBuilder = xmlDocumentBuilderFactory.newDocumentBuilder();
                        xmlDocumentBuilder.setErrorHandler(null);
                        document = xmlDocumentBuilder.parse(bais);
                        Element root_element = document.getDocumentElement();

                        /**
                         * Check if result is valid/positive.
                         */
                        Element rply = (Element) root_element.getElementsByTagName("Reply").item(0);
                        String status = rply.getAttribute("Status").toLowerCase();
                        if (status.equals("ok") == false) {
                            String _message = "(no message)";
                            if (rply.hasAttribute("Msg")) {
                                _message = rply.getAttribute("Msg");
                            }

                            String error_type = "";
                            if (rply.hasAttribute("ErrNum")) {
                                int err = Integer.parseInt(rply.getAttribute("ErrNum"));
                                switch (err) {
                                case 1:
                                    error_type = "Command Error";
                                    break;
                                case 2:
                                    error_type = "System Error";
                                    break;
                                case 3:
                                    error_type = "XML format error";
                                    break;
                                case 4:
                                    error_type = "System BUSY";
                                    break;
                                default:
                                    break;
                                }
                            }

                            if (status.equals("warning")) {
                                log.warn(_message + ": " + error_type);
                            }
                            if (status.equals("error")) {
                                if (response instanceof ServerResponseClipdata
                                        && _message.toLowerCase().endsWith("does not exist")) {
                                    ((ServerResponseClipdata) response).not_found = true;
                                    return response;
                                } else {
                                    throw new IOException(
                                            "Server return: \"" + _message + ": " + error_type + "\"");
                                }
                            }
                        }

                        if (response != null) {
                            response.injectServerResponse(root_element);
                        }

                        return response;
                    } catch (ParserConfigurationException pce) {
                        log.error("DOM parser error", pce);
                    } catch (SAXException se) {
                        log.error("XML Struct error", se);
                    } catch (Exception e) {
                        log.error("Invalid response", e);
                    }
                }
            } catch (SocketTimeoutException soe) {
                Thread.sleep(100);
            }
        }
    } catch (InterruptedException e) {
    } catch (IOException e) {
        if (e.getMessage().equalsIgnoreCase("Socket closed")) {
            log.debug("Socket is closed, quit parser");
        } else {
            throw e;
        }
    }
    return null;
}

From source file:importer.handler.post.stages.Splitter.java

/**
 * Percolate the versions accumulated in root to suitable sub-elements
 * @param elem the start node with its versions to percolate
 *//* ww w  .j  av a2s.c  o m*/
private void percolateDown(Element elem) {
    Node parent = elem.getParentNode();
    if (parent != null && parent.getNodeType() == Node.ELEMENT_NODE) {
        System.out.println(elem.getNodeName());
        String vers = ((Element) parent).getAttribute(VERSIONS);
        if (vers != null && vers.length() > 0) {
            if (!discriminator.isSibling(elem)) {
                Discriminator.addVersion(elem, vers);
                addDoneTag(elem);
            } else if (elem.hasAttribute(FINAL)) {
                String fVers = elem.getAttribute(FINAL);
                if (fVers != null && fVers.length() > 0) {
                    // find inverse versions
                    HashSet<String> invVers = new HashSet<String>();
                    String[] parts = vers.split(" ");
                    String[] iparts = fVers.split(" ");
                    for (int i = 0; i < parts.length; i++)
                        if ( /*!parts[i].startsWith(DEL) 
                             &&*/ !parts[i].equals(BASE))
                            invVers.add(parts[i]);
                    for (int i = 0; i < iparts.length; i++)
                        if (invVers.contains(iparts[i]))
                            invVers.remove(iparts[i]);
                    String newVers = hashsetToString(invVers);
                    Discriminator.addVersion(elem, newVers);
                    addDoneTag(elem);
                    Element lastOChild = discriminator.lastOpenChild(elem);
                    while (lastOChild != null) {
                        Discriminator.addVersion(lastOChild, newVers);
                        lastOChild = discriminator.lastOpenChild(lastOChild);
                    }
                }
            }
            // else ignore it
        }
    }
    // now examine the children of elem
    Element child = Discriminator.firstChild(elem);
    while (child != null && !isDone(child)) {
        percolateDown(child);
        child = Discriminator.firstChild(child);
    }
    // finall the siblings of elem
    Element brother = Discriminator.nextSibling(elem, true);
    while (brother != null) {
        if (!isDone(brother))
            percolateDown(brother);
        brother = Discriminator.nextSibling(brother, true);
    }
}