Java Code Examples for org.custommonkey.xmlunit.XMLUnit#setIgnoreAttributeOrder()

The following examples show how to use org.custommonkey.xmlunit.XMLUnit#setIgnoreAttributeOrder() . 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: TransformationUtilityTestHelper.java    From butterfly with MIT License 6 votes vote down vote up
/**
 * Assert that the specified XML file has not semantically changed,
 * although it might be identical to the original one due to format
 * changes, comments not being present, etc
 *
 * @param relativeFilePath relative path to file to be evaluated
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 */
protected void assertEqualsXml(String relativeFilePath) throws ParserConfigurationException, IOException, SAXException {
    File originalFile = new File(appFolder, relativeFilePath);
    File transformedFile = new File(transformedAppFolder, relativeFilePath);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);
    factory.setCoalescing(true);
    factory.setIgnoringElementContentWhitespace(true);
    factory.setIgnoringComments(true);

    DocumentBuilder builder = factory.newDocumentBuilder();
    Document originalXml = builder.parse(originalFile);
    Document transformedXml = builder.parse(transformedFile);

    originalXml.normalizeDocument();
    transformedXml.normalizeDocument();

    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setIgnoreComments(true);
    XMLUnit.setIgnoreWhitespace(true);

    Assert.assertTrue(XMLUnit.compareXML(originalXml, transformedXml).similar());
}
 
Example 2
Source File: TckValidator.java    From juddi with Apache License 2.0 6 votes vote down vote up
public static void checkKeyInfo(KeyInfoType kit1, KeyInfoType kit2) {
    if (kit1 == null || kit2 == null) {
            assertEquals(kit1, kit2);
            return;
    }
    assertEquals(kit1.getId(), kit2.getId());

    DOMResult domResult1 = new DOMResult();
    DOMResult domResult2 = new DOMResult();
    JAXB.marshal(kit1, domResult1);
    JAXB.marshal(kit2, domResult2);
    
    Document doc1 = (Document)domResult1.getNode();
    DOMSource domSource1 = new DOMSource(doc1.getDocumentElement());
    Document doc2 = (Document)domResult2.getNode();
    DOMSource domSource2 = new DOMSource(doc2.getDocumentElement());
    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setIgnoreComments(true);
    XMLUnit.setIgnoreWhitespace(true);
    Diff diff = new Diff(domSource1, domSource2);
    assertTrue("Key info elements should match", diff.similar());
}
 
Example 3
Source File: TransformExtensionsTest.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void beforeClass() throws IOException {
  Common.connect();
  Common.connectAdmin();

  XMLUnit.setIgnoreAttributeOrder(true);
  XMLUnit.setIgnoreWhitespace(true);
  XMLUnit.setNormalize(true);
  XMLUnit.setNormalizeWhitespace(true);
  XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true);

  Map<String,String> namespaces = new HashMap<>();
  namespaces.put("xsl",  "http://www.w3.org/1999/XSL/Transform");
  namespaces.put("rapi", "http://marklogic.com/rest-api");

  SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext(namespaces);

  xpather = XMLUnit.newXpathEngine();
  xpather.setNamespaceContext(namespaceContext);

  xqueryTransform = Common.testFileToString(XQUERY_FILE, "UTF-8");
  xslTransform    = Common.testFileToString(XSLT_FILE, "UTF-8");
}
 
Example 4
Source File: LdapSenderTest.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Before
public void startLdapServer() throws LDAPException, IOException {
	XMLUnit.setIgnoreWhitespace(true);
	XMLUnit.setIgnoreAttributeOrder(true);

	InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(
			baseDNs);
	config.setSchema(null);
	inMemoryDirectoryServer = new InMemoryDirectoryServer(config);

	String ldifDataFile = "Ldap/data.ldif";
	URL ldifDataUrl = ClassUtils.getResourceURL(this, ldifDataFile);
	if (ldifDataUrl == null) {
		throw new IOException("cannot find resource [" + ldifDataFile + "]");
	}
	inMemoryDirectoryServer.importFromLDIF(true, ldifDataUrl.getPath());
	inMemoryDirectoryServer.startListening();
}
 
