Java Code Examples for org.w3c.dom.Element#getNodeType()

The following examples show how to use org.w3c.dom.Element#getNodeType() . 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
Source File: DOMCategory.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the list of any direct String nodes of this node.
 *
 * @return the list of String values from this node
 * @since 2.3.0
 */
public static List<String> localText(Element self) {
    List<String> result = new ArrayList<String>();
    if (self.getNodeType() == Node.TEXT_NODE || self.getNodeType() == Node.CDATA_SECTION_NODE) {
        result.add(self.getNodeValue());
    } else if (self.hasChildNodes()) {
        NodeList nodeList = self.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node item = nodeList.item(i);
            if (item.getNodeType() == Node.TEXT_NODE || item.getNodeType() == Node.CDATA_SECTION_NODE) {
                result.add(item.getNodeValue());
            }
        }
    }
    return result;
}
 
Example 2
Source File: XmlMerger.java    From RADL with Apache License 2.0 6 votes vote down vote up
private FindResult find(Element node, Node parent) {
  for (Node current = parent.getFirstChild(); current != null; current = current.getNextSibling()) {
    if (current.getNodeType() == node.getNodeType()
        && isEqual(node.getNamespaceURI(), current.getNamespaceURI())
        && isEqual(node.getLocalName(), current.getLocalName())) {
      Element result = (Element)current;
      boolean exactMatch = isSame(node, result);
      String listName = node.getLocalName() + 's';
      boolean isListItem = listName.equals(parent.getLocalName());
      if (exactMatch || !isListItem) {
        return new FindResult(result, exactMatch);
      }
    }
  }
  return FindResult.notFound();
}
 
Example 3
Source File: TestCaseEngine.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static void setGlobalParams(Element rootElement) {
    NodeList globalParam = rootElement.getElementsByTagName("globalparam");
    Element parameter = (Element)globalParam.item(0);
    NodeList paramLst = parameter.getElementsByTagName("param");

    for (int i = 0; i < paramLst.getLength(); i++) {
        Element paramElement = (Element)paramLst.item(i);

        if (paramElement.getNodeType() == Node.ELEMENT_NODE) {
            Element itemElement = paramElement;
            NodeList itemName = itemElement.getElementsByTagName("name");
            Element itemNameElement = (Element)itemName.item(0);
            NodeList itemVariable = itemElement.getElementsByTagName("variable");
            Element itemVariableElement = (Element)itemVariable.item(0);
            s_globalParameters.put(itemVariableElement.getTextContent(), itemNameElement.getTextContent());
        }
    }
}
 
Example 4
Source File: ClientConfigHelper.java    From pmq with Apache License 2.0 5 votes vote down vote up
private void setTopic(ConsumerGroupVo consumerGroupConfig, Element consumerItem) {
	Map<String, ConsumerGroupTopicVo> groupConfigMap = new ConcurrentHashMap<>();
	if (consumerItem == null || !consumerItem.hasChildNodes()) {
		throw new IllegalArgumentException(consumerGroupConfig.getMeta().getName() + "下无topic节点");
	}
	NodeList nodeList = consumerItem.getElementsByTagName("topic");
	if (nodeList == null || nodeList.getLength() < 1) {
		throw new IllegalArgumentException(consumerGroupConfig.getMeta().getName() + "下无topic节点");
	}
	int count = nodeList.getLength();
	for (int i = 0; i < count; i++) {
		Element item = (Element) nodeList.item(i);
		if (item.getNodeType() != Node.ELEMENT_NODE) {
			continue;
		}
		if (!item.hasAttribute("name")) {
			throw new IllegalArgumentException("topic节点没有设置name参数");
		}
		ConsumerGroupTopicVo groupConfig = new ConsumerGroupTopicVo();
		groupConfig.setName(item.getAttribute("name"));
		if (item.hasAttribute("receiverType")) {
			groupConfig.setSubscriber(getSubscriber(item.getAttribute("receiverType")));

		} else {
			throw new IllegalArgumentException("topic:" + groupConfig.getName() + "节点没有设置receiverType参数");
		}
		groupConfigMap.put(groupConfig.getName(), groupConfig);
	}
	consumerGroupConfig.setTopics(groupConfigMap);

}
 
