Java Code Examples for javax.xml.parsers.DocumentBuilderFactory#setIgnoringElementContentWhitespace()

The following examples show how to use javax.xml.parsers.DocumentBuilderFactory#setIgnoringElementContentWhitespace() . 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: TrackWriterTest.java    From mytracks with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the given XML contents and returns a DOM {@link Document} for it.
 */
protected Document parseXmlDocument(String contents)
    throws FactoryConfigurationError, ParserConfigurationException,
        SAXException, IOException {
  DocumentBuilderFactory builderFactory =
      DocumentBuilderFactory.newInstance();
  builderFactory.setCoalescing(true);
  // TODO: Somehow do XML validation on Android
  // builderFactory.setValidating(true);
  builderFactory.setNamespaceAware(true);
  builderFactory.setIgnoringComments(true);
  builderFactory.setIgnoringElementContentWhitespace(true);
  DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
  Document doc = documentBuilder.parse(
      new InputSource(new StringReader(contents)));
  return doc;
}
 
Example 2
Source File: Bug6564400.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testDOM() throws ParserConfigurationException, SAXException, IOException {
    InputStream xmlFile = getClass().getResourceAsStream("Bug6564400.xml");

    // Set the options on the DocumentFactory to remove comments, remove
    // whitespace
    // and validate against the schema.
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setIgnoringComments(true);
    docFactory.setIgnoringElementContentWhitespace(true);
    docFactory.setSchema(schema);

    DocumentBuilder parser = docFactory.newDocumentBuilder();
    Document xmlDoc = parser.parse(xmlFile);

    boolean ok = dump(xmlDoc, true);
    Assert.assertEquals(true, ok);
}
 
Example 3
Source File: Bug6564400.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testConformantDOM() throws ParserConfigurationException, SAXException, IOException {
    InputStream xmlFile = getClass().getResourceAsStream("Bug6564400.xml");

    // Set the options on the DocumentFactory to remove comments, remove
    // whitespace
    // and validate against the schema.
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setIgnoringComments(true);
    docFactory.setIgnoringElementContentWhitespace(true);
    docFactory.setSchema(schema);
    docFactory.setFeature("http://java.sun.com/xml/schema/features/report-ignored-element-content-whitespace", true);

    DocumentBuilder parser = docFactory.newDocumentBuilder();
    Document xmlDoc = parser.parse(xmlFile);

    boolean ok = dump(xmlDoc, true);
    Assert.assertEquals(false, ok);
}
 
Example 4
Source File: JsonDataGeneratorTest.java    From json-data-generator with Apache License 2.0 6 votes vote down vote up
@Test
  public void testXmlTemplate() throws IOException, JsonDataGeneratorException, SAXException, ParserConfigurationException, XpathException {
      parser.generateTestDataJson(this.getClass().getClassLoader().getResource("xmlfunctionWithRepeat.xml"), outputStream);
      
      ByteArrayInputStream inputstream = new ByteArrayInputStream(outputStream.toByteArray());
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      dbf.setCoalescing(true);
      dbf.setIgnoringElementContentWhitespace(true);
      dbf.setIgnoringComments(true);
      DocumentBuilder db = dbf.newDocumentBuilder();

      Document doc = db.parse(inputstream);
      XpathEngine simpleXpathEngine = XMLUnit.newXpathEngine();
      String value = simpleXpathEngine.evaluate("//root/tags", doc);
assertEquals(value.split(",").length, 7);
assertTrue(simpleXpathEngine.evaluate("//root/element[1]/name", doc).length() > 1);
assertTrue(simpleXpathEngine.evaluate("//root/element[2]/name", doc).length() > 1);
assertTrue(simpleXpathEngine.evaluate("//root/friends/friend[1]/name", doc).length() > 1);
assertTrue(simpleXpathEngine.evaluate("//root/friends/friend[2]/name", doc).length() > 1);
assertTrue(simpleXpathEngine.evaluate("//root/friends/friend[3]/name", doc).length() > 1);
  }
 