Example 5
Source File: BufferableHandleTest.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void beforeClass() {
  Common.connect();

  XMLUnit.setIgnoreAttributeOrder(true);
  XMLUnit.setIgnoreWhitespace(true);
  XMLUnit.setNormalize(true);
  XMLUnit.setNormalizeWhitespace(true);
  XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true);

  Map<String,String> namespaces = new HashMap<>();
  namespaces.put("rapi", "http://marklogic.com/rest-api");
  namespaces.put("prop", "http://marklogic.com/xdmp/property");
  namespaces.put("xs",   "http://www.w3.org/2001/XMLSchema");
  namespaces.put("xsi",  "http://www.w3.org/2001/XMLSchema-instance");

  SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext(namespaces);

  xpather = XMLUnit.newXpathEngine();
  xpather.setNamespaceContext(namespaceContext);
}
 
Example 6
Source File: Bug5446Test.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    final SchemaContext schemaContext = YangParserTestUtils.parseYangResource("/bug5446/yang/foo.yang");
    final Document doc = loadDocument("/bug5446/xml/foo.xml");

    final ContainerNode docNode = createDocNode();

    Optional<DataContainerChild<? extends PathArgument, ?>> root = docNode.getChild(new NodeIdentifier(ROOT_QNAME));
    assertTrue(root.orElse(null) instanceof ContainerNode);

    Optional<DataContainerChild<? extends PathArgument, ?>> child = ((ContainerNode) root.orElse(null))
            .getChild(new NodeIdentifier(IP_ADDRESS_QNAME));
    assertTrue(child.orElse(null) instanceof LeafNode);
    LeafNode<?> ipAdress = (LeafNode<?>) child.get();

    Object value = ipAdress.getValue();
    assertTrue(value instanceof byte[]);
    assertEquals("fwAAAQ==", Base64.getEncoder().encodeToString((byte[]) value));

    DOMResult serializationResult = writeNormalizedNode(docNode, schemaContext);
    assertNotNull(serializationResult);

    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setIgnoreComments(true);
    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setNormalize(true);

    String expectedXMLString = toString(doc.getDocumentElement());
    String serializationResultXMLString = toString(serializationResult.getNode());

    assertXMLEqual(expectedXMLString, serializationResultXMLString);
}
 
Example 7
Source File: DLNAServiceTest.java    From Connect-SDK-Android-Core with Apache License 2.0 5 votes vote down vote up
private void assertXMLEquals(String expectedXML, String actualXML) throws SAXException, IOException {
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setNormalize(true);
    DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expectedXML, actualXML));
    List<?> allDifferences = diff.getAllDifferences();
    Assert.assertEquals("XML differences found: " + diff.toString(), 0, allDifferences.size());
}
 
Example 8
Source File: ParallelTest.java    From exificient with MIT License 5 votes vote down vote up
private void testParallelDecode(ParallelExiFactory parallelExiFactory,
		int nbThreads, int nbTask) throws Exception {
	EXIFactory exiFactory = getExiFactory();
	ArrayList<ExiSch> nc1NameExiMap = getExiSch(parallelExiFactory, true,
			exiFactory);
	Collection<Callable<DecodeResult>> tasks = new ArrayList<Callable<DecodeResult>>();
	for (int i = 0; i < nbTask; i++) {
		tasks.add(new TaskDecode(
				nc1NameExiMap.get(i % nc1NameExiMap.size())));
	}

	ExecutorService executor = Executors.newFixedThreadPool(nbThreads);
	List<Future<DecodeResult>> results = executor.invokeAll(tasks);
	int differentExiCount = 0;

	XMLUnit.setIgnoreWhitespace(true);
	XMLUnit.setIgnoreAttributeOrder(true);
	XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true);
	XMLUnit.setIgnoreComments(true);

	for (Future<DecodeResult> result : results) {
		DecodeResult exiResult = result.get();

		Diff diff = compareXML(exiResult.roundTripDoc, exiResult.doc);
		if (!diff.similar()) {
			differentExiCount++;
		}
	}
	executor.shutdown();
	assertEquals(0, differentExiCount);
}
 
