List of usage examples for org.w3c.dom Node getLocalName
public String getLocalName();
From source file:eu.europa.esig.dss.xades.validation.XAdESSignature.java
@Override public SignatureProductionPlace getSignatureProductionPlace() { NodeList nodeList = DSSXMLUtils.getNodeList(signatureElement, xPathQueryHolder.XPATH_PRODUCTION_PLACE); if ((nodeList.getLength() == 0) || (nodeList.item(0) == null)) { nodeList = DSSXMLUtils.getNodeList(signatureElement, xPathQueryHolder.XPATH_PRODUCTION_PLACE_V2); if ((nodeList.getLength() == 0) || (nodeList.item(0) == null)) { return null; }//ww w . j a v a2 s. co m } final SignatureProductionPlace signatureProductionPlace = new SignatureProductionPlace(); final NodeList list = nodeList.item(0).getChildNodes(); for (int ii = 0; ii < list.getLength(); ii++) { final Node item = list.item(ii); final String name = item.getLocalName(); final String nodeValue = item.getTextContent(); if (XPathQueryHolder.XMLE_CITY.equals(name)) { signatureProductionPlace.setCity(nodeValue); } else if (XPathQueryHolder.XMLE_STATE_OR_PROVINCE.equals(name)) { signatureProductionPlace.setStateOrProvince(nodeValue); } else if (XPathQueryHolder.XMLE_POSTAL_CODE.equals(name)) { signatureProductionPlace.setPostalCode(nodeValue); } else if (XPathQueryHolder.XMLE_COUNTRY_NAME.equals(name)) { signatureProductionPlace.setCountryName(nodeValue); } else if (XPathQueryHolder.XMLE_STREET_ADDRESS.equals(name)) { signatureProductionPlace.setStreetAddress(nodeValue); } } return signatureProductionPlace; }
From source file:com.nortal.jroad.typegen.xmlbeans.XteeSchemaCodePrinter.java
private Node findFirstNode(final NodeList nodeList, final String elementName, final String name, boolean processChildElements) { for (int i = 0; i < nodeList.getLength(); i++) { Node nNode = nodeList.item(i).cloneNode(true); String localName = nNode.getLocalName(); if (localName != null && nNode.getLocalName().equals(elementName)) { if (name == null) { return nNode; } else { if (nNode.hasAttributes()) { Node attrbute = nNode.getAttributes().getNamedItem("name"); if (attrbute != null && StringUtils.equals(attrbute.getNodeValue(), name)) { return nNode; }//from w w w . java 2 s . c o m } } } if (!processChildElements && "element".equals(localName)) { continue; } if (nNode.hasChildNodes()) { nNode = findFirstNode(nNode.getChildNodes(), elementName, name, processChildElements); if (nNode != null) { return nNode; } } } return null; }
From source file:eu.europa.esig.dss.xades.validation.XAdESSignature.java
/** * This method must not be called more than once. *//*w ww. java2 s .c o m*/ private void makeTimestampTokens() { contentTimestamps = new ArrayList<TimestampToken>(); signatureTimestamps = new ArrayList<TimestampToken>(); refsOnlyTimestamps = new ArrayList<TimestampToken>(); sigAndRefsTimestamps = new ArrayList<TimestampToken>(); archiveTimestamps = new ArrayList<TimestampToken>(); // TODO (20/12/2014): Browse in the physical order final NodeList allDataObjectsTimestamps = DSSXMLUtils.getNodeList(signatureElement, xPathQueryHolder.XPATH_ALL_DATA_OBJECTS_TIMESTAMP); addContentTimestamps(contentTimestamps, allDataObjectsTimestamps, TimestampType.ALL_DATA_OBJECTS_TIMESTAMP); final NodeList individualDataObjectsTimestampsNodes = DSSXMLUtils.getNodeList(signatureElement, xPathQueryHolder.XPATH_INDIVIDUAL_DATA_OBJECTS_TIMESTAMP); addContentTimestamps(contentTimestamps, individualDataObjectsTimestampsNodes, TimestampType.INDIVIDUAL_DATA_OBJECTS_TIMESTAMP); final Element unsignedSignaturePropertiesDom = getUnsignedSignaturePropertiesDom(); if (unsignedSignaturePropertiesDom == null) { return; } final List<String> timestampedTimestamps = new ArrayList<String>(); final NodeList unsignedProperties = unsignedSignaturePropertiesDom.getChildNodes(); for (int ii = 0; ii < unsignedProperties.getLength(); ii++) { final Node node = unsignedProperties.item(ii); if (node.getNodeType() != Node.ELEMENT_NODE) { // This can happened // when there is a // blank line // between tags. continue; } TimestampToken timestampToken; final String localName = node.getLocalName(); if (XMLE_SIGNATURE_TIME_STAMP.equals(localName)) { timestampToken = makeTimestampToken((Element) node, TimestampType.SIGNATURE_TIMESTAMP); if (timestampToken == null) { continue; } timestampToken.setTimestampedReferences(getSignatureTimestampedReferences()); signatureTimestamps.add(timestampToken); } else if (XMLE_REFS_ONLY_TIME_STAMP.equals(localName) || XPathQueryHolder.XMLE_REFS_ONLY_TIME_STAMP_V2.equals(localName)) { timestampToken = makeTimestampToken((Element) node, TimestampType.VALIDATION_DATA_REFSONLY_TIMESTAMP); if (timestampToken == null) { continue; } timestampToken.setTimestampedReferences(getTimestampedReferences()); refsOnlyTimestamps.add(timestampToken); } else if (XMLE_SIG_AND_REFS_TIME_STAMP.equals(localName) || XPathQueryHolder.XMLE_SIG_AND_REFS_TIME_STAMP_V2.equals(localName)) { timestampToken = makeTimestampToken((Element) node, TimestampType.VALIDATION_DATA_TIMESTAMP); if (timestampToken == null) { continue; } final List<TimestampReference> references = getSignatureTimestampedReferences(); references.addAll(getTimestampedReferences()); timestampToken.setTimestampedReferences(references); sigAndRefsTimestamps.add(timestampToken); } else if (isArchiveTimestamp(localName)) { timestampToken = makeTimestampToken((Element) node, TimestampType.ARCHIVE_TIMESTAMP); if (timestampToken == null) { continue; } final ArchiveTimestampType archiveTimestampType = getArchiveTimestampType(node, localName); timestampToken.setArchiveTimestampType(archiveTimestampType); final List<TimestampReference> references = getSignatureTimestampedReferences(); for (final String timestampId : timestampedTimestamps) { final TimestampReference signatureReference_ = new TimestampReference(timestampId); references.add(signatureReference_); } references.addAll(getTimestampedReferences()); final List<CertificateToken> encapsulatedCertificates = getCertificateSource() .getEncapsulatedCertificates(); for (final CertificateToken certificateToken : encapsulatedCertificates) { final TimestampReference certificateTimestampReference = createCertificateTimestampReference( certificateToken); if (!references.contains(certificateTimestampReference)) { references.add(certificateTimestampReference); } } // TODO (20/12/2014): ValidationData references to be added timestampToken.setTimestampedReferences(references); archiveTimestamps.add(timestampToken); } else { continue; } timestampedTimestamps.add(String.valueOf(timestampToken.getDSSId())); } }
From source file:com.nortal.jroad.typegen.xmlbeans.XteeSchemaCodePrinter.java
private String findXteeTitle(SchemaProperty prop) throws IOException { String xteeTitle = null;// ww w. j ava 2s . co m try { String localPart = prop.getName().getLocalPart(); Node propNode = ((SchemaTypeImpl) prop.getContainerType()).getParseObject().getDomNode(); Node node = propNode; if (StringUtils.equals(localPart, "item") || StringUtils.equals(localPart, "all")) { while (true) { if (StringUtils.equals(node.getLocalName(), "element")) { localPart = node.getAttributes().getNamedItem("name").getNodeValue(); break; } node = node.getParentNode(); if (node == null) { node = findFirstNode(propNode.getChildNodes(), "element", localPart); break; } } } else { node = findFirstNode(node.getChildNodes(), "element", localPart); } if (node != null) { xteeTitle = clearString( getXmlObjectValue(findFirstNode(node.getChildNodes(), "title", null, false))); if (xteeTitle == null) { xteeTitle = StringUtils.capitalize(node.getAttributes().getNamedItem("name").getNodeValue()); } } } catch (Exception e) { throw new IOException(e); } return xteeTitle; }
From source file:eu.europa.esig.dss.xades.validation.XAdESSignature.java
/** * Gathers the data to be used to calculate the hash value sent to the TSA (messageImprint). * * @param timestampToken// w w w. java 2 s . co m * {@code TimestampToken} to validate, or {@code null} when adding a new archive timestamp * @param canonicalizationMethod * @return {@code byte} array containing the canonicalized and concatenated timestamped data */ @Override public byte[] getArchiveTimestampData(final TimestampToken timestampToken, String canonicalizationMethod) { if (LOG.isTraceEnabled()) { LOG.trace("--->Get archive timestamp data:" + (timestampToken == null ? "--> CREATION" : "--> VALIDATION")); } canonicalizationMethod = timestampToken != null ? timestampToken.getCanonicalizationMethod() : canonicalizationMethod; /** * 8.2.1 Not distributed case<br> * * When xadesv141:ArchiveTimeStamp and all the unsigned properties covered by its time-stamp certificateToken have the same parent, this * property uses the Implicit mechanism for all the time-stamped data objects. The input to the computation of the digest value MUST be built * as follows: */ try { /** * 1) Initialize the final octet stream as an empty octet stream. */ final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); /** * 2) Take all the ds:Reference elements in their order of appearance within ds:SignedInfo referencing whatever the signer wants to sign * including the SignedProperties element. Process each one as indicated below:<br> * - Process the retrieved ds:Reference element according to the reference processing model of XMLDSIG.<br> * - If the result is a XML node set, canonicalize it. If ds:Canonicalization is present, the algorithm indicated by this element is used. * If not, the standard canonicalization method specified by XMLDSIG is used.<br> * - Concatenate the resulting octets to the final octet stream. */ /** * The references are already calculated {@see #checkSignatureIntegrity()} */ final Set<String> referenceURIs = new HashSet<String>(); for (final Reference reference : references) { try { String uri = reference.getURI(); if (uri.startsWith("#")) { uri = uri.substring(1); } referenceURIs.add(uri); final byte[] bytes = reference.getReferencedBytes(); DSSUtils.write(bytes, buffer); } catch (XMLSignatureException e) { throw new DSSException(e); } } /** * 3) Take the following XMLDSIG elements in the order they are listed below, canonicalize each one and concatenate each resulting octet * stream to the final octet stream:<br> * - The ds:SignedInfo element.<br> * - The ds:SignatureValue element.<br> * - The ds:KeyInfo element, if present. */ writeCanonicalizedValue(xPathQueryHolder.XPATH_SIGNED_INFO, canonicalizationMethod, buffer); writeCanonicalizedValue(xPathQueryHolder.XPATH_SIGNATURE_VALUE, canonicalizationMethod, buffer); writeCanonicalizedValue(xPathQueryHolder.XPATH_KEY_INFO, canonicalizationMethod, buffer); /** * 4) Take the unsigned signature properties that appear before the current xadesv141:ArchiveTimeStamp in the order they appear within the * xades:UnsignedSignatureProperties, canonicalize each one and concatenate each resulting octet stream to the final octet stream. While * concatenating the following rules apply: */ final Element unsignedSignaturePropertiesDom = getUnsignedSignaturePropertiesDom(); if (unsignedSignaturePropertiesDom == null) { throw new NullPointerException(xPathQueryHolder.XPATH_UNSIGNED_SIGNATURE_PROPERTIES); } final NodeList unsignedProperties = unsignedSignaturePropertiesDom.getChildNodes(); for (int ii = 0; ii < unsignedProperties.getLength(); ii++) { final Node node = unsignedProperties.item(ii); if (node.getNodeType() != Node.ELEMENT_NODE) { // This can // happened when // there is a // blank line // between tags. continue; } final String localName = node.getLocalName(); // In the SD-DSS implementation when validating the signature // the framework will not add missing data. To do so the // signature must be extended. // if (localName.equals("CertificateValues")) { /* * - The xades:CertificateValues property MUST be added if it is not already present and the ds:KeyInfo element does not contain the * full set of certificates used to validate the electronic signature. */ // } else if (localName.equals("RevocationValues")) { /* * - The xades:RevocationValues property MUST be added if it is not already present and the ds:KeyInfo element does not contain the * revocation information that has to be shipped with the electronic signature */ // } else if (localName.equals("AttrAuthoritiesCertValues")) { /* * - The xades:AttrAuthoritiesCertValues property MUST be added if not already present and the following conditions are true: there * exist an attribute certificate in the signature AND a number of certificates that have been used in its validation do not appear in * CertificateValues. Its content will satisfy with the rules specified in clause 7.6.3. */ // } else if (localName.equals("AttributeRevocationValues")) { /* * - The xades:AttributeRevocationValues property MUST be added if not already present and there the following conditions are true: * there exist an attribute certificate AND some revocation data that have been used in its validation do not appear in * RevocationValues. Its content will satisfy with the rules specified in clause 7.6.4. */ // } else if (isArchiveTimestamp(localName)) { if ((timestampToken != null) && (timestampToken.getHashCode() == node.hashCode())) { break; } } else if ("TimeStampValidationData".equals(localName)) { /** * ETSI TS 101 903 V1.4.2 (2010-12) 8.1 The new XAdESv141:TimeStampValidationData element ../.. This element is specified to serve * as an optional container for validation data required for carrying a full verification of time-stamp tokens embedded within any * of the different time-stamp containers defined in the present document. ../.. 8.1.1 Use of URI attribute ../.. a new * xadesv141:TimeStampValidationData element SHALL be created containing the missing validation data information and it SHALL be * added as a child of UnsignedSignatureProperties elements immediately after the respective time-stamp certificateToken container * element. */ } byte[] canonicalizedValue; if (timestampToken == null) { // Creation of the timestamp /** * This is the work around for the name space problem: The issue was reported on: * https://issues.apache.org/jira/browse/SANTUARIO-139 and considered as close. But for me (Bob) it still does not work! */ final byte[] bytesToCanonicalize = DSSXMLUtils.serializeNode(node); canonicalizedValue = DSSXMLUtils.canonicalize(canonicalizationMethod, bytesToCanonicalize); } else { canonicalizedValue = DSSXMLUtils.canonicalizeSubtree(canonicalizationMethod, node); } if (LOG.isTraceEnabled()) { LOG.trace(localName + ": Canonicalization: " + canonicalizationMethod); LOG.trace(new String(canonicalizedValue) + "\n"); } buffer.write(canonicalizedValue); } /** * 5) Take all the ds:Object elements except the one containing xades:QualifyingProperties element. Canonicalize each one and concatenate * each resulting octet stream to the final octet stream. If ds:Canonicalization is present, the algorithm indicated by this element is * used. If not, the standard canonicalization method specified by XMLDSIG is used. */ boolean xades141 = (timestampToken == null) || !ArchiveTimestampType.XAdES.equals(timestampToken.getArchiveTimestampType()); final NodeList objects = getObjects(); for (int ii = 0; ii < objects.getLength(); ii++) { final Node node = objects.item(ii); final Node qualifyingProperties = DSSXMLUtils.getElement(node, xPathQueryHolder.XPATH__QUALIFYING_PROPERTIES); if (qualifyingProperties != null) { continue; } if (!xades141) { /** * !!! ETSI TS 101 903 V1.3.2 (2006-03) 5) Take any ds:Object element in the signature that is not referenced by any ds:Reference * within ds:SignedInfo, except that one containing the QualifyingProperties element. Canonicalize each one and concatenate each * resulting octet stream to the final octet stream. If ds:Canonicalization is present, the algorithm indicated by this element is * used. If not, the standard canonicalization method specified by XMLDSIG is used. */ final NamedNodeMap attributes = node.getAttributes(); final int length = attributes.getLength(); String id = ""; for (int jj = 0; jj < length; jj++) { final Node item = attributes.item(jj); final String nodeName = item.getNodeName(); if ("ID".equals(nodeName.toUpperCase())) { id = item.getNodeValue(); break; } } final boolean contains = referenceURIs.contains(id); if (contains) { continue; } } byte[] canonicalizedValue = DSSXMLUtils.canonicalizeSubtree(canonicalizationMethod, node); buffer.write(canonicalizedValue); } final byte[] bytes = buffer.toByteArray(); return bytes; } catch (IOException e) { throw new DSSException("Error when computing the archive data", e); } }
From source file:com.amalto.core.history.accessor.ManyFieldAccessor.java
public void create() { parent.create();/*from w w w . j a va2 s . co m*/ // TODO Refactor this Document domDocument = document.asDOM(); Node node = getCollectionItemNode(); if (node == null) { Element parentNode = (Element) parent.getNode(); NodeList children = parentNode.getElementsByTagName(fieldName); int currentCollectionSize = children.getLength(); if (currentCollectionSize > 0) { Node refNode = children.item(currentCollectionSize - 1).getNextSibling(); while (currentCollectionSize <= index) { node = domDocument.createElementNS(domDocument.getNamespaceURI(), fieldName); parentNode.insertBefore(node, refNode); currentCollectionSize++; } } else { // Collection is not present at all, append at the end of parent element. Node lastAccessedNode = document.getLastAccessedNode(); if (lastAccessedNode != null) { Node refNode = lastAccessedNode.getNextSibling(); while (refNode != null && !(refNode instanceof Element)) { refNode = refNode.getNextSibling(); } while (currentCollectionSize <= index) { node = domDocument.createElementNS(domDocument.getNamespaceURI(), fieldName); if (lastAccessedNode == parentNode) { if (lastAccessedNode == document.asDOM().getDocumentElement() && lastAccessedNode.getChildNodes().getLength() > 0) parentNode.insertBefore(node, parentNode.getFirstChild()); else parentNode.appendChild(node); } else if (refNode != null && refNode.getParentNode() == parentNode) { parentNode.insertBefore(node, refNode); } else { parentNode.appendChild(node); } currentCollectionSize++; } } else { while (currentCollectionSize <= index) { node = domDocument.createElementNS(domDocument.getNamespaceURI(), fieldName); parentNode.appendChild(node); currentCollectionSize++; } } } document.setLastAccessedNode(node); } else if (node.getChildNodes().getLength() == 0) { // This accessor creates (n-1) empty elements when accessing first collection element at index n. // This setLastAccessedNode call allows all (n-1) elements to find their parent. if (!(node.getLocalName().equals(document.getLastAccessedNode().getLocalName()) && document.getLastAccessedNode().getParentNode() == node.getParentNode())) { // if last accessed node is parallel with this node, can't modify last accessed node. eg, last accessed // node=/feature/vendor[2], this node=/feature/vendor[1], the last accessed is still /feature/vendor[2] document.setLastAccessedNode(node); } } }
From source file:com.amalto.workbench.editors.DataModelMainPage.java
private void createToolBar(Composite parent) { Composite toolBarComp = new Composite(parent, SWT.BORDER); GridData gd = new GridData(SWT.FILL, SWT.TOP, true, false, 2, 1); gd.heightHint = 25;//from w w w . j a v a 2 s.co m toolBarComp.setLayoutData(gd); final GridLayout glToolBarBackground = new GridLayout(); glToolBarBackground.verticalSpacing = 0; glToolBarBackground.marginWidth = 0; glToolBarBackground.marginHeight = 0; glToolBarBackground.horizontalSpacing = 0; toolBarComp.setLayout(glToolBarBackground); ToolBar resultToolBar = new ToolBar(toolBarComp, SWT.FLAT | SWT.HORIZONTAL); gd = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); resultToolBar.setLayoutData(gd); ToolItem importToolItem = new ToolItem(resultToolBar, SWT.PUSH); importToolItem.setImage(ImageCache.getCreatedImage(EImage.IMPORT.getPath())); importToolItem.setToolTipText(Messages.ImportText); importToolItem.setEnabled(!isReadOnly()); ToolItem exportToolItem = new ToolItem(resultToolBar, SWT.PUSH); exportToolItem.setImage(ImageCache.getCreatedImage(EImage.EXPORT.getPath())); exportToolItem.setToolTipText(Messages.ExportText); exportToolItem.setEnabled(!isReadOnly()); ToolItem importSchemalItem = new ToolItem(resultToolBar, SWT.PUSH); importSchemalItem.setImage(ImageCache.getCreatedImage(EImage.CHECKIN_ACTION.getPath())); importSchemalItem.setToolTipText(Messages.ImportIncludeSchema); importSchemalItem.setEnabled(!isReadOnly()); importToolItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { FileDialog fd = new FileDialog(getSite().getShell(), SWT.OPEN); fd.setFilterExtensions(new String[] { "*.xsd", "*.dtd", "*.xml" });//$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ // set the default path to the workspace. fd.setFilterPath(Platform.getInstanceLocation().getURL().getPath().substring(1)); fd.setText(Messages.SelectXMLDefinition); String filename = fd.open(); if (filename == null) { return; } xsdSchema = null; inferXsdFromXml(filename); } private void inferXsdFromXml(String xmlFile) { int infer = 0; String xsd = "";//$NON-NLS-1$ try { String inputType = xmlFile.substring(xmlFile.lastIndexOf("."));//$NON-NLS-1$ if (inputType.equals(".xsd")) {//$NON-NLS-1$ xsd = Util.getXML(xmlFile); xsdSchema = Util.createXsdSchema(xsd, xobject); xsd = Util.nodeToString(xsdSchema.getDocument()); } else { XSDDriver d = new XSDDriver(); infer = d.doMain(new String[] { xmlFile, "out.xsd" });//$NON-NLS-1$ if (infer == 0) { xsd = d.outputXSD(); } } } catch (Exception e) { log.error(e.getMessage(), e); infer = 2; } finally { if (infer == 0 && !xsd.equals("")) {//$NON-NLS-1$ WSDataModel wsObj = (WSDataModel) (xobject.getWsObject()); wsObj.setXsdSchema(xsd); validateSchema(xsd); refreshData(); markDirtyWithoutCommit(); } else if (infer != 0) { MessageDialog.openError(getSite().getShell(), Messages._Error, Messages.XsdSchemaInferred); } } } void validateSchema(String xsd) { try { boolean elem = false; XSDSchema schema = getXSDSchema(xsd); NodeList nodeList = schema.getDocument().getDocumentElement().getChildNodes(); for (int idx = 0; idx < nodeList.getLength(); idx++) { Node node = nodeList.item(idx); if (node instanceof Element && node.getLocalName().indexOf("element") >= 0) {//$NON-NLS-1$ elem = true; break; } } if (!elem) { MessageDialog.openWarning(getSite().getShell(), Messages.Warning, Messages.NoElementNode); } } catch (Exception e) { log.error(e.getMessage(), e); } } }); exportToolItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { FileDialog fd = new FileDialog(getSite().getShell(), SWT.SAVE); fd.setFilterExtensions(new String[] { "*.xsd" });//$NON-NLS-1$ fd.setFilterPath(Platform.getInstanceLocation().getURL().getPath().substring(1)); fd.setText(Messages.SaveDataModuleXSDSchema); String filename = fd.open(); if (filename == null) { return; } inferXsdFromDataModule(filename); } private void inferXsdFromDataModule(String xmlFile) { WSDataModel wsObject = (WSDataModel) (xobject.getWsObject()); XSDDriver d = new XSDDriver(); if (d.outputXSD_UTF_8(wsObject.getXsdSchema(), xmlFile) != null) { MessageDialog.openInformation(getSite().getShell(), Messages.ExportXSD, Messages.OperationExportingXsd); } else { MessageDialog.openError(getSite().getShell(), Messages._Error, Messages.FailedExportXSD); } } }); importSchemalItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { popupImportDialog(); } }); }
From source file:de.escidoc.core.test.EscidocTestBase.java
/** * Gets the local name (the node name without the namespace prefix) of the provided node. * // w ww . j ava 2s . c om * @param node * The node to extract the name from. * @return Returns <code>node.getLocalName</code> if this is set, or the value of <code>node.getNodeName</code> * without the namespace prefix. */ private static String getLocalName(final Node node) { String name = node.getLocalName(); if (name == null) { name = node.getNodeName().replaceAll(".*?:", ""); } return name; }
From source file:de.escidoc.core.test.EscidocTestBase.java
/** * Assert XML content is equal.<br/> * <p/>/*w w w. jav a 2 s. c o m*/ * This methods compares the attributes (if any exist) and either recursively compares the child elements (if any * exists) or the text content.<br/> * Therefore, mixed content is NOT supported by this method. * * @param messageIn * The message printed if assertion fails. * @param expected * The expected XML content. * @param toBeAsserted * The XML content to be compared with the expected content. * @throws Exception * If anything fails. */ public static void assertXmlEquals(final String messageIn, final Node expected, final Node toBeAsserted) throws Exception { // Assert both nodes are null or both nodes are not null if (expected == null) { assertNull(messageIn + "Unexpected node. ", toBeAsserted); return; } assertNotNull(messageIn + " Expected node. ", toBeAsserted); if (expected.equals(toBeAsserted)) { return; } String nodeName = getLocalName(expected); String message = messageIn; if (!message.contains("-- Asserting ")) { message = message + "-- Asserting " + nodeName + ". "; } else { message = message + "/" + nodeName; } // assert both nodes are nodes of the same node type // if thedocument container xslt directive than is the nodeName // "#document" is here compared assertEquals(message + " Type of nodes are different", expected.getNodeType(), toBeAsserted.getNodeType()); if (expected.getNodeType() == Node.TEXT_NODE) { assertEquals(message + " Text nodes are different. ", expected.getTextContent().trim(), toBeAsserted.getTextContent().trim()); } // assert attributes NamedNodeMap expectedAttributes = expected.getAttributes(); NamedNodeMap toBeAssertedAttributes = toBeAsserted.getAttributes(); if (expectedAttributes == null) { assertNull(message + " Unexpected attributes. [" + nodeName + "]", toBeAssertedAttributes); } else { assertNotNull(message + " Expected attributes. ", toBeAssertedAttributes); final int expectedNumberAttributes = expectedAttributes.getLength(); for (int i = 0; i < expectedNumberAttributes; i++) { Node expectedAttribute = expectedAttributes.item(i); String expectedAttributeNamespace = expectedAttribute.getNamespaceURI(); Node toBeAssertedAttribute = null; if (expectedAttributeNamespace != null) { final String localName = expectedAttribute.getLocalName(); toBeAssertedAttribute = toBeAssertedAttributes.getNamedItemNS(expectedAttributeNamespace, localName); assertNotNull(message + " Expected attribute " + expectedAttribute.getNodeName(), toBeAssertedAttribute); } else { // not namespace aware parsed. Attributes may have different // prefixes which are now part of their node name. // To compare expected and to be asserted attribute, it is // first it is tried to find the appropriate to be asserted // attribute by the node name. If this fails, xpath // selection is used after extracting the expected // attribute name final String expectedAttributeNodeName = expectedAttribute.getNodeName(); toBeAssertedAttribute = toBeAssertedAttributes.getNamedItem(expectedAttributeNodeName); if (toBeAssertedAttribute == null) { final String attributeName = getLocalName(expectedAttribute); final String attributeXpath = "@" + attributeName; toBeAssertedAttribute = selectSingleNode(toBeAsserted, attributeXpath); } assertNotNull(message + " Expected attribute " + expectedAttributeNodeName, toBeAssertedAttribute); } assertEquals(message + " Attribute value mismatch [" + expectedAttribute.getNodeName() + "] ", expectedAttribute.getTextContent(), toBeAssertedAttribute.getTextContent()); } } // As mixed content (text + child elements) is not supported, // either the child elements or the text content have to be asserted. // Therefore, it is first tried to assert the children. // After that it is checked if children have been found. If this is not // the case, the text content is compared. NodeList expectedChildren = expected.getChildNodes(); NodeList toBeAssertedChildren = toBeAsserted.getChildNodes(); int expectedNumberElementNodes = 0; int toBeAssertedNumberElementNodes = 0; List<Node> previouslyAssertedChildren = new ArrayList<Node>(); for (int i = 0; i < expectedChildren.getLength(); i++) { Node expectedChild = expectedChildren.item(i); if (expectedChild.getNodeType() == Node.ELEMENT_NODE) { expectedNumberElementNodes++; String expectedChildName = getLocalName(expectedChild); String expectedUri = expectedChild.getNamespaceURI(); boolean expectedElementAsserted = false; for (int j = 0; j < toBeAssertedChildren.getLength(); j++) { final Node toBeAssertedChild = toBeAssertedChildren.item(j); // prevent previously asserted children from being // asserted again if (previouslyAssertedChildren.contains(toBeAssertedChild)) { continue; } if (toBeAssertedChild.getNodeType() == Node.ELEMENT_NODE && expectedChildName.equals(getLocalName(toBeAssertedChild)) && (expectedUri == null || expectedUri.equals(toBeAssertedChild.getNamespaceURI()))) { expectedElementAsserted = true; toBeAssertedNumberElementNodes++; assertXmlEquals(message, expectedChild, toBeAssertedChild); // add asserted child to list of asserted children to // prevent it from being asserted again. previouslyAssertedChildren.add(toBeAssertedChild); break; } } if (!expectedElementAsserted) { fail(new StringBuffer(message).append(" Did not found expected corresponding element [") .append(nodeName).append(", ").append(expectedChildName).append(", ").append(i) .append("]").toString()); } } } // check if any element node in toBeAssertedChildren exists // that has not been asserted. In this case, this element node // is unexpected! for (int i = 0; i < toBeAssertedChildren.getLength(); i++) { Node toBeAssertedChild = toBeAssertedChildren.item(i); // prevent previously asserted children from being // asserted again if (previouslyAssertedChildren.contains(toBeAssertedChild)) { continue; } if (toBeAssertedChild.getNodeType() == Node.ELEMENT_NODE) { fail(new StringBuffer(message).append("Found unexpected element node [").append(nodeName) .append(", ").append(getLocalName(toBeAssertedChild)).append(", ").append(i).append("]") .toString()); } } // if no children have been found, text content must be compared if (expectedNumberElementNodes == 0 && toBeAssertedNumberElementNodes == 0) { String expectedContent = expected.getTextContent(); String toBeAssertedContent = toBeAsserted.getTextContent(); assertEquals(message, expectedContent, toBeAssertedContent); } }
From source file:de.betterform.xml.xforms.model.submission.Submission.java
/** * Performs replace processing according to section 11.1, para 5. *//*from w w w . ja va 2s. c o m*/ protected void submitReplaceText(Map response) throws XFormsException { if (getLogger().isDebugEnabled()) { getLogger().debug(this + " submit: replacing text"); } Node targetNode; if (this.targetExpr != null) { targetNode = XPathUtil .getAsNode( XPathCache.getInstance() .evaluate( this.instance == null ? evalInScopeContext() : this.model.getInstance(this.instance).getRootContext() .getNodeset(), 1, this.targetExpr, this.prefixMapping, this.xpathFunctionContext), 1); } else if (this.instance == null) { targetNode = this.model.getInstance(getInstanceId()).getInstanceDocument().getDocumentElement(); } else { targetNode = this.model.getInstance(this.instance).getInstanceDocument().getDocumentElement(); } final InputStream responseStream = (InputStream) response.get(XFormsProcessor.SUBMISSION_RESPONSE_STREAM); StringBuilder text = new StringBuilder(512); try { String contentType = (String) response.get("Content-Type"); String encoding = "UTF-8"; if (contentType != null) { final String[] contTypeEntries = contentType.split(", ?"); for (int i = 0; i < contTypeEntries.length; i++) { if (contTypeEntries[i].startsWith("charset=")) { encoding = contTypeEntries[i].substring(8); } } } byte[] buffer = new byte[512]; int bytesRead; while ((bytesRead = responseStream.read(buffer)) > 0) { text.append(new String(buffer, 0, bytesRead, encoding)); } responseStream.close(); } catch (Exception e) { // todo: check for response media type (needs submission response // refactoring) in order to dispatch xforms-link-exception throw new XFormsSubmitError("instance parsing failed", e, this.getTarget(), XFormsSubmitError.constructInfoObject(this.element, this.container, locationPath, XFormsConstants.PARSE_ERROR, getResourceURI(), 200d, null, "", "")); } if (targetNode == null) { throw new XFormsSubmitError("Invalid target", this.getTarget(), XFormsSubmitError.constructInfoObject(this.element, this.container, locationPath, XFormsConstants.TARGET_ERROR, getResourceURI(), 200d, null, "", "")); } else if (targetNode.getNodeType() == Node.ELEMENT_NODE) { while (targetNode.getFirstChild() != null) { targetNode.removeChild(targetNode.getFirstChild()); } targetNode.appendChild(targetNode.getOwnerDocument().createTextNode(text.toString())); } else if (targetNode.getNodeType() == Node.ATTRIBUTE_NODE) { targetNode.setNodeValue(text.toString()); } else { LOGGER.warn("Don't know how to handle targetNode '" + targetNode.getLocalName() + "', node is neither an element nor an attribute Node"); } // perform rebuild, recalculate, revalidate, and refresh this.model.rebuild(); this.model.recalculate(); this.model.revalidate(); this.container.refresh(); // deferred update behaviour UpdateHandler updateHandler = this.model.getUpdateHandler(); if (updateHandler != null) { updateHandler.doRebuild(false); updateHandler.doRecalculate(false); updateHandler.doRevalidate(false); updateHandler.doRefresh(false); } // dispatch xforms-submit-done this.container.dispatch(this.target, XFormsEventNames.SUBMIT_DONE, constructEventInfo(response)); }