Example 5
Source File: ClusteringCacheManagerServiceConfigurationParserTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
/**
 * Ensures the namespace declared by {@link ClusteringCacheManagerServiceConfigurationParser} and its
 * schema are the same.
 */
@Test
public void testSchema() throws Exception {
  final ClusteringCacheManagerServiceConfigurationParser parser = new ClusteringCacheManagerServiceConfigurationParser();
  final StreamSource schemaSource = (StreamSource) parser.getXmlSchema();

  final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  factory.setIgnoringComments(true);
  factory.setIgnoringElementContentWhitespace(true);

  final DocumentBuilder domBuilder = factory.newDocumentBuilder();
  final Element schema = domBuilder.parse(schemaSource.getInputStream()).getDocumentElement();
  final Attr targetNamespaceAttr = schema.getAttributeNode("targetNamespace");
  assertThat(targetNamespaceAttr, is(not(nullValue())));
  assertThat(targetNamespaceAttr.getValue(), is(parser.getNamespace().toString()));
}
 
Example 6
Source File: NiCadOutputParser.java    From JDeodorant with MIT License 6 votes vote down vote up
public NiCadOutputParser(IJavaProject iJavaProject, String cloneOutputFilePath) throws InvalidInputFileException {
	super(iJavaProject, cloneOutputFilePath);
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	factory.setIgnoringElementContentWhitespace(true);
	try {
		DocumentBuilder builder = factory.newDocumentBuilder();
		File file = new File(this.getToolOutputFilePath());
		this.document  = builder.parse(file);
		NodeList classInfoNodeList = document.getElementsByTagName("classinfo");
		try {
			this.setCloneGroupCount(Integer.parseInt(classInfoNodeList.item(0).getAttributes().getNamedItem("nclasses").getNodeValue()));
		} catch (Exception nfe) {
			this.document = null;
			throw new InvalidInputFileException();
		}
	} catch (IOException ioex) {
		ioex.printStackTrace();
	} catch (SAXException saxe) {
		saxe.printStackTrace();
	} catch (ParserConfigurationException e) {
		e.printStackTrace();
	}
}
 
Example 7
Source File: FilePreferencesXmlSupport.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Load an XML document from specified input stream, which must have the
 * requisite DTD URI.
 */
private static Document loadPrefsDoc(InputStream in) throws SAXException, IOException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setValidating(true);
    dbf.setCoalescing(true);
    dbf.setIgnoringComments(true);
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new Resolver());
        db.setErrorHandler(new EH());
        return db.parse(new InputSource(in));
    } catch (ParserConfigurationException e) {
        throw new AssertionError(e);
    }
}
 
Example 8
Source File: PredefinedTeXFormulaParser.java    From AndroidMathKeyboard with Apache License 2.0 5 votes vote down vote up
public PredefinedTeXFormulaParser(InputStream file, String type)
		throws ResourceParseException, IOException {
	try {
		this.type = type;
		DocumentBuilderFactory factory = DocumentBuilderFactory
				.newInstance();
		factory.setIgnoringElementContentWhitespace(true);
		factory.setIgnoringComments(true);
		root = factory.newDocumentBuilder().parse(file)
				.getDocumentElement();
	} catch (Exception e) { // JDOMException or IOException
		throw new XMLResourceParseException("", e);
	}
	file.close();
}
 