Example 9
Source File: DOMRoundtrip.java    From exificient with MIT License 5 votes vote down vote up
protected void isXMLEqual(Document control, Document test)
		throws SAXException, IOException {
	XMLUnit.setIgnoreWhitespace(true);
	XMLUnit.setIgnoreAttributeOrder(true);
	XMLUnit.setIgnoreComments(true);
	XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true);
	// XMLUnit.setNormalize(true);

	// Diff diff = compareXML (control, test);

	assertXMLEqual(control, test);
}
 
Example 10
Source File: UtilsDiff.java    From apogen with Apache License 2.0 5 votes vote down vote up
/**
 * BETA version of APOGEN-DOM-differencing mechanism
 * 
 * @param doc1
 * @param doc2
 * @return list of Differences
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 */
@SuppressWarnings("unchecked")
public static List<Difference> customisedDomDiff(String string, String string2)
		throws ParserConfigurationException, SAXException, IOException {

	org.w3c.dom.Document doc1 = asDocument(string, true);
	org.w3c.dom.Document doc2 = asDocument(string2, true);

	XMLUnit.setControlParser("org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
	XMLUnit.setTestParser("org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
	XMLUnit.setSAXParserFactory("org.apache.xerces.jaxp.SAXParserFactoryImpl");

	XMLUnit.setNormalizeWhitespace(true);
	XMLUnit.setIgnoreAttributeOrder(true);
	XMLUnit.setIgnoreWhitespace(true);
	XMLUnit.setIgnoreComments(true);
	XMLUnit.setNormalize(true);
	XMLUnit.setIgnoreDiffBetweenTextAndCDATA(false);

	Diff d = new Diff(doc1, doc2);
	DetailedDiff dd = new DetailedDiff(d);

	dd.overrideDifferenceListener(new DomDifferenceListener());
	dd.overrideElementQualifier(null);

	return dd.getAllDifferences();
}
 
Example 11
Source File: ParallelTest.java    From exificient with MIT License 4 votes vote down vote up
private void testParallelEncode(ParallelExiFactory parallelExiFactory,
		int nbThreads, int nbTask, boolean testXml) throws Exception {
	EXIFactory exiFactory = getExiFactory();
	ArrayList<ExiSch> nc1NameExiMap = getExiSch(parallelExiFactory,
			testXml, exiFactory);
	Collection<Callable<EncodeResult>> tasks = new ArrayList<Callable<EncodeResult>>();
	for (int i = 0; i < nbTask; i++) {
		tasks.add(new TaskEncode(
				nc1NameExiMap.get(i % nc1NameExiMap.size())));
	}

	ExecutorService executor = Executors.newFixedThreadPool(nbThreads);
	List<Future<EncodeResult>> results = executor.invokeAll(tasks);
	int differentExiCount = 0;

	if (testXml) {
		XMLUnit.setIgnoreWhitespace(true);
		XMLUnit.setIgnoreAttributeOrder(true);
		XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true);
		XMLUnit.setIgnoreComments(true);
	}

	for (Future<EncodeResult> result : results) {
		EncodeResult exiResult = result.get();
		boolean equals = Arrays
				.equals(exiResult.exiOriginal, exiResult.exi);
		if (!equals) {
			differentExiCount++;
		}

		if (testXml) {
			Document document = decodeExiToDoc(exiResult.exi, exiFactory);
			Diff diff = compareXML(document, exiResult.roundTripDoc);
			if (equals) {
				Assert.assertTrue(diff.toString(), diff.similar());
			} else {
				Assert.assertFalse(diff.toString(), diff.similar());
			}
		}
	}
	executor.shutdown();
	assertEquals(0, differentExiCount);
}
 
Example 12
Source File: ReferenceResourceTest.java    From oodt with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that {@link ReferenceResource reference resources} are marshalled to
 * the expected XML format.
 * @throws IOException if the {@link Diff} constructor fails
 * @throws JAXBException if the {@link JAXBContext} or {@link Marshaller} fail
 * @throws MimeTypeException if {@link MimeTypes#forName(String)} fails
 * @throws SAXException if the {@link Diff} constructor fails
 */
@Test
public void testXmlMarshalling() throws IOException, JAXBException,
  MimeTypeException, SAXException
{
  String productId = "123";
  int refIndex = 0;

  // Create a new ReferenceResource using a Reference instance.
  Reference reference = new Reference("original", "dataStore", 1000,
    new MimeTypes().forName("text/plain"));

  ReferenceResource resource = new ReferenceResource(productId, refIndex,
    reference, new File("/tmp"));


  // Generate the expected output.
  String expectedXml =
      "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
    + "<reference>"
    + "<productId>" + productId + "</productId>"
    + "<refIndex>" + refIndex + "</refIndex>"
    + "<dataStoreReference>"
    +    reference.getDataStoreReference()
    + "</dataStoreReference>"
    + "<originalReference>"
    +    reference.getOrigReference()
    + "</originalReference>"
    + "<mimeType>" + reference.getMimeType().getName() + "</mimeType>"
    + "<fileSize>" + reference.getFileSize() +  "</fileSize>"
    + "</reference>";


  // Set up a JAXB context and marshall the ReferenceResource to XML.
  JAXBContext context = JAXBContext.newInstance(resource.getClass());
  Marshaller marshaller = context.createMarshaller();
  StringWriter writer = new StringWriter();
  marshaller.marshal(resource, writer);

  // Compare the expected and actual outputs.
  XMLUnit.setIgnoreWhitespace(true);
  XMLUnit.setIgnoreComments(true);
  XMLUnit.setIgnoreAttributeOrder(true);
  Diff diff = new Diff(expectedXml, writer.toString());
  assertTrue("The output XML was different to the expected XML: "
    + diff.toString(), diff.identical());
}
 
Example 13
Source File: XCalDocumentTest.java    From biweekly with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@BeforeClass
public static void beforeClass() {
	XMLUnit.setIgnoreAttributeOrder(true);
	XMLUnit.setIgnoreWhitespace(true);
}
 
Example 14
Source File: XCalWriterTest.java    From biweekly with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@BeforeClass
public static void beforeClass() {
	XMLUnit.setIgnoreAttributeOrder(true);
	XMLUnit.setIgnoreWhitespace(true);
}
 
Example 15
Source File: NormalizedNodeXmlTranslationTest.java    From yangtools with Eclipse Public License 1.0 4 votes vote down vote up
private void testTranslation(final XMLOutputFactory factory) throws Exception {
    final InputStream resourceAsStream = XmlToNormalizedNodesTest.class.getResourceAsStream(xmlPath);

    final XMLStreamReader reader = UntrustedXML.createXMLStreamReader(resourceAsStream);

    final NormalizedNodeResult result = new NormalizedNodeResult();
    final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);

    final XmlParserStream xmlParser = XmlParserStream.create(streamWriter, schema, containerNode);
    xmlParser.parse(reader);

    final NormalizedNode<?, ?> built = result.getResult();
    assertNotNull(built);

    if (expectedNode != null) {
        org.junit.Assert.assertEquals(expectedNode, built);
    }

    final Document document = UntrustedXML.newDocumentBuilder().newDocument();
    final DOMResult domResult = new DOMResult(document);

    final XMLStreamWriter xmlStreamWriter = factory.createXMLStreamWriter(domResult);

    final NormalizedNodeStreamWriter xmlNormalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter
            .create(xmlStreamWriter, schema);

    final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(
            xmlNormalizedNodeStreamWriter);

    normalizedNodeWriter.write(built);

    final Document doc = loadDocument(xmlPath);

    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setIgnoreComments(true);
    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setNormalize(true);

    final String expectedXml = toString(doc.getDocumentElement());
    final String serializedXml = toString(domResult.getNode());

    final Diff diff = new Diff(expectedXml, serializedXml);
    diff.overrideDifferenceListener(new IgnoreTextAndAttributeValuesDifferenceListener());
    diff.overrideElementQualifier(new ElementNameAndTextQualifier());

    // FIXME the comparison cannot be performed, since the qualifiers supplied by XMlUnit do not work correctly in
    // this case
    // We need to implement custom qualifier so that the element ordering does not mess the DIFF
    // dd.overrideElementQualifier(new MultiLevelElementNameAndTextQualifier(100, true));
    // assertTrue(dd.toString(), dd.similar());

    //new XMLTestCase() {}.assertXMLEqual(diff, true);
}
 
Example 16
Source File: YangModeledAnyXMLSerializationTest.java    From yangtools with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testSerializationOfBaz() throws Exception {
    final InputStream resourceAsStream = XmlToNormalizedNodesTest.class.getResourceAsStream(
            "/anyxml-support/serialization/baz.xml");
    final Module bazModule = SCHEMA_CONTEXT.findModules("baz").iterator().next();
    final ContainerSchemaNode bazCont = (ContainerSchemaNode) bazModule.findDataChildByName(
            QName.create(bazModule.getQNameModule(), "baz")).get();

    final XMLStreamReader reader = UntrustedXML.createXMLStreamReader(resourceAsStream);

    final NormalizedNodeResult result = new NormalizedNodeResult();

    final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);

    final XmlParserStream xmlParser = XmlParserStream.create(streamWriter, SCHEMA_CONTEXT, bazCont);
    xmlParser.parse(reader);

    final NormalizedNode<?, ?> transformedInput = result.getResult();
    assertNotNull(transformedInput);

    assertTrue(transformedInput instanceof ContainerNode);
    ContainerNode bazContainer = (ContainerNode) transformedInput;
    assertEquals(bazContainer.getNodeType(), bazQName);

    Optional<DataContainerChild<? extends PathArgument, ?>> bazContainerChild = bazContainer.getChild(
            new NodeIdentifier(myAnyXMLDataBaz));
    assertTrue(bazContainerChild.orElse(null) instanceof YangModeledAnyXmlNode);
    YangModeledAnyXmlNode yangModeledAnyXmlNode = (YangModeledAnyXmlNode) bazContainerChild.get();

    DataSchemaNode schemaOfAnyXmlData = yangModeledAnyXmlNode.getSchemaOfAnyXmlData();
    SchemaNode myContainer2SchemaNode = SchemaContextUtil.findDataSchemaNode(SCHEMA_CONTEXT,
            SchemaPath.create(true, bazQName, myContainer2QName));
    assertTrue(myContainer2SchemaNode instanceof ContainerSchemaNode);
    assertEquals(myContainer2SchemaNode, schemaOfAnyXmlData);

    final Document document = UntrustedXML.newDocumentBuilder().newDocument();
    final DOMResult domResult = new DOMResult(document);

    final XMLStreamWriter xmlStreamWriter = factory.createXMLStreamWriter(domResult);

    final NormalizedNodeStreamWriter xmlNormalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter
            .create(xmlStreamWriter, SCHEMA_CONTEXT);

    final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(
            xmlNormalizedNodeStreamWriter);

    normalizedNodeWriter.write(transformedInput);

    final Document doc = loadDocument("/anyxml-support/serialization/baz.xml");

    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setIgnoreComments(true);
    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setNormalize(true);

    String expectedXml = toString(doc.getDocumentElement());
    String serializedXml = toString(domResult.getNode());

    assertXMLEqual(expectedXml, serializedXml);
}
 
