Java Code Examples for org.custommonkey.xmlunit.XMLAssert#assertXMLEqual()

The following examples show how to use org.custommonkey.xmlunit.XMLAssert#assertXMLEqual() . 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: AnalysisEngineFactoryTest.java    From uima-uimafit with Apache License 2.0 6 votes vote down vote up
@Test
  public void serializeComponent() throws Exception {
    File reference = new File("src/test/resources/data/reference/SerializationTestAnnotator.xml");
    
    File target = new File("target/test-output/AnalysisEngineFactoryTest/SerializationTestAnnotator.xml");
    target.getParentFile().mkdirs();
    
    AnalysisEngineDescription desc = createEngineDescription(SerializationTestAnnotator.class);
    try (OutputStream os = new FileOutputStream(target)) {
      desc.toXML(os);
    }
    
    String actual = FileUtils.readFileToString(target, "UTF-8");
    String expected = FileUtils.readFileToString(reference, "UTF-8");
    XMLUnit.setIgnoreWhitespace(true);
    XMLAssert.assertXMLEqual(expected, actual);
//    assertEquals(expected, actual);
  }
 
Example 2
Source File: DocumentContentTest.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Tests modification of the DocumentContentVO object directly.
 */
@Test public void testManualDocumentContentModification() throws Exception {
	WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("ewestfal"), "TestDocumentType");
	document.saveDocumentData();
	
	// fetch it from WorkflowInfo
	DocumentContent content = KewApiServiceLocator.getWorkflowDocumentService().getDocumentContent(document.getDocumentId());
	assertTrue("Should contain default content, was " + content.getFullContent(), KewApiConstants.DEFAULT_DOCUMENT_CONTENT.equals(content.getFullContent()) ||
			KewApiConstants.DEFAULT_DOCUMENT_CONTENT2.equals(content.getFullContent()));
	
	String appContent = "<abcdefg>hijklm n o p</abcdefg>";
	DocumentContentUpdate.Builder contentUpdate = DocumentContentUpdate.Builder.create(content);
	contentUpdate.setApplicationContent(appContent);
	document.updateDocumentContent(contentUpdate.build());
    document.saveDocumentData();
	
	// test that the content on the document is the same as the content we just set
	XMLAssert.assertXMLEqual(appContent, document.getApplicationContent());
	
	// fetch the document fresh and make sure the content is correct
	document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("ewestfal"), document.getDocumentId());
	XMLAssert.assertXMLEqual(appContent, document.getApplicationContent());
	
}
 
Example 3
Source File: PrettyPrinterTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that pretty printing works properly under normal circumstances.
 */
@Test
public void testPrettyPrint() throws SAXException, IOException, ParserConfigurationException {
  when(adsApiConfiguration.getSensitiveXPaths()).thenReturn(new String[] {TEST_SENSITIVE_XPATH});

  String prettyPrintedXml = createPrettyPrinter().prettyPrint(TEST_XML);
  String expectedXml = TEST_XML.replace("moe", "REDACTED");
  
  Document expectedDocument =
      XMLUnit.getControlDocumentBuilderFactory()
          .newDocumentBuilder()
          .parse(new InputSource(new StringReader(expectedXml)));
  Document actualDocument =
      XMLUnit.getTestDocumentBuilderFactory()
          .newDocumentBuilder()
          .parse(new InputSource(new StringReader(prettyPrintedXml)));
  XMLAssert.assertXMLEqual(
      XMLUnit.getWhitespaceStrippedDocument(expectedDocument),
      XMLUnit.getWhitespaceStrippedDocument(actualDocument));
}
 
Example 4
Source File: TransformersTest.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
@Test
    public void testMarcAsMods() throws Exception {
        XMLUnit.setNormalizeWhitespace(true);
        InputStream goldenIS = TransformersTest.class.getResourceAsStream("alephXServerDetailResponseAsMods.xml");
        assertNotNull(goldenIS);
        InputStream xmlIS = TransformersTest.class.getResourceAsStream("alephXServerDetailResponseAsMarcXml.xml");// from test
        assertNotNull(xmlIS);
        StreamSource streamSource = new StreamSource(xmlIS);
        Transformers mt = new Transformers();

        try {
            byte[] contents = mt.transformAsBytes(streamSource, Transformers.Format.MarcxmlAsMods3);
            assertNotNull(contents);
//            System.out.println(new String(contents, "UTF-8"));
            XMLAssert.assertXMLEqual(new InputSource(goldenIS), new InputSource(new ByteArrayInputStream(contents)));
        } finally {
            close(xmlIS);
            close(goldenIS);
        }
    }
 