Example 9
Source File: GenericDaemonGeneratorTest.java    From appassembler with MIT License 5 votes vote down vote up
public void testGenerationWithAllInfoInDescriptor()
    throws Exception
{
    runTest( "generic", "src/test/resources/project-1/pom.xml", "src/test/resources/project-1/descriptor.xml",
             "target/output-1-generic" );

    File actualAppXml = new File( getTestFile( "target/output-1-generic" ), "app.xml" );

    assertTrue( "config file is missing: " + actualAppXml.getAbsolutePath(), actualAppXml.isFile() );

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

    builderFactory.setIgnoringComments( true );
    builderFactory.setIgnoringElementContentWhitespace( true );
    DocumentBuilder builder = builderFactory.newDocumentBuilder();

    Document actual = builder.parse( actualAppXml );

    assertNodeEquals( "com.westerngeco.example.App", "mainClass", actual );
    assertNodeEquals( "org/codehaus/mojo/appassembler/project-1/1.0-SNAPSHOT/project-1-1.0-SNAPSHOT.jar",
                      "relativePath", actual );
    assertNodeEquals( "345", "initialMemorySize", actual );
    assertNodeEquals( "234", "maxMemorySize", actual );
    assertNodeEquals( "321", "maxStackSize", actual );
    assertNodeEquals( "foo=bar", "systemProperty", actual );
    assertNodeEquals( "arg1=arg1-value", "commandLineArgument", actual );
    assertNodeNull( "commandLineArgument", actual );

}
 
Example 10
Source File: XmlHelper.java    From rice with Educational Community License v2.0 5 votes vote down vote up
public static org.w3c.dom.Document trimXml(InputStream input) throws SAXException, IOException, ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setIgnoringElementContentWhitespace(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    org.w3c.dom.Document oldDocument = builder.parse(input);
    org.w3c.dom.Element naviElement = oldDocument.getDocumentElement();
    trimElement(naviElement);
    return oldDocument;
}
 
Example 11
Source File: TeXSymbolParser.java    From FlexibleRichTextView with Apache License 2.0 5 votes vote down vote up
public TeXSymbolParser(InputStream file, String name)
		throws ResourceParseException {
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory
				.newInstance();
		factory.setIgnoringElementContentWhitespace(true);
		factory.setIgnoringComments(true);
		root = factory.newDocumentBuilder().parse(file)
				.getDocumentElement();
		// set possible valid symbol type mappings
		setTypeMappings();
	} catch (Exception e) { // JDOMException or IOException
		throw new XMLResourceParseException(name, e);
	}
}
 
Example 12
Source File: TeXFormulaSettingsParser.java    From FlexibleRichTextView with Apache License 2.0 5 votes vote down vote up
public TeXFormulaSettingsParser(InputStream file, String name)
		throws ResourceParseException, IOException {
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory
				.newInstance();
		factory.setIgnoringElementContentWhitespace(true);
		factory.setIgnoringComments(true);
		root = factory.newDocumentBuilder().parse(file)
				.getDocumentElement();
	} catch (Exception e) { // JDOMException or IOException
		throw new XMLResourceParseException(name, e);
	}
	file.close();
}
 
Example 13
Source File: Procedure.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Constructs a new Procedure from an InputSource.
 *
 * @param xml The InputSource to read.
 * @return A new Procedure instance.
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws Exception
 */
public static Procedure fromXML(InputSource xml) throws IOException,
        ParserConfigurationException, SAXException, ProcedureParseException {

    long processingTime = System.currentTimeMillis();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);
    dbf.setIgnoringComments(true);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(false);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document d = db.parse(xml);

    NodeList children = d.getChildNodes();
    Node procedureNode = null;
    for (int i = 0; i < children.getLength(); i++) {
        Node child = d.getChildNodes().item(i);
        if (child.getNodeName().equals("Procedure")) {
            procedureNode = child;
            break;
        }
    }
    if (procedureNode == null) {
        throw new ProcedureParseException("Can't get procedure");
    }
    Procedure result = fromXML(procedureNode);

    processingTime = System.currentTimeMillis() - processingTime;
    Log.i(TAG, "Parsing procedure XML took " + processingTime + " milliseconds.");

    return result;
}
 