Example 17
Source File: MetadataResourceTest.java    From oodt with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that {@link MetadataResource metadata resources} are marshalled to
 * the expected XML format.
 * @throws IOException if the {@link Diff} constructor fails
 * @throws JAXBException if the {@link JAXBContext} or {@link Marshaller} fail
 * @throws SAXException if the {@link Diff} constructor fails
 */
@Test
public void testXmlMarshalling() throws IOException, JAXBException,
  SAXException
{
  // Generate the expected output.
  String expectedXml =
    "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
    + "<metadata>"
    + "<keyval><key>1</key><val>one</val></keyval>"
    + "<keyval><key>2</key><val>two</val></keyval>"
    + "<keyval><key>3</key><val>three</val></keyval>"
    + "<keyval><key>4</key><val>a</val><val>b</val><val>c</val></keyval>"
    + "</metadata>";

  // Create a MetadataResource using a Metadata instance.
  Hashtable metadataEntries = new Hashtable<String, Object>();
  metadataEntries.put("1", "one");
  metadataEntries.put("2", "two");
  metadataEntries.put("3", "three");
  List<String> list = new ArrayList<String>();
  list.add("a");
  list.add("b");
  list.add("c");
  metadataEntries.put("4", list);

  Metadata metadata = new Metadata();
  metadata.addMetadata(metadataEntries);
  MetadataResource resource = new MetadataResource(metadata);


  // Set up a JAXB context and marshall the ReferenceResource to XML.
  JAXBContext context = JAXBContext.newInstance(resource.getClass());
  Marshaller marshaller = context.createMarshaller();
  StringWriter writer = new StringWriter();
  marshaller.marshal(resource, writer);

  // Compare the expected and actual outputs.
  XMLUnit.setIgnoreWhitespace(true);
  XMLUnit.setIgnoreComments(true);
  XMLUnit.setIgnoreAttributeOrder(true);
  Diff diff = new Diff(expectedXml, writer.toString());
  diff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
  assertTrue("The output XML was different to the expected XML: "
    + diff.toString(), diff.similar());
}
 