Example 5
Source File: FullRoundtripTest.java    From dashencrypt with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testEncrypt2_plain() throws Exception {
    File outputDir = File.createTempFile("FullRoundtrip", "testEncrypt2");
    outputDir.delete();
    outputDir.mkdir();

    Main.main(new String[]{
            "encrypt2",
            "-o", outputDir.getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_1000000.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_1400000.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_800000.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_600000.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_128000_eng.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_128000_ita.mp4").getAbsolutePath(),
    });

    XMLUnit.setIgnoreWhitespace(true);
    XMLAssert.assertXMLEqual(new InputSource(getClass().getResourceAsStream("testEncrypt2_plain.mpd")), new InputSource(new FileInputStream(new File(outputDir, "Manifest.mpd"))));
    FileUtils.deleteDirectory(outputDir);
}
 
Example 6
Source File: FullRoundtripTest.java    From dashencrypt with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testEncrypt2_encrypted1() throws Exception {
    File outputDir = File.createTempFile("FullRoundtrip", "testEncrypt2");
    outputDir.delete();
    outputDir.mkdir();

    Main.main(new String[]{
            "encrypt2",
            "-o", outputDir.getAbsolutePath(),
            "--secretKey:v", "cbfed0736042e5962db8e23ddf1d0425",
            "--uuid:v", "22089b3b-527f-4612-a7bb-944559547306",
            new File(tos, "tears_of_steel/Tears_Of_Steel_1000000.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_1400000.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_800000.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_600000.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_128000_eng.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_128000_ita.mp4").getAbsolutePath(),
    });

    XMLUnit.setIgnoreWhitespace(true);
    System.out.println(FileUtils.readFileToString(new File(outputDir, "Manifest.mpd")));
    XMLAssert.assertXMLEqual(new InputSource(getClass().getResourceAsStream("testEncrypt2_encrypted1.mpd")), new InputSource(new FileInputStream(new File(outputDir, "Manifest.mpd"))));
    FileUtils.deleteDirectory(outputDir);
}
 
Example 7
Source File: FullRoundtripTest.java    From dashencrypt with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testEncrypt2_encrypted1_clearlead() throws Exception {
    File outputDir = File.createTempFile("FullRoundtrip", "testEncrypt2");
    outputDir.delete();
    outputDir.mkdir();

    Main.main(new String[]{
            "encrypt2",
            "-o", outputDir.getAbsolutePath(),
            "-clearlead", "30",
            "--secretKey:v", "cbfed0736042e5962db8e23ddf1d0425",
            "--uuid:v", "22089b3b-527f-4612-a7bb-944559547306",
            new File(tos, "tears_of_steel/Tears_Of_Steel_1000000.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_1400000.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_800000.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_600000.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_128000_eng.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_128000_ita.mp4").getAbsolutePath(),
    });

    XMLUnit.setIgnoreWhitespace(true);
    XMLAssert.assertXMLEqual(new InputSource(getClass().getResourceAsStream("testEncrypt2_encrypted1_clearlead.mpd")), new InputSource(new FileInputStream(new File(outputDir, "Manifest.mpd"))));
    FileUtils.deleteDirectory(outputDir);
}
 
Example 8
Source File: AbstractYinExportTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
private static void assertXMLEquals(final String fileName, final Document expectedXMLDoc, final String output)
        throws SAXException, IOException {
    final String expected = YinExportTestUtils.toString(expectedXMLDoc.getDocumentElement());

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

    final Diff diff = new Diff(expected, output);
    diff.overrideElementQualifier(new ElementNameAndAttributeQualifier());
    XMLAssert.assertXMLEqual(fileName, diff, true);
}
 
Example 9
Source File: PostProcessorTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Tests that modifying a document in the post processor works.  This test will do a few things:
 * 
 * 1) Change the document content in the post processor
 * 2) Send an app specific FYI request to the initiator of the document
 * 3) Modify the document title.
 * 
 * This test is meant to expose the bug KULWF-668 where it appears an OptimisticLockException is
 * being thrown after returning from the EPIC post processor.
 */