Example 14
Source File: MessageGenerator.java    From flex-blazeds with Apache License 2.0 5 votes vote down vote up
public MessageGenerator() {
    super(new SerializationContext());
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setIgnoringComments(true);
    docBuilderFactory.setIgnoringElementContentWhitespace(true);
    try {
        docBuilder = docBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 15
Source File: GlueSettingsParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public GlueSettingsParser() throws ResourceParseException {
    try {
        setTypeMappings();
        setStyleMappings();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringElementContentWhitespace(true);
        factory.setIgnoringComments(true);
        root = factory.newDocumentBuilder().parse(GlueSettingsParser.class.getResourceAsStream(RESOURCE_NAME)).getDocumentElement();
        parseGlueTypes();
    } catch (Exception e) { // JDOMException or IOException
        throw new XMLResourceParseException(RESOURCE_NAME, e);
    }
}
 
Example 16
Source File: SignatureConfirmationTest.java    From steady with Apache License 2.0 4 votes vote down vote up
private void testSignatureConfirmationResponse(
    List<WSHandlerResult> sigSaved,
    List<WSHandlerResult> sigReceived
) throws Exception {
    Document doc = readDocument("wsse-request-clean.xml");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);
    
    SOAPMessage saajMsg = MessageFactory.newInstance().createMessage();
    SOAPPart part = saajMsg.getSOAPPart();
    part.setContent(new DOMSource(doc));
    saajMsg.saveChanges();

    msg.setContent(SOAPMessage.class, saajMsg);

    msg.put(WSHandlerConstants.ACTION, WSHandlerConstants.TIMESTAMP);
    msg.put(WSHandlerConstants.RECV_RESULTS, sigReceived);
    
    handler.handleMessage(msg);

    doc = part;
    
    assertValid("//wsse:Security", doc);
    // assertValid("//wsse:Security/wsse11:SignatureConfirmation", doc);

    byte[] docbytes = getMessageBytes(doc);
    // System.out.println(new String(docbytes));
    
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());
    doc = StaxUtils.read(db, reader, false);

    WSS4JInInterceptor inHandler = new WSS4JInInterceptor();

    SoapMessage inmsg = new SoapMessage(new MessageImpl());
    ex.setInMessage(inmsg);
    inmsg.setContent(SOAPMessage.class, saajMsg);

    inHandler.setProperty(WSHandlerConstants.ACTION, WSHandlerConstants.TIMESTAMP);
    inmsg.put(WSHandlerConstants.SEND_SIGV, sigSaved);

    inHandler.handleMessage(inmsg);
}
 
Example 17
Source File: WSS4JInOutTest.java    From steady with Apache License 2.0 4 votes vote down vote up
@Test
public void testCustomProcessor() throws Exception {
    Document doc = readDocument("wsse-request-clean.xml");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);
    
    SOAPMessage saajMsg = MessageFactory.newInstance().createMessage();
    SOAPPart part = saajMsg.getSOAPPart();
    part.setContent(new DOMSource(doc));
    saajMsg.saveChanges();

    msg.setContent(SOAPMessage.class, saajMsg);

    msg.put(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE);
    msg.put(WSHandlerConstants.SIG_PROP_FILE, "outsecurity.properties");
    msg.put(WSHandlerConstants.USER, "myalias");
    msg.put("password", "myAliasPassword");

    handler.handleMessage(msg);

    doc = part;
    
    assertValid("//wsse:Security", doc);
    assertValid("//wsse:Security/ds:Signature", doc);

    byte[] docbytes = getMessageBytes(doc);
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());
    doc = StaxUtils.read(db, reader, false);

    final Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(
        WSS4JInInterceptor.PROCESSOR_MAP,
        createCustomProcessorMap()
    );
    WSS4JInInterceptor inHandler = new WSS4JInInterceptor(properties);

    SoapMessage inmsg = new SoapMessage(new MessageImpl());
    ex.setInMessage(inmsg);
    inmsg.setContent(SOAPMessage.class, saajMsg);

    inHandler.setProperty(WSHandlerConstants.ACTION, WSHandlerConstants.NO_SECURITY);

    inHandler.handleMessage(inmsg);
    
    WSSecurityEngineResult result = 
        (WSSecurityEngineResult) inmsg.get(WSS4JInInterceptor.SIGNATURE_RESULT);
    assertNull(result);
}
 