Example 18
Source File: TestBug18026.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
@Test
public void testBug18026() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
  String filename = "xml-original.xml";
  String uri = "/write-buffer/";
  byte[] before = null;
  byte[] after = null;
  String strBefore = null;
  String strAfter = null;

  System.out.println("Running testBug18026");

  XMLUnit.setIgnoreAttributeOrder(true);
  XMLUnit.setIgnoreWhitespace(true);
  XMLUnit.setNormalize(true);
  XMLUnit.setNormalizeWhitespace(true);
  XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true);

  Map<String, String> namespaces = new HashMap<>();
  namespaces.put("rapi", "http://marklogic.com/rest-api");
  namespaces.put("prop", "http://marklogic.com/xdmp/property");
  namespaces.put("xs", "http://www.w3.org/2001/XMLSchema");
  namespaces.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");

  SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext(namespaces);

  xpather = XMLUnit.newXpathEngine();
  xpather.setNamespaceContext(namespaceContext);

  // connect the client
  DatabaseClient client = getDatabaseClient("rest-writer", "x", getConnType());

  Document readDoc = expectedXMLDocument(filename);

  DOMHandle dHandle = new DOMHandle();
  dHandle.set(readDoc);
  before = dHandle.toBuffer();
  strBefore = new String(before);
  System.out.println("Before: " + strBefore);

  // write doc
  XMLDocumentManager docMgr = client.newXMLDocumentManager();
  String docId = uri + filename;
  docMgr.write(docId, dHandle);

  // read doc
  docMgr.read(docId, dHandle);
  dHandle.get();

  after = dHandle.toBuffer();
  strAfter = new String(after);
  System.out.println("After: " + strAfter);

  assertXMLEqual("Buffer is not the same", strBefore, strAfter);

  // release client
  client.release();
}
 