@Test public void testModifyDocumentInPostProcessor() throws Exception {
       XMLUnit.setIgnoreWhitespace(true);
	WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("ewestfal"), "testModifyDocumentInPostProcessor");
	document.saveDocument("");
       assertEquals("application content should be empty initially", "", document.getApplicationContent());
	assertTrue("Doc title should be empty initially", StringUtils.isBlank(document.getTitle()));

       document.adHocToPrincipal(ActionRequestType.APPROVE, "AdHoc", "", "2002", "", true);
	document.complete("");
       document = WorkflowDocumentFactory.loadDocument("2002", document.getDocumentId());

       // now approve the document, it should through a 2 nodes, then go PROCESSED then FINAL
       document.approve("");

       assertEquals("Should have transitioned nodes twice", 2, DocumentModifyingPostProcessor.levelChanges);
	assertTrue("SHould have called the processed status change", DocumentModifyingPostProcessor.processedChange);
	assertTrue("Document should be final.", document.isFinal());
	XMLAssert.assertXMLEqual("Application content should have been sucessfully modified.", APPLICATION_CONTENT, document.getApplicationContent());
			
	// check that the title was modified successfully
	assertEquals("Wrong doc title", DOC_TITLE, document.getTitle());
	
	// check that the document we routed from the post processor exists
	assertNotNull("SHould have routed a document from the post processor.", DocumentModifyingPostProcessor.routedDocumentId);
	document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("ewestfal"), DocumentModifyingPostProcessor.routedDocumentId);
	assertTrue("document should be enroute", document.isEnroute());
	assertEquals("Document should have 1 pending request.", 1, KEWServiceLocator.getActionRequestService().findPendingByDoc(document.getDocumentId()).size());
	assertTrue("ewestfal should have an approve request.", document.isApprovalRequested());
	document.approve("");
	assertTrue("Document should be final.", document.isFinal());
}
 
Example 10
Source File: NamespaceReplacerTest.java    From jlibs with Apache License 2.0 5 votes vote down vote up
@Test
public void withoutDefaultNamespace() throws Exception{
    String soap11Xml = getClass().getResource("/soap11.xml").toString();
    Map<String, String> namespaces = new HashMap<String, String>();
    namespaces.put(URI_SOAPENV, URI_SOAP12ENV);
    XMLReader reader = SAXUtil.newSAXParser(true, false, false).getXMLReader();
    NamespaceReplacer replacer = new NamespaceReplacer(reader, namespaces);
    Transformer transformer = TransformerUtil.newTransformer(null, true, 0, null);
    StringWriter writer = new StringWriter();
    transformer.transform(new SAXSource(replacer, new InputSource(soap11Xml)), new StreamResult(writer));
    String soap12Xml = getClass().getResource("/soap12.xml").toString();
    XMLAssert.assertXMLEqual(new InputSource(soap12Xml), new InputSource(new StringReader(writer.toString())));
}
 
Example 11
Source File: NamespaceReplacerTest.java    From jlibs with Apache License 2.0 5 votes vote down vote up
@Test
public void toDefaultNamespace() throws Exception{
    String soap11Xml = getClass().getResource("/soap11.xml").toString();
    Map<String, String> namespaces = new HashMap<String, String>();
    namespaces.put("http://www.example.org/stock", "");
    XMLReader reader = SAXUtil.newSAXParser(true, false, false).getXMLReader();
    NamespaceReplacer replacer = new NamespaceReplacer(reader, namespaces);
    Transformer transformer = TransformerUtil.newTransformer(null, true, 0, null);
    StringWriter writer = new StringWriter();
    transformer.transform(new SAXSource(replacer, new InputSource(soap11Xml)), new StreamResult(writer));
    String soap12Xml = getClass().getResource("/soap11-default.xml").toString();
    XMLAssert.assertXMLEqual(new InputSource(soap12Xml), new InputSource(new StringReader(writer.toString())));
}
 