Example 5
Source File: RpcBindingConverter.java    From sofa-rpc-boot-projects with Apache License 2.0 5 votes vote down vote up
private void parseParameter(List<Element> parameterElements, RpcBindingParam param) {
    if (CollectionUtils.isEmpty(parameterElements)) {
        return;
    }
    Map<String, String> parameters = new LinkedHashMap<String, String>(parameterElements.size());
    for (Element element : parameterElements) {
        if (element.getNodeType() == Node.ELEMENT_NODE &&
            element.getLocalName().equals(RpcBindingXmlConstants.TAG_PARAMETER)) {
            String key = element.getAttribute(RpcBindingXmlConstants.TAG_PARAMETER_KEY);
            String value = element.getAttribute(RpcBindingXmlConstants.TAG_PARAMETER_VALUE);
            parameters.put(key, value);
        }
    }
    param.setParameters(parameters);
}
 
Example 6
Source File: GO_CharacterString.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Invoked by JAXB for any XML element which is not a {@code <gco:CharacterString>}, {@code <gcx:FileName>}
 * or {@code <gcx:MimeFileType>}. This method presumes that the element name is the CodeList standard name.
 * If not, the element will be ignored.
 */
@SuppressWarnings({"unchecked", "unused"})
private void setCodeList(final Object value) {
    final Element e = (Element) value;
    if (e.getNodeType() == Element.ELEMENT_NODE) {
        final Class<?> ct = Types.forStandardName(e.getLocalName());
        final Class<? extends IndexedResourceBundle> resources;
        final short errorKey;
        final Object[] args;
        if (ct != null && CodeList.class.isAssignableFrom(ct)) {
            final String attribute = e.getAttribute("codeListValue").trim();
            if (!attribute.isEmpty()) {
                text = Types.getCodeTitle(Types.forCodeName((Class) ct, attribute, true));
                type = ENUM;
                return;
            } else {
                resources = Errors.class;
                errorKey  = Errors.Keys.MissingOrEmptyAttribute_2;
                args      = new Object[2];
                args[1]   = "codeListValue";
            }
        } else {
            resources = Messages.class;
            errorKey  = Messages.Keys.UnknownCodeList_1;
            args      = new Object[1];
        }
        args[0] = e.getNodeName();
        Context.warningOccured(Context.current(), GO_CharacterString.class, "setCodeList", resources, errorKey, args);
    }
}
 
Example 7
Source File: RpcBindingConverter.java    From sofa-rpc-boot-projects with Apache License 2.0 4 votes vote down vote up
private void parseMethod(List<Element> elements, RpcBindingParam param) {

        if (CollectionUtils.isEmpty(elements)) {
            return;
        }

        List<RpcBindingMethodInfo> boltBindingMethodInfos = new ArrayList<RpcBindingMethodInfo>();

        for (Element element : elements) {
            if (element.getNodeType() == Node.ELEMENT_NODE &&
                element.getLocalName().equals(RpcBindingXmlConstants.TAG_METHOD)) {

                String name = element.getAttribute(RpcBindingXmlConstants.TAG_NAME);
                Integer timeout = SofaBootRpcParserUtil.parseInteger(element
                    .getAttribute(RpcBindingXmlConstants.TAG_TIMEOUT));
                Integer retries = SofaBootRpcParserUtil.parseInteger(element
                    .getAttribute(RpcBindingXmlConstants.TAG_RETRIES));
                String type = element.getAttribute(RpcBindingXmlConstants.TAG_TYPE);

                RpcBindingMethodInfo boltBindingMethodInfo = new RpcBindingMethodInfo();
                if (StringUtils.hasText(name)) {
                    boltBindingMethodInfo.setName(name);
                }
                if (timeout != null) {
                    boltBindingMethodInfo.setTimeout(timeout);
                }
                if (retries != null) {
                    boltBindingMethodInfo.setRetries(retries);
                }
                if (StringUtils.hasText(type)) {
                    boltBindingMethodInfo.setType(type);
                }

                if (type.equalsIgnoreCase(RpcBindingXmlConstants.TYPE_CALLBACK)) {
                    String callbackRef = element.getAttribute(RpcBindingXmlConstants.TAG_CALLBACK_REF);
                    String callbackClass = element.getAttribute(RpcBindingXmlConstants.TAG_CALLBACK_CLASS);

                    boltBindingMethodInfo.setCallbackRef(callbackRef);
                    boltBindingMethodInfo.setCallbackClass(callbackClass);
                }

                boltBindingMethodInfos.add(boltBindingMethodInfo);
            }
        }

        param.setMethodInfos(boltBindingMethodInfos);
    }
 