Example 19
Source File: TestBug18026.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
@Test
public void testBug18026WithJson() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException
{
  String filename = "json-original.json";
  String uri = "/write-buffer/";
  byte[] before = null;
  byte[] after = null;
  String strBefore = null;
  String strAfter = null;

  System.out.println("Running testBug18026WithJson");

  XMLUnit.setIgnoreAttributeOrder(true);
  XMLUnit.setIgnoreWhitespace(true);
  XMLUnit.setNormalize(true);
  XMLUnit.setNormalizeWhitespace(true);
  XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true);

  Map<String, String> namespaces = new HashMap<>();
  namespaces.put("rapi", "http://marklogic.com/rest-api");
  namespaces.put("prop", "http://marklogic.com/xdmp/property");
  namespaces.put("xs", "http://www.w3.org/2001/XMLSchema");
  namespaces.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");

  SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext(namespaces);

  xpather = XMLUnit.newXpathEngine();
  xpather.setNamespaceContext(namespaceContext);

  ObjectMapper mapper = new ObjectMapper();

  // connect the client
  DatabaseClient client = getDatabaseClient("rest-writer", "x", getConnType());

  InputStream inputStream = new FileInputStream("src/test/java/com/marklogic/client/functionaltest/data/" + filename);

  InputStreamHandle isHandle = new InputStreamHandle();
  isHandle.set(inputStream);
  before = isHandle.toBuffer();
  strBefore = new String(before);
  System.out.println("Before: " + strBefore);

  JsonNode contentBefore = mapper.readValue(strBefore, JsonNode.class);

  // write doc
  JSONDocumentManager docMgr = client.newJSONDocumentManager();
  String docId = uri + filename;
  docMgr.write(docId, isHandle);

  // read doc
  docMgr.read(docId, isHandle);
  isHandle.get();

  after = isHandle.toBuffer();
  strAfter = new String(after);
  System.out.println("After: " + strAfter);

  JsonNode contentAfter = mapper.readValue(strAfter, JsonNode.class);

  assertTrue("Buffered JSON document difference", contentBefore.equals(contentAfter));

  // release client
  client.release();
}
 