Example 12
Source File: NamespaceReplacerTest.java    From jlibs with Apache License 2.0 5 votes vote down vote up
@Test
public void toDefaultNamespaceWithEmptyPrefix() throws Exception{
    String input = "<test xmlns='http://test'/>";
    Map<String, String> namespaces = Collections.singletonMap("http://test", "");
    XMLReader reader = SAXUtil.newSAXParser(true, false, false).getXMLReader();
    NamespaceReplacer replacer = new NamespaceReplacer(reader, namespaces);
    Transformer transformer = TransformerUtil.newTransformer(null, true, 0, null);
    StringWriter writer = new StringWriter();
    transformer.transform(new SAXSource(replacer, new InputSource(new StringReader(input))), new StreamResult(writer));
    XMLAssert.assertXMLEqual("<test/>", writer.toString());
}
 
Example 13
Source File: test_RecursiveElementNameAndTextQualifier.java    From xmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * @see <a href="https://sourceforge.net/forum/forum.php?thread_id=2948005&amp;forum_id=73273"/>
 */
public void testOpenDiscussionThread2948995_2() throws Exception {
    Diff myDiff = new Diff("<root>"
                           + "  <ent>"
                           + "    <value>"
                           + "      <int>1</int>"
                           + "    </value>"
                           + "    <value>"
                           + "      <int>2</int>"
                           + "    </value>"
                           + "  </ent>"
                           + "  <ent>"
                           + "    <value>"
                           + "      <int>3</int>"
                           + "    </value>"
                           + "    <value>"
                           + "      <int>4</int>"
                           + "    </value>"
                           + "  </ent>"
                           + "</root>",
                           "<root>"
                           + "  <ent>"
                           + "    <value>"
                           + "      <int>1</int>"
                           + "    </value>"
                           + "    <value>"
                           + "      <int>2</int>"
                           + "    </value>"
                           + "  </ent>"
                           + "  <ent>"
                           + "    <value>"
                           + "      <int>4</int>"
                           + "    </value>"
                           + "    <value>"
                           + "      <int>3</int>"
                           + "    </value>"
                           + "  </ent>"
                           + "</root>");
    myDiff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier()); 
    XMLAssert.assertXMLEqual("Not similar", myDiff, true); 
}
 
Example 14
Source File: AdWordsAxisSoapCompressionIntegrationTest.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Tests making an Axis AdWords API call with OAuth2 and compression enabled.
 */
@Test
public void testGoldenSoap_oauth2_compressionEnabled() throws Exception {
  testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION));

  GoogleCredential credential = new GoogleCredential.Builder().setTransport(
      new NetHttpTransport()).setJsonFactory(new JacksonFactory()).build();
  credential.setAccessToken("TEST_ACCESS_TOKEN");

  AdWordsSession session = new AdWordsSession.Builder().withUserAgent("TEST_APP")
      .withOAuth2Credential(credential)
      .withEndpoint(testHttpServer.getServerUrl())
      .withDeveloperToken("TEST_DEVELOPER_TOKEN")
      .withClientCustomerId("TEST_CLIENT_CUSTOMER_ID")
      .build();

  BudgetServiceInterface companyService =
      new AdWordsServices().get(session, BudgetServiceInterface.class);
  
  Budget budget = new Budget();
  budget.setName("Test Budget Name");
  Money money = new Money();
  money.setMicroAmount(50000000L);
  budget.setAmount(money);
  budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);

  BudgetOperation operation = new BudgetOperation();
  operation.setOperand(budget);
  operation.setOperator(Operator.ADD);
  
  Budget responseBudget = companyService.mutate(new BudgetOperation[] {operation}).getValue(0);

  assertEquals("Budget ID does not match", 251877074L, responseBudget.getBudgetId().longValue());
  assertEquals("Budget name does not match", budget.getName(), responseBudget.getName());
  assertEquals("Budget amount does not match", budget.getAmount().getMicroAmount(),
      responseBudget.getAmount().getMicroAmount());
  assertEquals("Budget delivery method does not match", budget.getDeliveryMethod(),
      responseBudget.getDeliveryMethod());
  
  assertTrue("Compression was enabled but the last request body was not compressed",
      testHttpServer.wasLastRequestBodyCompressed());
  XMLAssert.assertXMLEqual(SoapRequestXmlProvider.getOAuth2SoapRequest(API_VERSION),
      testHttpServer.getLastRequestBody());
  assertEquals("Bearer TEST_ACCESS_TOKEN", testHttpServer.getLastAuthorizationHttpHeader());
}
 
