下面列出了javax.xml.parsers.DocumentBuilder#setEntityResolver ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Returns the root of deployment descriptor bean graph for java.io.File object.
*
* @param inputSource source representing the ejb-jar.xml file
* @return EjbJar object - root of the deployment descriptor bean graph
*/
public EjbJar getDDRoot(InputSource inputSource) throws IOException, SAXException {
ErrorHandler errorHandler = new ErrorHandler();
DocumentBuilder parser = createParser(errorHandler);
parser.setEntityResolver(DDResolver.getInstance());
Document document = parser.parse(inputSource);
SAXParseException error = errorHandler.getError();
String version = extractVersion(document);
EjbJar original = createEjbJar(version, document);
EjbJarProxy ejbJarProxy = new EjbJarProxy(original, version);
ejbJarProxy.setError(error);
if (error != null) {
ejbJarProxy.setStatus(EjbJar.STATE_INVALID_PARSABLE);
} else {
ejbJarProxy.setStatus(EjbJar.STATE_VALID);
}
return ejbJarProxy;
}
/**
* * This method provides a secured document builder which will secure XXE attacks.
*
* @param setIgnoreComments whether to set setIgnoringComments in DocumentBuilderFactory.
* @return DocumentBuilder
* @throws ParserConfigurationException
*/
private static DocumentBuilder getSecuredDocumentBuilder(boolean setIgnoreComments) throws
ParserConfigurationException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setIgnoringComments(setIgnoreComments);
documentBuilderFactory.setNamespaceAware(true);
documentBuilderFactory.setExpandEntityReferences(false);
documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
documentBuilderFactory.setFeature(EXTERNAL_GENERAL_ENTITIES_URI, false);
SecurityManager securityManager = new SecurityManager();
securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
documentBuilder.setEntityResolver(new CarbonEntityResolver());
return documentBuilder;
}
protected Document getDocument(boolean namespaceAware, boolean validate) throws Exception {
// TODO: optimize this
final InputSource source = getTestXMLInputSource();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(validate);
dbf.setNamespaceAware(namespaceAware);
dbf.setAttribute(JAXPConstants.JAXP_SCHEMA_LANGUAGE, JAXPConstants.W3C_XML_SCHEMA);
DocumentBuilder db = dbf.newDocumentBuilder();
LOG.info("Setting entityresolver");
db.setEntityResolver(Util.getNotificationEntityResolver(services.getNotificationContentTypeService()));
db.setErrorHandler(new SimpleErrorHandler(LOG));
return db.parse(source);
}
/**
* 根据流生成xml dom
* @param is 流
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public XMLUtil(InputSource is) throws ParserConfigurationException, SAXException, IOException{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
//不检查DTD
db.setEntityResolver( new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
return new InputSource(new StringReader(""));
}
}
);
//读取文件
doc=db.parse(is);
}
/**
* creates a parser using JAXP API.
*/
public static DocumentBuilder newParser() throws SAXException {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver( new HttpUnitUtils.ClasspathEntityResolver() );
return builder;
} catch (ParserConfigurationException ex) {
// redirect the new exception for code compatibility
throw new SAXException( ex );
}
}
public DDParse(InputSource is, String defaultPublicId) throws SAXException, IOException {
try {
SunDDErrorHandler errorHandler = new SunDDErrorHandler();
DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = parserFactory.newDocumentBuilder();
parser.setErrorHandler(errorHandler);
parser.setEntityResolver(SunDDResolver.getInstance());
Document d = parser.parse(is);
initialize(d, errorHandler.getError(), defaultPublicId);
} catch (NullPointerException | ParserConfigurationException ex) {
throw new SAXException(ex.getMessage());
}
}
public void testDOM(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
DocumentBuilder docBuilder = getDomBuilder(setUseCatalog, useCatalog, catalog);
docBuilder.setEntityResolver(handler);
Document doc = docBuilder.parse(xml);
Node node = doc.getElementsByTagName(elementInSystem).item(0);
String result = node.getFirstChild().getTextContent();
Assert.assertEquals(result.trim(), expected);
}
/**
* * This method provides a secured document builder which will secure XXE attacks.
*
* @return DocumentBuilder
* @throws ParserConfigurationException
*/
private DocumentBuilder getSecuredDocumentBuilder() throws ParserConfigurationException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
documentBuilderFactory.setExpandEntityReferences(false);
documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
documentBuilderFactory.setFeature(EXTERNAL_GENERAL_ENTITIES_URI, false);
SecurityManager securityManager = new SecurityManager();
securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
documentBuilder.setEntityResolver(new CarbonEntityResolver());
return documentBuilder;
}
public Document getDocument( String _renderedBody ) throws cfmRunTimeException{
try{
DocumentBuilder builder;
InputSource is = new InputSource( new StringReader( _renderedBody ) );
Document doc;
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setValidating( false );
builder = builderFactory.newDocumentBuilder();
builder.setEntityResolver( new NoValidationResolver() );
doc = builder.parse( is );
return doc;
} catch (Exception e) {
throw newRunTimeException( "Failed to create valid xhtml document due to " + e.getClass().getName() + ": " + e.getMessage() );
}
}
protected Object initialValue() {
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(new JBossEntityResolver());
return builder;
}
catch (ParserConfigurationException e)
{
throw PicketBoxMessages.MESSAGES.failedToCreateDocumentBuilder(e);
}
}
protected static XmlConfigurator parse(InputStream stream) throws java.io.IOException {
/**
* CAUTION: crappy code ahead ! I (bela) am not an XML expert, so the code below is pretty amateurish...
* But it seems to work, and it is executed only on startup, so no perf loss on the critical path.
* If somebody wants to improve this, please be my guest.
*/
try {
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
factory.setValidating(false); //for now
DocumentBuilder builder=factory.newDocumentBuilder();
builder.setEntityResolver(new ClassPathEntityResolver());
Document document=builder.parse(stream);
// The root element of the document should be the "config" element,
// but the parser(Element) method checks this so a check is not
// needed here.
Element configElement = document.getDocumentElement();
return parse(configElement);
}
catch(Exception x) {
if(x instanceof java.io.IOException)
throw (java.io.IOException)x;
else {
IOException tmp=new IOException();
tmp.initCause(x);
throw tmp;
}
}
}
/**
* Get the <code>DocumentBuilder</code> instance used to parse the control
* XML in an XMLTestCase.
* @return parser for control values
* @throws ConfigurationException
*/
public static DocumentBuilder newControlParser()
throws ConfigurationException {
try {
controlBuilderFactory = getControlDocumentBuilderFactory();
DocumentBuilder builder =
controlBuilderFactory.newDocumentBuilder();
if (controlEntityResolver!=null) {
builder.setEntityResolver(controlEntityResolver);
}
return builder;
} catch (ParserConfigurationException ex) {
throw new ConfigurationException(ex);
}
}
/**
* Builds a document from the content of the web response.
* A warning is logged if an exception is thrown while parsing the XML content
* (for instance when the content is not a valid XML and can't be parsed).
*
* @param webResponse the response from the server
* @throws IOException if the page could not be created
* @return the parse result
* @throws SAXException if the parsing fails
* @throws ParserConfigurationException if a DocumentBuilder cannot be created
*/
public static Document buildDocument(final WebResponse webResponse)
throws IOException, SAXException, ParserConfigurationException {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
if (webResponse == null) {
return factory.newDocumentBuilder().newDocument();
}
factory.setNamespaceAware(true);
final InputStreamReader reader = new InputStreamReader(
new BOMInputStream(webResponse.getContentAsStream()),
webResponse.getContentCharset());
// we have to do the blank input check and the parsing in one step
final TrackBlankContentReader tracker = new TrackBlankContentReader(reader);
final InputSource source = new InputSource(tracker);
final DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(DISCARD_MESSAGES_HANDLER);
builder.setEntityResolver(new EntityResolver() {
@Override
public InputSource resolveEntity(final String publicId, final String systemId)
throws SAXException, IOException {
return new InputSource(new StringReader(""));
}
});
try {
// this closes the input source/stream
return builder.parse(source);
}
catch (final SAXException e) {
if (tracker.wasBlank()) {
return factory.newDocumentBuilder().newDocument();
}
throw e;
}
}
@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);
}
protected LibraryDescriptor parseTLD(InputStream content) throws ParserConfigurationException, SAXException, IOException {
final Map<String, Tag> tags = new HashMap<>();
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
InputSource is = new InputSource(content); //the ecoding should be autodetected
docBuilder.setEntityResolver(UserCatalog.getDefault().getEntityResolver()); //we count on TaglibCatalog from web.core module
Document doc = docBuilder.parse(is);
// //usually the default taglib prefix
// Node tagLib = FaceletsLibraryDescriptor.getNodeByName(doc, "taglib"); //NOI18N
// String prefix = getTextContent(tagLib, "short-name"); //NOI18N
// String uri = getTextContent(tagLib, "uri"); //NOI18N
// String displayName = getTextContent(tagLib, "display-name"); //NOI18N
//scan the <tag> nodes content - the tag descriptions
NodeList tagNodes = doc.getElementsByTagName("tag"); //NOI18N
if (tagNodes != null) {
for (int i = 0; i < tagNodes.getLength(); i++) {
Node tag = tagNodes.item(i);
String tagName = getTextContent(tag, "name"); //NOI18N
String tagDescription = getTextContent(tag, "description"); //NOI18N
Map<String, Attribute> attrs = new HashMap<>();
//find attributes
for (Node attrNode : FaceletsLibraryDescriptor.getNodesByName(tag, "attribute")) { //NOI18N
String aName = getTextContent(attrNode, "name"); //NOI18N
String aDescription = getTextContent(attrNode, "description"); //NOI18N
boolean aRequired = Boolean.parseBoolean(getTextContent(attrNode, "required")); //NOI18N
String aType = null;
String aMethodSignature = null;
//type
Node aDeferredValueNode = FaceletsLibraryDescriptor.getNodeByName(attrNode, "deferred-value"); //NOI18N
if(aDeferredValueNode != null) {
aType = FaceletsLibraryDescriptor.getTextContent(aDeferredValueNode, "type"); //NOI18N
}
//method signature
Node aDeferredMethodNode = FaceletsLibraryDescriptor.getNodeByName(attrNode, "deferred-method"); //NOI18N
if(aDeferredMethodNode != null) {
aType = FaceletsLibraryDescriptor.getTextContent(aDeferredMethodNode, "method-signature"); //NOI18N
}
attrs.put(aName, new Attribute.DefaultAttribute(aName, aDescription, aType, aRequired, aMethodSignature));
}
tags.put(tagName, new TagImpl(tagName, tagDescription, attrs));
}
}
return new LibraryDescriptor() {
@Override
public String getNamespace() {
return TldProxyLibraryDescriptor.this.getNamespace();
}
@Override
public String getPrefix() {
return TldProxyLibraryDescriptor.this.getPrefix();
}
@Override
public Map<String, Tag> getTags() {
return tags;
}
};
}
@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);
}
@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);
}
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);
}
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);
}
/**
* Test that an action mismatch gets mapped to a proper fault code
*/
@Test
public void testActionMismatch() 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);
handler.handleMessage(msg);
doc = part;
assertValid("//wsse:Security", 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);
WSS4JInInterceptor inHandler = new WSS4JInInterceptor();
SoapMessage inmsg = new SoapMessage(new MessageImpl());
ex.setInMessage(inmsg);
inmsg.setContent(SOAPMessage.class, saajMsg);
inHandler.setProperty(WSHandlerConstants.ACTION,
WSHandlerConstants.TIMESTAMP + " " + WSHandlerConstants.USERNAME_TOKEN);
inHandler.setProperty(WSHandlerConstants.PW_CALLBACK_CLASS, TestPwdCallback.class.getName());
try {
inHandler.handleMessage(inmsg);
fail("Expected failure on an action mismatch");
} catch (SoapFault fault) {
assertTrue(fault.getReason().startsWith(
"An error was discovered processing the <wsse:Security> header"));
QName faultCode = new QName(WSConstants.WSSE_NS, "InvalidSecurity");
assertTrue(fault.getFaultCode().equals(faultCode));
}
}