Example 20
Source File: EjbJarXmlTest.java    From tomee with Apache License 2.0 4 votes vote down vote up
/**
 * TODO Doesn't seem there are any asserts here
 *
 * @throws Exception
 */
public void testEjbJar() throws Exception {
    final String fileName = "ejb-jar-example1.xml";

    final Event test = Event.start("Test");

    final URL resource = this.getClass().getClassLoader().getResource(fileName);

    final String expected = IO.slurp(resource);

    final Event ejbJarJAXBCreate = Event.start("EjbJarJAXBCreate");
    ejbJarJAXBCreate.stop();

    final Event unmarshalEvent = Event.start("unmarshal");
    final Object value;

    final EjbJar$JAXB jaxbType = new EjbJar$JAXB();
    value = Sxc.unmarshalJavaee(resource, jaxbType);

    unmarshalEvent.stop();

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    final Event marshall = Event.start("marshall");
    Sxc.marshall(jaxbType, value, baos);
    marshall.stop();

    final String result = new String(baos.toByteArray(), "UTF-8");

    XMLUnit.setIgnoreComments(Boolean.TRUE);
    XMLUnit.setIgnoreWhitespace(Boolean.TRUE);
    XMLUnit.setIgnoreAttributeOrder(Boolean.TRUE);
    XMLUnit.setIgnoreDiffBetweenTextAndCDATA(Boolean.TRUE);

    final Diff diff = new Diff(expected.trim(), result.trim());
    final Diff myDiff = new DetailedDiff(diff);

    final AtomicInteger differenceNumber = new AtomicInteger(0); // just to get an int wrapper for the test
    myDiff.overrideDifferenceListener(new IgnoreTextAndAttributeValuesDifferenceListener() {
        @Override
        public int differenceFound(final Difference difference) {
            if (!difference.isRecoverable()) {
                differenceNumber.incrementAndGet();
                System.err.println(">>> " + difference.toString());
            }
            return 0;
        }
    });

    assertTrue("Files are not identical", myDiff.identical());
    test.stop();
}