Example 18
Source File: cfXmlData.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Parses and potentially validates a xml document using the specified
 * ValidatorSource. The InputSourceGenerator produces InputSource objects that wrap
 * the xml document. The ValiatorSource wraps the validation object (DTD/Schema).
 * Returns a parsed and potentially validated cfXmlData instance.
 * Note, because DTD validation occurs during parsing, and xml schema validation takes
 * place after parsing, we need to separate the validation types into two steps.
 * Also note, if a customHandler is specified, it may not throw any parse or
 * validation errors/warnings. Which could lead to a null Document being returned.
 * 
 * @param xs
 *          generator that creates new InputSource instances
 * @param validator
 *          wrapper for the validation object (DTD/Schema)
 * @param customHandler
 *          custom ErrorHandler, may be null
 * @return parsed and potentially validated xml object, or null
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
protected static Document parseXml(XmlSource xs, ValidatorSource validator, ErrorHandler customHandler) throws IOException, SAXException, ParserConfigurationException {
	InputSource is = null;
	boolean schemaValidationRequired = false;
	boolean dtdRemovalRequired = false;
	EntityResolver dtdResolver = null;
	DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
	fact.setNamespaceAware(true);
	fact.setIgnoringElementContentWhitespace(true);

	if (validator.isNull()) {
		// Return empty content for all entity references (presumably from a <!DOCTYPE ...>
		// element) so the parser will parse without any DTD validation and not complain when
		// resolving <!DOCTYPE ...> entity references (if it exists).
		is = new ValidationInputSource(xs, ValidationInputSource.NO_CHANGE);
		dtdResolver = new NoValidationResolver();
	} else if (validator.isSchema()) {
		// Return empty content for all entity references (presumably from a <!DOCTYPE ...>
		// element) so the parser will parse without any DTD validation and not complain when
		// resolving <!DOCTYPE ...> entity references (if it exists).
		is = new ValidationInputSource(xs, ValidationInputSource.NO_CHANGE);
		dtdResolver = new NoValidationResolver();
		// Note that we must do some post parse xml schema validation.
		schemaValidationRequired = true;
	} else if (validator.isEmptyString() && !xs.hasDTD()) {
		// Return empty content for all entity references (presumably from a <!DOCTYPE ...>
		// element) so the parser will parse without any DTD validation and not complain when
		// resolving <!DOCTYPE ...> entity references (if it exists).
		is = new ValidationInputSource(xs, ValidationInputSource.NO_CHANGE);
		dtdResolver = new NoValidationResolver();
		// Note that we must do some post parse xml schema validation. This assumes
		// that the xml doc has some embedded xml schema reference.
		schemaValidationRequired = true;
	} else if (validator.isEmptyString()) {
		// Best have DTD referenced in the xml source. Set DTD validation to true,
		// leave the existing <!DOCTYPE ...> element intact.
		fact.setValidating(true);
		if (customHandler == null)
			customHandler = new ValidationErrorHandler();
		is = new ValidationInputSource(xs, ValidationInputSource.NO_CHANGE);
	} else {
		// Must have specified a DTD validator object so set DTD validation
		// to true, read the <!DOCTYPE ...> element while parsing and return
		// the specified DTD validator during entity reference lookup, or if
		// no <!DOCTYPE ..> element exists, add our own so we can return the
		// specified DTD validator content during entity reference lookup.
		fact.setValidating(true);
		if (customHandler == null)
			customHandler = new ValidationErrorHandler();
		dtdRemovalRequired = !xs.hasDTD();
		ValidationResolver vr = new ValidationResolver(validator);
		dtdResolver = vr;
		is = new ValidationInputSource(xs, vr, ValidationInputSource.READ_ADD);
	}

	DocumentBuilder parser = fact.newDocumentBuilder();
	parser.setEntityResolver(dtdResolver); // if these are null, it doesn't matter,
	parser.setErrorHandler(customHandler); // setting these won't change default behavior
	Document doc = parser.parse(is);
	
	if (doc != null) {
		doc.normalize();
	
		// Now see if we need to do any schema validation
		if (schemaValidationRequired)
			validateXml(doc, validator, customHandler);
	}

	// Remove the inserted DTD (if necessary)
	if (doc != null && dtdRemovalRequired && doc.getDoctype() != null)
		doc.removeChild(doc.getDoctype());

	// Return the parsed (and possibly validated Document)
	return doc;
}
 