Example 15
Source File: ODataXmlSerializerTest.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private void checkXMLEqual(final String expected, final String resultString) throws SAXException, IOException {
  Diff diff = XMLUnit.compareXML(expected, resultString);
  diff.overrideDifferenceListener(DIFFERENCE_LISTENER);
  XMLAssert.assertXMLEqual(diff, true);
}
 
Example 16
Source File: XsdGeneratorHelperTest.java    From jaxb2-maven-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void validateProcessingXSDsWithEnumerations() throws Exception
{

    // Assemble
    final BufferingLog log = new BufferingLog();
    final JavaDocExtractor extractor = new JavaDocExtractor( log );
    extractor.setEncoding( "UTF-8" );

    final String parentPath = "testdata/schemageneration/javadoc/enums/";
    final URL parentPathURL = getClass().getClassLoader().getResource( parentPath );
    Assert.assertNotNull( parentPathURL );

    final File parentDir = new File( parentPathURL.getPath() );
    Assert.assertTrue( parentDir.exists() && parentDir.isDirectory() );

    final List<Filter<File>> excludeFilesMatching = new ArrayList<Filter<File>>();
    excludeFilesMatching.add( new PatternFileFilter( Collections.singletonList( "\\.xsd" ) ) );
    Filters.initialize( log, excludeFilesMatching );

    final List<File> allSourceFiles = FileSystemUtilities.filterFiles( parentDir, null, parentDir.getAbsolutePath(),
            log, "allJavaFiles", excludeFilesMatching );
    Assert.assertEquals( 3, allSourceFiles.size() );

    final List<URL> urls = new ArrayList<URL>();
    for ( File current : allSourceFiles )
    {
        try
        {
            urls.add( current.toURI().toURL() );
        }
        catch ( MalformedURLException e )
        {
            throw new IllegalArgumentException(
                    "Could not convert file [" + current.getAbsolutePath() + "] to a URL", e );
        }
    }
    Assert.assertEquals( 3, urls.size() );

    extractor.addSourceURLs( urls );
    final SearchableDocumentation docs = extractor.process();

    // #1) The raw / un-processed XSD (containing the 'before' state)
    // #2) The processed XSD (containing the 'expected' state)
    final String rawEnumSchema = PropertyResources.readFully( parentPath + "rawEnumSchema.xsd" );
    final String processedEnumSchema = PropertyResources.readFully( parentPath + "processedEnumSchema.xsd" );
    final NodeProcessor enumProcessor = new XsdEnumerationAnnotationProcessor( docs,
            new NoAuthorJavaDocRenderer() );

    // Act
    final Document processedDocument = XsdGeneratorHelper.parseXmlStream( new StringReader( rawEnumSchema ) );
    XsdGeneratorHelper.process( processedDocument.getFirstChild(), true, enumProcessor );
    // System.out.println("Got: " + AbstractSourceCodeAwareNodeProcessingTest.printDocument(processedDocument));

    // Assert
    final Document expectedDocument = XsdGeneratorHelper.parseXmlStream( new StringReader( processedEnumSchema ) );
    final Diff diff = new Diff( expectedDocument, processedDocument, null, new ElementNameAndAttributeQualifier() );
    diff.overrideElementQualifier( new ElementNameAndAttributeQualifier() );

    XMLAssert.assertXMLEqual( processedDocument, expectedDocument );
}
 
