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

The following examples show how to use org.custommonkey.xmlunit.XMLUnit#setIgnoreComments() . 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: WsdlTest.java    From iaf with Apache License 2.0 6 votes vote down vote up
protected void test(Wsdl wsdl, String testWsdl) throws IOException, SAXException, ParserConfigurationException, XMLStreamException, URISyntaxException, NamingException, ConfigurationException {
    wsdl.setDocumentation("test");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    wsdl.wsdl(out, "Test");
    DocumentBuilder dbuilder = createDocumentBuilder();
    Document result = dbuilder.parse(new ByteArrayInputStream(out.toByteArray()));

    Document expected = dbuilder.parse(getClass().getClassLoader().getResourceAsStream(testWsdl));
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setIgnoreComments(true);

    assertXMLEqual("expected xml (" + testWsdl + ") not similar to result xml:\n" + new String(out.toByteArray()), expected, result);

    zip(wsdl);

}
 
Example 3
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 4
Source File: TestCreoleAnnotationHandler.java    From gate-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
  // Initialise the GATE library and creole register
  Gate.init();

  XMLUnit.setIgnoreComments(true);
  XMLUnit.setIgnoreWhitespace(true);
  XMLUnit.setIgnoreAttributeOrder(true);
}
 
Example 5
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 6
Source File: XmlUnitService.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Initializes {@link XMLUnit} properties
 */
private void initXMLUnitProperties() {
    XMLUnit.setIgnoreComments(true);
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true);
    XMLUnit.setCompareUnmatched(false);
}
 
Example 7
Source File: ODataXmlSerializerTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setup() {
  XMLUnit.setIgnoreComments(true);
  XMLUnit.setIgnoreAttributeOrder(true);
  XMLUnit.setIgnoreWhitespace(true);
  XMLUnit.setNormalizeWhitespace(true);
  XMLUnit.setCompareUnmatched(false);
}
 
Example 8
Source File: ODataXmlDeserializerTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setup() {
  XMLUnit.setIgnoreComments(true);
  XMLUnit.setIgnoreAttributeOrder(true);
  XMLUnit.setIgnoreWhitespace(true);
  XMLUnit.setNormalizeWhitespace(true);
  XMLUnit.setCompareUnmatched(false);
}
 
Example 9
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 10
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 11
Source File: XmlExpectationsHelper.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Parse the expected and actual content strings as XML and assert that the
 * two are "similar" -- i.e. they contain the same elements and attributes
 * regardless of order.
 * <p>Use of this method assumes the
 * <a href="http://xmlunit.sourceforge.net/">XMLUnit<a/> library is available.
 * @param expected the expected XML content
 * @param actual the actual XML content
 * @see org.springframework.test.web.servlet.result.MockMvcResultMatchers#xpath(String, Object...)
 * @see org.springframework.test.web.servlet.result.MockMvcResultMatchers#xpath(String, Map, Object...)
 */
public void assertXmlEqual(String expected, String actual) throws Exception {
	XMLUnit.setIgnoreWhitespace(true);
	XMLUnit.setIgnoreComments(true);
	XMLUnit.setIgnoreAttributeOrder(true);

	Document control = XMLUnit.buildControlDocument(expected);
	Document test = XMLUnit.buildTestDocument(actual);
	Diff diff = new Diff(control, test);
	if (!diff.similar()) {
		AssertionErrors.fail("Body content " + diff.toString());
	}
}
 