Example 19
Source File: MXFFragmentBuilderTest.java    From regxmllib with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();

    /* build the dictionaries */
    mds_catsup = buildDictionaryCollection(
        "registers/catsup/Elements.xml",
        "registers/catsup/Groups.xml",
        "registers/catsup/Types.xml"
    );

    assertNotNull(mds_catsup);

    /* build the dictionaries */
    mds_brown_sauce = buildDictionaryCollection(
        "registers/brown_sauce/Elements.xml",
        "registers/brown_sauce/Groups.xml",
        "registers/brown_sauce/Types.xml"
    );

    assertNotNull(mds_brown_sauce);

    /* build the dictionaries */
    mds_snapshot = buildDictionaryCollection(
        "registers/snapshot/Elements.xml",
        "registers/snapshot/Groups.xml",
        "registers/snapshot/Types.xml"
    );

    assertNotNull(mds_snapshot);

    mds_ponzu = buildDictionaryCollection(
        "registers/ponzu/Elements.xml",
        "registers/ponzu/Groups.xml",
        "registers/ponzu/Types.xml"
    );

    assertNotNull(mds_ponzu);


    /* setup the doc builder */
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setCoalescing(true);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setIgnoringComments(true);
    db = dbf.newDocumentBuilder();

    assertNotNull(db);
}
 
Example 20
Source File: SignatureConfirmationTest.java    From steady with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSignatureConfirmationRequest() throws Exception {
    Document doc = readDocument("wsse-request-clean.xml");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);
    
    SOAPMessage saajMsg = MessageFactory.newInstance().createMessage();
    SOAPPart part = saajMsg.getSOAPPart();
    part.setContent(new DOMSource(doc));
    saajMsg.saveChanges();

    msg.setContent(SOAPMessage.class, saajMsg);

    msg.put(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE);
    msg.put(WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION, "true");
    msg.put(WSHandlerConstants.SIG_PROP_FILE, "outsecurity.properties");
    msg.put(WSHandlerConstants.USER, "myalias");
    msg.put("password", "myAliasPassword");
    //
    // This is necessary to convince the WSS4JOutInterceptor that we're
    // functioning as a requestor
    //
    msg.put(org.apache.cxf.message.Message.REQUESTOR_ROLE, true);

    handler.handleMessage(msg);
    doc = part;
    
    assertValid("//wsse:Security", doc);
    assertValid("//wsse:Security/ds:Signature", doc);

    byte[] docbytes = getMessageBytes(doc);
    //
    // Save the signature for future confirmation
    //
    List<WSHandlerResult> sigv = CastUtils.cast((List<?>)msg.get(WSHandlerConstants.SEND_SIGV));
    assertNotNull(sigv);
    assertTrue(sigv.size() != 0);
    
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());
    doc = StaxUtils.read(db, reader, false);

    WSS4JInInterceptor inHandler = new WSS4JInInterceptor();

    SoapMessage inmsg = new SoapMessage(new MessageImpl());
    ex.setInMessage(inmsg);
    inmsg.setContent(SOAPMessage.class, saajMsg);

    inHandler.setProperty(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE);
    inHandler.setProperty(WSHandlerConstants.SIG_PROP_FILE, "insecurity.properties");
    inHandler.setProperty(WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION, "true");

    inHandler.handleMessage(inmsg);
    
    //
    // Check that the inbound signature result was saved
    //
    WSSecurityEngineResult result = 
        (WSSecurityEngineResult) inmsg.get(WSS4JInInterceptor.SIGNATURE_RESULT);
    assertNotNull(result);
    
    List<WSHandlerResult> sigReceived = 
        CastUtils.cast((List<?>)inmsg.get(WSHandlerConstants.RECV_RESULTS));
    assertNotNull(sigReceived);
    assertTrue(sigReceived.size() != 0);
    
    testSignatureConfirmationResponse(sigv, sigReceived);
}