Example 17
Source File: DtrMapTestCase.java    From exificient with MIT License 4 votes vote down vote up
private byte[] testEString(String xmlAsString) throws EXIException,
		IOException, SAXException, TransformerException {
	/* DTR Map */
	QName type = new QName("", "es");
	QName representation = new QName(Constants.W3C_EXI_NS_URI, "estring");
	QName[] dtrMapTypes = { type };
	QName[] dtrMapRepresentations = { representation };

	// factory
	EXIFactory ef = DefaultEXIFactory.newInstance();
	ef.setFidelityOptions(FidelityOptions.createStrict());
	ef.setGrammars(GrammarFactory.newInstance().createGrammars(
			new ByteArrayInputStream(xsdAsStringEString.getBytes())));
	ef.setDatatypeRepresentationMap(dtrMapTypes, dtrMapRepresentations);

	// encode
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	EXIResult exiResult = new EXIResult(ef);
	exiResult.setOutputStream(baos);
	XMLReader xmlReader = XMLReaderFactory.createXMLReader();
	xmlReader.setContentHandler(exiResult.getHandler());
	xmlReader.parse(new InputSource(new ByteArrayInputStream(xmlAsString
			.getBytes()))); // parse XML input

	// decode
	ByteArrayOutputStream baosXML = new ByteArrayOutputStream();
	Result result = new StreamResult(baosXML);
	InputSource is = new InputSource(new ByteArrayInputStream(
			baos.toByteArray()));
	SAXSource exiSource = new EXISource(ef);
	exiSource.setInputSource(is);
	TransformerFactory tf = TransformerFactory.newInstance();
	Transformer transformer = tf.newTransformer();
	transformer.transform(exiSource, result);

	// System.out.println(new String(baosXML.toByteArray()));

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

	XMLAssert.assertXMLEqual(new StringReader(xmlAsString),
			new StringReader(new String(baosXML.toByteArray())));

	return baos.toByteArray();
}
 
Example 18
Source File: AdManagerAxisSoapIntegrationTest.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/** Tests making a Axis Ad Manager API call with OfflineCredentials. */
@Test
public void testGoldenSoap_oauth2_offlineCredentials() throws Exception {
  testHttpServer.setMockResponseBodies(
      Lists.newArrayList(
          AuthResponseProvider.getTestOAuthResponse(
              "TEST_ACCESS_TOKEN_1", 1L, "newRefreshToken1"),
          AuthResponseProvider.getTestOAuthResponse(
              "TEST_ACCESS_TOKEN_2", 3600L, "newRefreshToken2"),
          SoapResponseXmlProvider.getTestSoapResponse(API_VERSION)));

  OfflineCredentials offlineCredentials =
      new OfflineCredentials.Builder()
          .forApi(OfflineCredentials.Api.AD_MANAGER)
          .withTokenUrlServer(testHttpServer.getServerUrl())
          .fromFile(
              AdManagerAxisSoapIntegrationTest.class.getResource("props/ads-test.properties"))
          .build();

  Credential credential = offlineCredentials.generateCredential();

  assertTrue(testHttpServer.getLastRequestBody().contains("grant_type=refresh_token"));
  assertTrue(testHttpServer.getLastRequestBody().contains("refresh_token=refreshToken"));
  assertTrue(testHttpServer.getLastRequestBody().contains("client_id=clientId"));
  assertTrue(testHttpServer.getLastRequestBody().contains("client_secret=clientSecret"));

  // Make sure the old token expires - the session builder should issue a request
  // for another access token.
  Thread.sleep(1000);

  assertEquals("TEST_ACCESS_TOKEN_1", credential.getAccessToken());

  AdManagerSession session =
      new AdManagerSession.Builder()
          .withApplicationName("TEST_APP")
          .withOAuth2Credential(credential)
          .withEndpoint(testHttpServer.getServerUrl())
          .withNetworkCode("TEST_NETWORK_CODE")
          .build();

  CompanyServiceInterface companyService =
      new AdManagerServices().get(session, CompanyServiceInterface.class);
  Company[] companies = companyService.createCompanies(new Company[] {new Company()});

  assertEquals(1234L, companies[0].getId().longValue());
  XMLAssert.assertXMLEqual(
      SoapRequestXmlProvider.getOAuth2SoapRequest(API_VERSION),
      testHttpServer.getLastRequestBody());
  assertFalse(
      "Did not request compression but request was compressed",
      testHttpServer.wasLastRequestBodyCompressed());
  assertEquals("newRefreshToken2", credential.getRefreshToken());
  assertEquals("Bearer TEST_ACCESS_TOKEN_2", testHttpServer.getLastAuthorizationHttpHeader());
}
 
