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:org.apache.ode.utils.wsdl.WsdlUtils.java

/**
 * @param fault/*from   w  ww.ja v  a 2 s .  c om*/
 * @return true if the given fault is bound with the {@link org.apache.ode.utils.Namespaces.ODE_HTTP_EXTENSION_NS}:fault element.
 */
public static boolean isOdeFault(BindingFault fault) {
    final Collection<UnknownExtensibilityElement> unknownExtElements = CollectionsX
            .filter(fault.getExtensibilityElements(), UnknownExtensibilityElement.class);
    for (UnknownExtensibilityElement extensibilityElement : unknownExtElements) {
        final Element e = extensibilityElement.getElement();
        if (Namespaces.ODE_HTTP_EXTENSION_NS.equalsIgnoreCase(e.getNamespaceURI())
                && "fault".equals(extensibilityElement.getElement().getLocalName())) {
            // name attribute is optional, but if any it must match the fault name
            if (e.hasAttribute("name")) {
                return fault.getName().equals(e.getAttribute("name"));
            } else {
                return true;
            }
        }
    }
    return false;
}

From source file:org.apache.servicemix.jbi.deployer.descriptor.DescriptorFactory.java

private static String getAttribute(Element e, String name) {
    if (e.hasAttribute(name)) {
        return e.getAttribute(name);
    } else {/*from  www. ja va  2 s  .  co  m*/
        return null;
    }
}

From source file:org.apache.ws.security.util.WSSecurityUtil.java

/**
 * Returns the single SAMLAssertion element that contains an AssertionID/ID that
 * matches the supplied parameter.//from w w w  .  java 2 s  . c o  m
 * 
 * @param startNode Where to start the search
 * @param value Value of the AssertionID/ID attribute
 * @return The found element if there was exactly one match, or
 *         <code>null</code> otherwise
 */
public static Element findSAMLAssertionElementById(Node startNode, String value) {
    Element foundElement = null;

    //
    // Replace the formerly recursive implementation with a depth-first-loop
    // lookup
    //
    if (startNode == null) {
        return null;
    }
    Node startParent = startNode.getParentNode();
    Node processedNode = null;

    while (startNode != null) {
        // start node processing at this point
        if (startNode.getNodeType() == Node.ELEMENT_NODE) {
            Element se = (Element) startNode;
            if ((se.hasAttribute("ID") && value.equals(se.getAttribute("ID")))
                    || (se.hasAttribute("AssertionID") && value.equals(se.getAttribute("AssertionID")))) {
                if (foundElement == null) {
                    foundElement = se; // Continue searching to find duplicates
                } else {
                    log.warn("Multiple elements with the same 'ID' attribute value!");
                    return null;
                }
            }
        }

        processedNode = startNode;
        startNode = startNode.getFirstChild();

        // no child, this node is done.
        if (startNode == null) {
            // close node processing, get sibling
            startNode = processedNode.getNextSibling();
        }
        // no more siblings, get parent, all children
        // of parent are processed.
        while (startNode == null) {
            processedNode = processedNode.getParentNode();
            if (processedNode == startParent) {
                return foundElement;
            }
            // close parent node processing (processed node now)
            startNode = processedNode.getNextSibling();
        }
    }
    return foundElement;
}

From source file:org.beepcore.beep.example.Beepd.java

/**
 * Parses the beepd element in the configuration file and loads the
 * classes for the specified profiles.//from   w  w  w . j  a  v  a 2s . c o  m
 *
 * @param serverConfig &ltbeepd&gt configuration element.
 */
private Beepd(Element serverConfig) throws Exception {
    reg = new ProfileRegistry();

    if (serverConfig.hasAttribute("port") == false) {
        throw new Exception("Invalid configuration, no port specified");
    }

    port = Integer.parseInt(serverConfig.getAttribute("port"));

    // Parse the list of profile elements.
    NodeList profiles = serverConfig.getElementsByTagName("profile");
    for (int i = 0; i < profiles.getLength(); ++i) {
        if (profiles.item(i).getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }

        Element profile = (Element) profiles.item(i);

        if (profile.getNodeName().equalsIgnoreCase("profile") == false) {
            continue;
        }

        String uri;
        String className;
        String requiredProperites;
        String tuningProperties;

        if (profile.hasAttribute("uri") == false) {
            throw new Exception("Invalid configuration, no uri specified");
        }

        uri = profile.getAttribute("uri");

        if (profile.hasAttribute("class") == false) {
            throw new Exception("Invalid configuration, no class " + "specified for profile " + uri);
        }

        className = profile.getAttribute("class");

        // parse the parameter elements into a ProfileConfiguration
        ProfileConfiguration profileConfig = parseProfileConfig(profile.getElementsByTagName("parameter"));

        // load the profile class
        Profile p;
        try {
            p = (Profile) Class.forName(className).newInstance();
        } catch (ClassNotFoundException e) {
            throw new Exception("Class " + className + " not found");
        } catch (ClassCastException e) {
            throw new Exception("class " + className + " does not " + "implement the "
                    + "org.beepcore.beep.profile.Profile " + "interface");
        }

        SessionTuningProperties tuning = null;

        if (profile.hasAttribute("tuning")) {
            String tuningString = profile.getAttribute("tuning");
            Hashtable hash = new Hashtable();
            StringTokenizer tokens = new StringTokenizer(tuningString, ":=");

            try {
                while (tokens.hasMoreTokens()) {
                    String parameter = tokens.nextToken();
                    String value = tokens.nextToken();

                    hash.put(parameter, value);
                }
            } catch (NoSuchElementException e) {
                e.printStackTrace();

                throw new Exception("Error parsing tuning property on " + "profile " + uri);
            }

            tuning = new SessionTuningProperties(hash);
        }

        // Initialize the profile and add it to the advertised profiles
        reg.addStartChannelListener(uri, p.init(uri, profileConfig), tuning);
    }
}