Example 8
Source File: LessonManagerServlet.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
   private Element getAllStudentProgress(Document document, String serverId, String datetime, String hashValue,
    String username, long lsId, String courseID) throws RemoteException {
try {
    ExtServer extServer = integrationService.getExtServer(serverId);
    Authenticator.authenticate(extServer, datetime, username, hashValue);
    Lesson lesson = lessonService.getLesson(lsId);

    Element element = document.createElement(CentralConstants.ELEM_LESSON_PROGRESS);
    element.setAttribute(CentralConstants.ATTR_LESSON_ID, "" + lsId);

    String prefix = extServer.getPrefix();
    if (lesson != null) {

	int activitiesTotal = lesson.getLearningDesign().getActivities().size();
	Iterator<LearnerProgress> iterator = lesson.getLearnerProgresses().iterator();
	while (iterator.hasNext()) {
	    LearnerProgress learnProg = iterator.next();
	    LearnerProgressDTO learnerProgress = learnProg.getLearnerProgressData();

	    // get the username with the integration prefix removed
	    String userNoPrefixName = learnerProgress.getUserName().substring(prefix.length() + 1);
	    ExtUserUseridMap learnerMap = integrationService.getExtUserUseridMap(extServer, userNoPrefixName);

	    Element learnerProgElem = document.createElement(CentralConstants.ELEM_LEARNER_PROGRESS);

	    int completedActivities = learnerProgress.getCompletedActivities().length;
	    int attemptedActivities = learnerProgress.getAttemptedActivities().length;

	    if (learnerProgElem.getNodeType() == Node.ELEMENT_NODE) {
		learnerProgElem.setAttribute(CentralConstants.ATTR_LESSON_COMPLETE,
			"" + learnerProgress.getLessonComplete());
		learnerProgElem.setAttribute(CentralConstants.ATTR_ACTIVITY_COUNT, "" + activitiesTotal);
		learnerProgElem.setAttribute(CentralConstants.ATTR_ACTIVITIES_COMPLETED,
			"" + completedActivities);
		learnerProgElem.setAttribute(CentralConstants.ATTR_ACTIVITIES_ATTEMPTED,
			"" + attemptedActivities);
		// learnerProgElem.setAttribute(CentralConstants.ATTR_CURRENT_ACTIVITY , currActivity);
		learnerProgElem.setAttribute(CentralConstants.ATTR_STUDENT_ID, "" + learnerMap.getSid());
		learnerProgElem.setAttribute(CentralConstants.ATTR_COURSE_ID, courseID);
		learnerProgElem.setAttribute(CentralConstants.ATTR_USERNAME, userNoPrefixName);
		learnerProgElem.setAttribute(CentralConstants.ATTR_LESSON_ID, "" + lsId);
	    }

	    element.appendChild(learnerProgElem);
	}
    } else {
	throw new Exception("Lesson with lessonID: " + lsId + " could not be found for learner progresses");
    }

    return element;

} catch (Exception e) {
    throw new RemoteException(e.getMessage(), e);
}

   }
 