Example 12
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 13
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 14
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 15
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 16
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 17
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 18
Source File: ProductResourceTest.java    From oodt with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that {@link ProductResource product 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
{
  // Create a ProductResource using ProductType, Reference, Metadata and
  // Product instances.
  Hashtable metadataEntries = new Hashtable<String, Object>();
  metadataEntries.put("CAS.Test", "test value");
  Metadata metadata = new Metadata();
  metadata.addMetadata(metadataEntries);

  Reference reference = new Reference("original", "dataStore", 1000,
    new MimeTypes().forName("text/plain"));
  List<Reference> references = new ArrayList<Reference>();
  references.add(reference);

  ProductType productType = new ProductType("1", "GenericFile", "test type",
    "repository", "versioner");

  Product product = new Product();
  product.setProductId("123");
  product.setProductName("test.txt");
  product.setProductStructure(Product.STRUCTURE_FLAT);
  product.setProductType(productType);

  ProductResource resource = new ProductResource(product, metadata,
    references, new File("/tmp"));


  // Generate the expected output.
  String expectedXml =
      "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
      + "<product>"
      + "<id>" + product.getProductId() + "</id>"
      + "<name>" + product.getProductName() + "</name>"
      + "<structure>" + product.getProductStructure() + "</structure>"
      + "<type>" + productType.getName() + "</type>"
      + "<metadata>"
      + "<keyval>"
      + "<key>" + metadata.getAllKeys().get(0) + "</key>"
      + "<val>" + metadata.getAllValues().get(0) + "</val>"
      + "</keyval>"
      + "</metadata>"
      + "<references>"
      + "<reference>"
      + "<productId>" + product.getProductId() + "</productId>"
      + "<refIndex>0</refIndex>"
      + "<dataStoreReference>"
      +    reference.getDataStoreReference()
      + "</dataStoreReference>"
      + "<originalReference>"
      +    reference.getOrigReference()
      + "</originalReference>"
      + "<mimeType>" + reference.getMimeType().getName() + "</mimeType>"
      + "<fileSize>" + reference.getFileSize() + "</fileSize>"
      + "</reference>"
      + "</references>"
      + "</product>";


  // Set up a JAXB context and marshall the ProductResource 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 19
Source File: TransferResourceTest.java    From oodt with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that {@link TransferResource transfer 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
{
  // Create a TransferResource using ProductType, Product, Metadata, Reference
  // and FileTransferStatus instances.
  Hashtable metadataEntries = new Hashtable<String, Object>();
  metadataEntries.put("CAS.ProductReceivedTime", "2013-09-12T16:25:50.662Z");
  Metadata metadata = new Metadata();
  metadata.addMetadata(metadataEntries);

  Reference reference = new Reference("original", "dataStore", 1000,
    new MimeTypes().forName("text/plain"));

  ProductType productType = new ProductType("1", "GenericFile", "test type",
    "repository", "versioner");

  Product product = new Product();
  product.setProductId("123");
  product.setProductName("test product");
  product.setProductStructure(Product.STRUCTURE_FLAT);
  product.setProductType(productType);

  FileTransferStatus status = new FileTransferStatus(reference, 1000, 100,
    product);

  TransferResource resource = new TransferResource(product, metadata, status);


  // Generate the expected output.
  String expectedXml =
    "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
    + "<transfer>"
    + "<productName>" + product.getProductName() + "</productName>"
    + "<productId>" + product.getProductId() + "</productId>"
    + "<productTypeName>" + productType.getName() + "</productTypeName>"
    + "<dataStoreReference>"
    +   reference.getDataStoreReference()
    + "</dataStoreReference>"
    + "<origReference>"
    +   reference.getOrigReference()
    + "</origReference>"
    + "<mimeType>" + reference.getMimeType().getName() + "</mimeType>"
    + "<fileSize>" + reference.getFileSize() + "</fileSize>"
    + "<totalBytes>" + reference.getFileSize() + "</totalBytes>"
    + "<bytesTransferred>"
    +    status.getBytesTransferred()
    + "</bytesTransferred>"
    + "<percentComplete>"
    +    status.computePctTransferred() * 100
    + "</percentComplete>"
    + "<productReceivedTime>"
    +    metadata.getAllValues().get(0)
    + "</productReceivedTime>"
    + "</transfer>";

  // Set up a JAXB context and marshall the DatasetResource 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 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();
}