From source file:org.beepcore.beep.example.Beepd.java

/**
 * Parses the child elements of a profile element into a
 * <code>ProfileConfiguration</code> object.
 *
 * @param profileConfig list of parameter child elements of a profile
 *                      element./*from   ww  w  . ja v a2s  . co m*/
 */
private static ProfileConfiguration parseProfileConfig(NodeList profileConfig) throws Exception {
    ProfileConfiguration config = new ProfileConfiguration();

    for (int i = 0; i < profileConfig.getLength(); ++i) {
        Element parameter = (Element) profileConfig.item(i);

        if (parameter.hasAttribute("name") == false || parameter.hasAttribute("value") == false) {
            throw new Exception("Invalid configuration parameter " + "missing name or value attibute");
        }

        config.setProperty(parameter.getAttribute("name"), parameter.getAttribute("value"));
    }

    return config;
}

From source file:org.bibsonomy.importer.bookmark.service.DeliciousImporter.java

/**
 * This Method retrieves a list of Posts for a given user.
 *//*from ww w .  j a  va2  s .c  o m*/
public List<Post<Bookmark>> getPosts() throws IOException {

    final List<Post<Bookmark>> posts = new LinkedList<Post<Bookmark>>();

    //open a connection to delicious and retrieve a document
    final Document document = getDocument();

    // traverse document and put everything into Post<Bookmark> Objects
    final NodeList postList = document.getElementsByTagName("post");
    for (int i = 0; i < postList.getLength(); i++) {
        final Element resource = (Element) postList.item(i);

        final Post<Bookmark> post = new Post<Bookmark>();
        final Bookmark bookmark = new Bookmark();
        bookmark.setTitle(resource.getAttribute("description"));
        bookmark.setUrl(resource.getAttribute("href"));
        try {
            post.getTags().addAll(TagUtils.parse(resource.getAttribute("tag")));
        } catch (Exception e) {
            throw new IOException("Could not parse tags. ", e);
        }

        //no tags available? -> add one tag to the resource and mark it as "imported"
        if (post.getTags().isEmpty()) {
            post.setTags(Collections.singleton(TagUtils.getEmptyTag()));
        }

        post.setDescription(resource.getAttribute("extended"));
        try {
            post.setDate(df.parse(resource.getAttribute("time")));
        } catch (ParseException e) {
            log.warn("Could not parse date.", e);
            post.setDate(new Date());
        }

        //set the visibility of the imported resource
        if (resource.hasAttribute("shared")) {
            if ("no".equals(resource.getAttribute("shared"))) {
                post.getGroups().add(GroupUtils.getPrivateGroup());
            } else {
                post.getGroups().add(GroupUtils.getPublicGroup());
            }
        }
        post.setResource(bookmark);
        posts.add(post);

    }

    return posts;
}

From source file:org.bibsonomy.importer.bookmark.service.DeliciousV2Importer.java

/**
 * This Method retrieves a list of Posts for a given user.
 *//*from ww w .  j  a  va2 s  .c o  m*/