Example 19
Source File: CasToInlineXmlTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public void testCasToInlineXml() throws Exception {
    // Jira https://issues.apache.org/jira/browse/UIMA-2406
    
    File typeSystemFile1 = JUnitExtension.getFile("ExampleCas/testTypeSystem_arrays.xml");
    File indexesFile = JUnitExtension.getFile("ExampleCas/testIndexes_arrays.xml");

    TypeSystemDescription typeSystem = UIMAFramework.getXMLParser().parseTypeSystemDescription(
            new XMLInputSource(typeSystemFile1));
    FsIndexDescription[] indexes = UIMAFramework.getXMLParser().parseFsIndexCollection(new XMLInputSource(indexesFile))
            .getFsIndexes();

    CAS srcCas = CasCreationUtils.createCas(typeSystem, new TypePriorities_impl(), indexes);
    
    JCas jcas = srcCas.getJCas();
    
    jcas.setDocumentText("1 2 3 4 5 6 7 8 9");
    OfShorts f = new OfShorts(jcas);
    ShortArray a = new ShortArray(jcas, 3);
    a.set(0, (short)0);
    a.set(1, (short)1);
    a.set(2, (short)2);
    f.setF1Shorts(a);
    f.addToIndexes();
    
    OfStrings ss = new OfStrings(jcas);
    StringArray sa = new StringArray(jcas, 3);
    sa.set(0, "0s");
    sa.set(1, "1s");
    sa.set(2, "2s");
    ss.setF1Strings(sa);
    ss.addToIndexes();
    
    CasToInlineXml c2x = new CasToInlineXml();
    String result = c2x.generateXML(srcCas).trim();
    System.out.println(result);
    int s = result.indexOf("<Document>");
    result = result.substring(s);
    result = canonicalizeNl(result);
    
    // Java 9 xml formatter formats the text with a new line and indentations
    String expected = "<Document>\n" +
        IND+"<uima.tcas.DocumentAnnotation sofa=\"Sofa\" begin=\"0\" end=\"17\" language=\"x-unspecified\">\n" +
        IND+IND+"<org.apache.uima.testTypeSystem_arrays.OfStrings sofa=\"Sofa\" begin=\"0\" end=\"0\" f1Strings=\"[0s,1s,2s]\"/>\n"  +
        IND+IND+"<org.apache.uima.testTypeSystem_arrays.OfShorts sofa=\"Sofa\" begin=\"0\" end=\"0\" f1Shorts=\"[0,1,2]\"/>"
        		+ (Misc.isJava9ea() ? "\n        " : "") + 
        		"1 2 3 4 5 6 7 8 9"
        		+ (Misc.isJava9ea() ? "\n    " : "") + "</uima.tcas.DocumentAnnotation>\n" +
        "</Document>";
    for (int i = 0; i < result.length(); i++ ) {
      if (result.charAt(i) != expected.charAt(i)) {
        System.out.format("Unequal compare at position %,d, char code result = %d, expected = %d%n", i, (int)result.charAt(i), (int)expected.charAt(i));
        break;
      }
    }
    boolean whitespaceFlag = XMLUnit.getIgnoreWhitespace();
    XMLUnit.setIgnoreWhitespace(true);
    try {
      XMLAssert.assertXMLEqual(expected, result);
    }
    finally {
      XMLUnit.setIgnoreWhitespace(whitespaceFlag);
    }
//    assertEquals(expected, result.trim());
  }
 
Example 20
Source File: SchemalessXMLStreamNormalizedNodeStreamWriterTest.java    From yangtools with Eclipse Public License 1.0 3 votes vote down vote up
@Test
public void testWrite() throws XMLStreamException, IOException, SAXException {
    final Document doc = loadDocument("/foobar.xml");

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

    final XMLStreamWriter xmlStreamWriter = factory.createXMLStreamWriter(domResult);

    final NormalizedNodeStreamWriter schemalessXmlNormalizedNodeStreamWriter =
            XMLStreamNormalizedNodeStreamWriter.createSchemaless(xmlStreamWriter);

    final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(
            schemalessXmlNormalizedNodeStreamWriter);

    normalizedNodeWriter.write(buildOuterContainerNode());

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

    final String expectedXml = toString(doc.getDocumentElement());
    final String serializedXml = toString(domResult.getNode());
    final Diff diff = new Diff(expectedXml, serializedXml);

    final DifferenceListener differenceListener = new IgnoreTextAndAttributeValuesDifferenceListener();
    diff.overrideDifferenceListener(differenceListener);

    XMLAssert.assertXMLEqual(diff, true);
}