Example 9
Source File: LessonManagerServlet.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private Element getSingleStudentProgress(Document document, String serverId, String datetime, String hashValue,
    String username, String firstName, String lastName, String locale, String country, String email, long lsId,
    String courseID) throws RemoteException {
try {
    ExtServer extServer = integrationService.getExtServer(serverId);
    Authenticator.authenticate(extServer, datetime, username, hashValue);
    Lesson lesson = lessonService.getLesson(lsId);

    Element element = document.createElement(CentralConstants.ELEM_LESSON_PROGRESS);
    element.setAttribute(CentralConstants.ATTR_LESSON_ID, "" + lsId);

    if (lesson != null) {
	int activitiesTotal = lesson.getLearningDesign().getActivities().size();

	// create new user if required
	final boolean usePrefix = true;
	final boolean isUpdateUserDetails = false;
	ExtUserUseridMap userMap = integrationService.getImplicitExtUserUseridMap(extServer, username,
		firstName, lastName, locale, country, email, usePrefix, isUpdateUserDetails);

	LearnerProgress learnProg = lessonService.getUserProgressForLesson(userMap.getUser().getUserId(), lsId);

	Element learnerProgElem = document.createElement(CentralConstants.ELEM_LEARNER_PROGRESS);

	// if learner progress exists, make a response, otherwise, return an empty learner progress element
	if (learnProg != null) {
	    LearnerProgressDTO learnerProgress = learnProg.getLearnerProgressData();

	    int completedActivities = learnerProgress.getCompletedActivities().length;
	    int attemptedActivities = learnerProgress.getAttemptedActivities().length;

	    if (learnerProgElem.getNodeType() == Node.ELEMENT_NODE) {
		learnerProgElem.setAttribute(CentralConstants.ATTR_LESSON_COMPLETE,
			"" + learnerProgress.getLessonComplete());
		learnerProgElem.setAttribute(CentralConstants.ATTR_ACTIVITY_COUNT, "" + activitiesTotal);
		learnerProgElem.setAttribute(CentralConstants.ATTR_ACTIVITIES_COMPLETED,
			"" + completedActivities);
		learnerProgElem.setAttribute(CentralConstants.ATTR_ACTIVITIES_ATTEMPTED,
			"" + attemptedActivities);
		// learnerProgElem.setAttribute(CentralConstants.ATTR_CURRENT_ACTIVITY , currActivity);
		learnerProgElem.setAttribute(CentralConstants.ATTR_STUDENT_ID, "" + userMap.getSid());
		learnerProgElem.setAttribute(CentralConstants.ATTR_COURSE_ID, courseID);
		learnerProgElem.setAttribute(CentralConstants.ATTR_USERNAME, username);
		learnerProgElem.setAttribute(CentralConstants.ATTR_LESSON_ID, "" + lsId);
	    }
	} else {
	    if (learnerProgElem.getNodeType() == Node.ELEMENT_NODE) {
		learnerProgElem.setAttribute(CentralConstants.ATTR_LESSON_COMPLETE, "false");
		learnerProgElem.setAttribute(CentralConstants.ATTR_ACTIVITY_COUNT, "" + activitiesTotal);
		learnerProgElem.setAttribute(CentralConstants.ATTR_ACTIVITIES_COMPLETED, "0");
		learnerProgElem.setAttribute(CentralConstants.ATTR_ACTIVITIES_ATTEMPTED, "0");
		// learnerProgElem.setAttribute(CentralConstants.ATTR_CURRENT_ACTIVITY , currActivity);
		learnerProgElem.setAttribute(CentralConstants.ATTR_STUDENT_ID, "" + userMap.getSid());
		learnerProgElem.setAttribute(CentralConstants.ATTR_COURSE_ID, courseID);
		learnerProgElem.setAttribute(CentralConstants.ATTR_USERNAME, username);
		learnerProgElem.setAttribute(CentralConstants.ATTR_LESSON_ID, "" + lsId);
	    }
	}

	element.appendChild(learnerProgElem);
    } else {
	throw new Exception("Lesson with lessonID: " + lsId + " could not be found for learner progresses");
    }

    return element;

} catch (Exception e) {
    throw new RemoteException(e.getMessage(), e);
}

   }
 