public static List<Post<Bookmark>> getPosts(HttpURLConnection connection) throws IOException {

    final List<Post<Bookmark>> posts = new LinkedList<Post<Bookmark>>();

    //open a connection to delicious and retrieve a document
    connection.connect();
    final Document document = getDocument(connection.getInputStream());
    connection.disconnect();
    /*
     * TODO: this is copied code from DeliciousImporter
     */
    // traverse document and put everything into Post<Bookmark> Objects
    final NodeList postList = document.getElementsByTagName("post");
    for (int i = 0; i < postList.getLength(); i++) {
        final Element resource = (Element) postList.item(i);

        final Post<Bookmark> post = new Post<Bookmark>();
        final Bookmark bookmark = new Bookmark();
        bookmark.setTitle(resource.getAttribute("description"));
        bookmark.setUrl(resource.getAttribute("href"));
        try {
            post.getTags().addAll(TagUtils.parse(resource.getAttribute("tag")));
        } catch (Exception e) {
            throw new IOException("Could not parse tags. ", e);
        }

        //no tags available? -> add one tag to the resource and mark it as "imported"
        if (post.getTags().isEmpty()) {
            post.setTags(Collections.singleton(TagUtils.getEmptyTag()));
        }

        post.setDescription(resource.getAttribute("extended"));
        try {
            post.setDate(df.parse(resource.getAttribute("time")));
        } catch (ParseException e) {
            log.warn("Could not parse date.", e);
            post.setDate(new Date());
        }

        //set the visibility of the imported resource
        if (resource.hasAttribute("shared")) {
            if ("no".equals(resource.getAttribute("shared"))) {
                post.getGroups().add(GroupUtils.getPrivateGroup());
            } else {
                post.getGroups().add(GroupUtils.getPublicGroup());
            }
        }
        post.setResource(bookmark);
        posts.add(post);

    }

    return posts;
}

From source file:org.commonreality.sensors.xml.processor.AbstractProcessor.java

/**
 * @see org.commonreality.sensors.xml.processor.IXMLProcessor#process(org.w3c.dom.Element,
 *      org.commonreality.identifier.IIdentifier,
 *      org.commonreality.sensors.xml.XMLSensor)
 *//*from ww w  .j ava 2s  .  co  m*/
public Collection<IMessage> process(Element element, IIdentifier agentID, XMLSensor sensor) {
    Collection<IMessage> rtn = new ArrayList<IMessage>();
    Collection<IObjectDelta> added = new ArrayList<IObjectDelta>();
    Collection<IIdentifier> addedIds = new ArrayList<IIdentifier>();
    Collection<IObjectDelta> updated = new ArrayList<IObjectDelta>();
    Collection<IIdentifier> updatedIds = new ArrayList<IIdentifier>();
    Collection<IIdentifier> removedIds = new ArrayList<IIdentifier>();

    Collection<NodeList> nodeLists = new ArrayList<NodeList>();
    nodeLists.add(element.getElementsByTagName("add"));
    nodeLists.add(element.getElementsByTagName("update"));
    nodeLists.add(element.getElementsByTagName("remove"));

    for (NodeList nl : nodeLists)
        for (int i = 0; i < nl.getLength(); i++) {
            Node child = nl.item(i);
            if (!(child instanceof Element))
                continue;

            Element childElement = (Element) child;
            String tagName = childElement.getTagName();

            /**
             * remove all that match a pattern
             */
            if (tagName.equalsIgnoreCase("remove") && childElement.hasAttribute("pattern")
                    && _aliases.containsKey(agentID)) {
                Pattern pattern = Pattern.compile(childElement.getAttribute("pattern"));

                Collection<String> aliases = new ArrayList<String>(_aliases.get(agentID).keySet());
                for (String alias : aliases)
                    if (pattern.matcher(alias).matches()) {
                        IIdentifier objectId = getIdentifier(alias, agentID);
                        if (objectId != null) {
                            removeIdentifier(alias, agentID);
                            removedIds.add(objectId);
                        }
                    }
            } else if (shouldProcess(childElement, agentID) && childElement.hasAttribute("alias"))
                if (tagName.equalsIgnoreCase("add")) {
                    IObjectDelta delta = add(childElement, agentID, sensor);
                    if (delta != null) {
                        added.add(delta);
                        addedIds.add(delta.getIdentifier());
                    }
                } else if (tagName.equalsIgnoreCase("update")) {
                    IObjectDelta delta = update(childElement, agentID, sensor);
                    if (delta != null) {
                        updated.add(delta);
                        updatedIds.add(delta.getIdentifier());
                    }
                } else if (tagName.equalsIgnoreCase("remove")) {
                    IIdentifier id = remove(childElement, agentID, sensor);
                    if (id != null)
                        removedIds.add(id);
                }
        }

    IIdentifier sId = sensor.getIdentifier();
    /*
     * handle all the adds, updates and removes send the data first..
     */
    if (added.size() != 0) {
        rtn.add(new ObjectDataRequest(sId, agentID, added));
        rtn.add(new ObjectCommandRequest(sId, agentID, IObjectCommand.Type.ADDED, addedIds));
    }

    if (updated.size() != 0) {
        rtn.add(new ObjectDataRequest(sId, agentID, updated));
        rtn.add(new ObjectCommandRequest(sId, agentID, IObjectCommand.Type.UPDATED, updatedIds));
    }

    if (removedIds.size() != 0)
        rtn.add(new ObjectCommandRequest(sId, agentID, IObjectCommand.Type.REMOVED, removedIds));

    return rtn;
}