Example 10
Source File: RMSoapInInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void decodeHeaders(SoapMessage message, List<Header> headers, RMProperties rmps) {
    try {
        Collection<SequenceAcknowledgement> acks = new ArrayList<>();
        Collection<AckRequestedType> requested = new ArrayList<>();

        String rmUri = null;
        EncoderDecoder codec = null;
        Iterator<Header> iter = headers.iterator();
        while (iter.hasNext()) {
            Object node = iter.next().getObject();
            if (node instanceof Element) {
                Element elem = (Element) node;
                if (Node.ELEMENT_NODE != elem.getNodeType()) {
                    continue;
                }
                String ns = elem.getNamespaceURI();
                if (rmUri == null && (RM10Constants.NAMESPACE_URI.equals(ns)
                    || RM11Constants.NAMESPACE_URI.equals(ns))) {
                    LOG.log(Level.FINE, "set RM namespace {0}", ns);
                    rmUri = ns;
                    rmps.exposeAs(rmUri);
                }
                if (rmUri != null && rmUri.equals(ns)) {
                    if (codec == null) {
                        String wsauri = null;
                        AddressingProperties maps = ContextUtils.retrieveMAPs(message, false, false, false);
                        if (maps == null) {
                            RMConfiguration config = getManager(message).getEffectiveConfiguration(message);
                            wsauri = config.getAddressingNamespace();
                        } else {
                            wsauri = maps.getNamespaceURI();
                        }
                        ProtocolVariation protocol = ProtocolVariation.findVariant(rmUri, wsauri);
                        if (protocol == null) {
                            LOG.log(Level.WARNING, "NAMESPACE_ERROR_MSG", wsauri);
                            break;
                        }
                        codec = protocol.getCodec();
                    }
                    String localName = elem.getLocalName();
                    LOG.log(Level.FINE, "decoding RM header {0}", localName);
                    if (RMConstants.SEQUENCE_NAME.equals(localName)) {
                        rmps.setSequence(codec.decodeSequenceType(elem));
                        rmps.setCloseSequence(codec.decodeSequenceTypeCloseSequence(elem));
                    } else if (RMConstants.SEQUENCE_ACK_NAME.equals(localName)) {
                        acks.add(codec.decodeSequenceAcknowledgement(elem));
                    } else if (RMConstants.ACK_REQUESTED_NAME.equals(localName)) {
                        requested.add(codec.decodeAckRequestedType(elem));
                    }
                }
            }
        }
        if (!acks.isEmpty()) {
            rmps.setAcks(acks);
        }
        if (!requested.isEmpty()) {
            rmps.setAcksRequested(requested);
        }
    } catch (JAXBException ex) {
        LOG.log(Level.WARNING, "SOAP_HEADER_DECODE_FAILURE_MSG", ex);
    }
}
 
Example 11
Source File: TestCaseEngine.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public static void setComponent(Element rootElement) {
    NodeList testLst = rootElement.getElementsByTagName("test");
    for (int j = 0; j < testLst.getLength(); j++) {
        Element testElement = (Element)testLst.item(j);

        if (testElement.getNodeType() == Node.ELEMENT_NODE) {
            Element itemElement = testElement;

            // get test case name
            NodeList testCaseNameList = itemElement.getElementsByTagName("testname");
            if (testCaseNameList != null) {
                s_testCaseName = ((Element)testCaseNameList.item(0)).getTextContent();
            }

            if (s_isSanity == true && !s_testCaseName.equals("SANITY TEST"))
                continue;
            else if (s_isRegression == true && !(s_testCaseName.equals("SANITY TEST") || s_testCaseName.equals("REGRESSION TEST")))
                continue;

            // set class name
            NodeList className = itemElement.getElementsByTagName("class");
            if ((className.getLength() == 0) || (className == null)) {
                s_componentMap.put(s_testCaseName, "com.cloud.test.regression.VMApiTest");
            } else {
                String name = ((Element)className.item(0)).getTextContent();
                s_componentMap.put(s_testCaseName, name);
            }

            // set input file name
            NodeList inputFileNameLst = itemElement.getElementsByTagName("filename");
            s_inputFile.put(s_testCaseName, new ArrayList<String>());
            for (int k = 0; k < inputFileNameLst.getLength(); k++) {
                String inputFileName = ((Element)inputFileNameLst.item(k)).getTextContent();
                s_inputFile.get(s_testCaseName).add(inputFileName);
            }
        }
    }

    //If sanity test required, make sure that SANITY TEST componennt got loaded
    if (s_isSanity == true && s_componentMap.size() == 0) {
        s_logger.error("FAILURE!!! Failed to load SANITY TEST component. Verify that the test is uncommented in adapter.xml");
        System.exit(1);
    }

    if (s_isRegression == true && s_componentMap.size() != 2) {
        s_logger.error("FAILURE!!! Failed to load SANITY TEST or REGRESSION TEST components. Verify that these tests are uncommented in adapter.xml");
        System.exit(1);
    }

    // put all keys from _componentMap to the ArrayList
    Set<?> set = s_componentMap.entrySet();
    Iterator<?> it = set.iterator();
    while (it.hasNext()) {
        Map.Entry<?, ?> me = (Map.Entry<?, ?>)it.next();
        String key = (String)me.getKey();
        s_keys.add(key);
    }

}