From source file:org.commonreality.sensors.xml.XMLProcessor.java

public double getTime(Element frame) {
    double nextTime = 0;
    /*//from   w ww.  j  a  va2  s .co  m
     * is time absolute or relative?
     */
    if (frame.hasAttribute("value"))
        nextTime = Double.valueOf(frame.getAttribute("value"));
    else if (frame.hasAttribute("relative"))
        nextTime = _sensor.getClock().getTime() + Double.valueOf(frame.getAttribute("relative"));
    else
        nextTime = Double.NaN;

    return nextTime;
}

From source file:org.commonreality.sensors.xml2.processor.AbstractProcessor.java

/**
 * @see org.commonreality.sensors.xml.processor.IXMLProcessor#process(org.w3c.dom.Element,
 *      org.commonreality.identifier.IIdentifier,
 *      org.commonreality.sensors.xml.XMLSensor)
 *//* w  ww .j a va 2s. c o  m*/
public Collection<IMessage> process(Element element, IIdentifier agentID, XMLSensor sensor) {
    Collection<IMessage> rtn = new ArrayList<IMessage>();
    Collection<IObjectDelta> added = new ArrayList<IObjectDelta>();
    Collection<IIdentifier> addedIds = new ArrayList<IIdentifier>();
    Collection<IObjectDelta> updated = new ArrayList<IObjectDelta>();
    Collection<IIdentifier> updatedIds = new ArrayList<IIdentifier>();
    Collection<IIdentifier> removedIds = new ArrayList<IIdentifier>();

    Collection<NodeList> nodeLists = new ArrayList<NodeList>();
    nodeLists.add(element.getElementsByTagName("add"));
    nodeLists.add(element.getElementsByTagName("update"));
    nodeLists.add(element.getElementsByTagName("remove"));

    for (NodeList nl : nodeLists)
        for (int i = 0; i < nl.getLength(); i++) {
            Node child = nl.item(i);
            if (!(child instanceof Element))
                continue;

            Element childElement = (Element) child;
            String tagName = childElement.getTagName();

            String forWhichAgent = childElement.getAttribute("for");
            if (forWhichAgent != null && forWhichAgent.length() > 0) {
                IAgentObject ao = sensor.getAgentObjectManager().get(agentID);
                String agentName = (String) ao.getProperty("name");
                if (agentName == null)
                    LOGGER.error("Agent name was not set for " + agentID);
                else if (!agentName.equals(forWhichAgent)) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug(
                                String.format("agentId %s does not match targeted name %s, skipping processing",
                                        agentName, forWhichAgent));

                    continue;
                }
            }

            /**
             * remove all that match a pattern
             */
            if (tagName.equalsIgnoreCase("remove") && childElement.hasAttribute("pattern")
                    && _aliases.containsKey(agentID)) {
                Pattern pattern = Pattern.compile(childElement.getAttribute("pattern"));

                Collection<String> aliases = new ArrayList<String>(_aliases.get(agentID).keySet());
                for (String alias : aliases)
                    if (pattern.matcher(alias).matches()) {
                        IIdentifier objectId = getIdentifier(alias, agentID);
                        if (objectId != null) {
                            removeIdentifier(alias, agentID);
                            removedIds.add(objectId);
                        }
                    }
            } else if (shouldProcess(childElement, agentID) && childElement.hasAttribute("alias"))
                if (tagName.equalsIgnoreCase("add")) {
                    IObjectDelta delta = add(childElement, agentID, sensor);
                    if (delta != null) {
                        added.add(delta);
                        addedIds.add(delta.getIdentifier());
                    }
                } else if (tagName.equalsIgnoreCase("update")) {
                    IObjectDelta delta = update(childElement, agentID, sensor);
                    if (delta != null) {
                        updated.add(delta);
                        updatedIds.add(delta.getIdentifier());
                    }
                } else if (tagName.equalsIgnoreCase("remove")) {
                    IIdentifier id = remove(childElement, agentID, sensor);
                    if (id != null)
                        removedIds.add(id);
                }
        }

    IIdentifier sId = sensor.getIdentifier();
    /*
     * handle all the adds, updates and removes send the data first..
     */
    if (added.size() != 0) {
        rtn.add(new ObjectDataRequest(sId, agentID, added));
        rtn.add(new ObjectCommandRequest(sId, agentID, IObjectCommand.Type.ADDED, addedIds));
    }

    if (updated.size() != 0) {
        rtn.add(new ObjectDataRequest(sId, agentID, updated));
        rtn.add(new ObjectCommandRequest(sId, agentID, IObjectCommand.Type.UPDATED, updatedIds));
    }

    if (removedIds.size() != 0)
        rtn.add(new ObjectCommandRequest(sId, agentID, IObjectCommand.Type.REMOVED, removedIds));

    return rtn;
}