下面列出了javax.annotation.OverridingMethodsMustInvokeSuper#javax.xml.ws.handler.MessageContext 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
void callHandlersOnResponse(MessageUpdatableContext context, boolean handleFault) {
//Lets copy all the MessageContext.OUTBOUND_ATTACHMENT_PROPERTY to the message
Map<String, DataHandler> atts = (Map<String, DataHandler>) context.get(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS);
AttachmentSet attSet = context.packet.getMessage().getAttachments();
for (Map.Entry<String, DataHandler> entry : atts.entrySet()) {
String cid = entry.getKey();
if (attSet.get(cid) == null) { // Otherwise we would be adding attachments twice
Attachment att = new DataHandlerAttachment(cid, atts.get(cid));
attSet.add(att);
}
}
try {
//SERVER-SIDE
processor.callHandlersResponse(HandlerProcessor.Direction.OUTBOUND, context, handleFault);
} catch (WebServiceException wse) {
//no rewrapping
throw wse;
} catch (RuntimeException re) {
throw re;
}
}
private WebServiceContext createWebServiceContextMock(String expectedIP,
String expectedUser) {
requestMock = mock(HttpServletRequest.class);
when(requestMock.getRemoteAddr()).thenReturn(expectedIP);
Principal principalMock = mock(Principal.class);
when(principalMock.getName()).thenReturn(expectedUser);
MessageContext msgContextMock = mock(MessageContext.class);
when(msgContextMock.get(anyString())).thenReturn(requestMock);
WebServiceContext wsContextMock = mock(WebServiceContext.class);
when(wsContextMock.getUserPrincipal()).thenReturn(principalMock);
when(wsContextMock.getMessageContext()).thenReturn(msgContextMock);
return wsContextMock;
}
void callHandlersOnResponse(MessageUpdatableContext context, boolean handleFault) {
//Lets copy all the MessageContext.OUTBOUND_ATTACHMENT_PROPERTY to the message
Map<String, DataHandler> atts = (Map<String, DataHandler>) context.get(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS);
AttachmentSet attSet = context.packet.getMessage().getAttachments();
for (Entry<String, DataHandler> entry : atts.entrySet()) {
String cid = entry.getKey();
if (attSet.get(cid) == null) { // Otherwise we would be adding attachments twice
Attachment att = new DataHandlerAttachment(cid, atts.get(cid));
attSet.add(att);
}
}
try {
//SERVER-SIDE
processor.callHandlersResponse(HandlerProcessor.Direction.OUTBOUND, context, handleFault);
} catch (WebServiceException wse) {
//no rewrapping
throw wse;
} catch (RuntimeException re) {
throw re;
}
}
/**
* Called by close(MessageContext mc) in a Client Handlertube
*/
protected void closeClientsideHandlers(MessageContext msgContext) {
if (processor == null)
return;
if (remedyActionTaken) {
//Close only invoked handlers in the chain
//CLIENT-SIDE
processor.closeHandlers(msgContext, processor.getIndex(), 0);
processor.setIndex(-1);
//reset remedyActionTaken
remedyActionTaken = false;
} else {
//Close all handlers in the chain
//CLIENT-SIDE
processor.closeHandlers(msgContext, handlers.size() - 1, 0);
}
}
public Object get(Object key) {
if(packet.supports(key))
return packet.get(key); // strongly typed
if(packet.getHandlerScopePropertyNames(true).contains(key))
return null; // no such application-scope property
Object value = packet.invocationProperties.get(key);
//add the attachments from the Message to the corresponding attachment property
if(key.equals(MessageContext.INBOUND_MESSAGE_ATTACHMENTS)){
Map<String, DataHandler> atts = (Map<String, DataHandler>) value;
if(atts == null)
atts = new HashMap<String, DataHandler>();
AttachmentSet attSet = packet.getMessage().getAttachments();
for(Attachment att : attSet){
atts.put(att.getContentId(), att.asDataHandler());
}
return atts;
}
return value;
}
/**
* Calls close on previously invoked handlers.
* Also, Cleans up any state left over in the Tube instance from the current
* invocation, as Tube instances can be reused after the completion of MEP.
*
* On Client, SOAPHandlers are closed first and then LogicalHandlers
* On Server, LogicalHandlers are closed first and then SOAPHandlers
*/
final public void close(MessageContext msgContext) {
//assuming cousinTube is called if requestProcessingSucessful is true
if (requestProcessingSucessful) {
if (cousinTube != null) {
cousinTube.close(msgContext);
}
}
if (processor != null)
closeHandlers(msgContext);
// Clean up the exchange for next invocation.
exchange = null;
requestProcessingSucessful = false;
}
void callHandlersOnResponse(MessageUpdatableContext context, boolean handleFault) {
//Lets copy all the MessageContext.OUTBOUND_ATTACHMENT_PROPERTY to the message
Map<String, DataHandler> atts = (Map<String, DataHandler>) context.get(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS);
AttachmentSet attSet = context.packet.getMessage().getAttachments();
for (Entry<String, DataHandler> entry : atts.entrySet()) {
String cid = entry.getKey();
Attachment att = new DataHandlerAttachment(cid, atts.get(cid));
attSet.add(att);
}
try {
//SERVER-SIDE
processor.callHandlersResponse(HandlerProcessor.Direction.OUTBOUND, context, handleFault);
} catch (WebServiceException wse) {
//no rewrapping
throw wse;
} catch (RuntimeException re) {
throw re;
}
}
/**
* Returns the QName of the wsdl operation associated with this packet.
* <p/>
* Information such as Payload QName, wsa:Action header, SOAPAction HTTP header are used depending on the features
* enabled on the particular port.
*
* @return null if there is no WSDL model or
* runtime cannot uniquely identify the wsdl operation from the information in the packet.
*/
@Property(MessageContext.WSDL_OPERATION)
public final
@Nullable
QName getWSDLOperation() {
if (wsdlOperation != null) return wsdlOperation;
if ( wsdlOperationMapping == null) wsdlOperationMapping = getWSDLOperationMapping();
if ( wsdlOperationMapping != null ) wsdlOperation = wsdlOperationMapping.getOperationName();
return wsdlOperation;
}
/**
* Sets the Message Direction.
* MessageContext.MESSAGE_OUTBOUND_PROPERTY is changed.
*/
private void setDirection(Direction direction, C context) {
if (direction == Direction.OUTBOUND) {
context.put(MessageContext.MESSAGE_OUTBOUND_PROPERTY, true);
} else {
context.put(MessageContext.MESSAGE_OUTBOUND_PROPERTY, false);
}
}
public Object get(Object key) {
if(key == null)
return null;
Object value = asMapIncludingInvocationProperties.get(key);
//add the attachments from the Message to the corresponding attachment property
if(key.equals(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS) ||
key.equals(MessageContext.INBOUND_MESSAGE_ATTACHMENTS)){
Map<String, DataHandler> atts = (Map<String, DataHandler>) value;
if(atts == null)
atts = new HashMap<String, DataHandler>();
AttachmentSet attSet = packet.getMessage().getAttachments();
for(Attachment att : attSet){
String cid = att.getContentId();
if (cid.indexOf("@jaxws.sun.com") == -1) {
Object a = atts.get(cid);
if (a == null) {
a = atts.get("<" + cid + ">");
if (a == null) atts.put(att.getContentId(), att.asDataHandler());
}
} else {
atts.put(att.getContentId(), att.asDataHandler());
}
}
return atts;
}
return value;
}
@Override
protected Packet getResponse(Packet request, Exception e, WSDLPort port, WSBinding binding) {
Packet response = super.getResponse(request, e, port, binding);
if (e instanceof HTTPException) {
if (response.supports(MessageContext.HTTP_RESPONSE_CODE)) {
response.put(MessageContext.HTTP_RESPONSE_CODE, ((HTTPException)e).getStatusCode());
}
}
return response;
}
@Test
public void testGetSetMessageContext() {
WebServiceContextImpl wsci = new WebServiceContextImpl();
assertNull(wsci.getMessageContext());
MessageImpl msg = new MessageImpl();
final MessageContext ctx = new WrappedMessageContext(msg);
WebServiceContextImpl.setMessageContext(ctx);
assertSame(ctx, wsci.getMessageContext());
Thread t = new Thread() {
public void run() {
WebServiceContextImpl threadLocalWSCI = new WebServiceContextImpl();
assertNull(threadLocalWSCI.getMessageContext());
MessageImpl msg1 = new MessageImpl();
MessageContext threadLocalCtx = new WrappedMessageContext(msg1);
WebServiceContextImpl.setMessageContext(threadLocalCtx);
assertSame(threadLocalCtx, threadLocalWSCI.getMessageContext());
assertTrue(ctx != threadLocalWSCI.getMessageContext());
}
};
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
protected void initiateClosing(MessageContext mc) {
if (getBinding().getSOAPVersion() != null) {
super.initiateClosing(mc);
} else {
close(mc);
super.initiateClosing(mc);
}
}
/**
* Reverses the Message Direction.
* MessageContext.MESSAGE_OUTBOUND_PROPERTY is changed.
*/
private void reverseDirection(Direction origDirection, C context) {
if (origDirection == Direction.OUTBOUND) {
context.put(MessageContext.MESSAGE_OUTBOUND_PROPERTY, false);
} else {
context.put(MessageContext.MESSAGE_OUTBOUND_PROPERTY, true);
}
}
@Test
public void testCaptureServiceAndOperationNames_soapException() throws Exception {
when(mockSoapMessageContext.get(MessageContext.WSDL_SERVICE))
.thenReturn(wsdlService);
when(mockSoapMessageContext.getMessage()).thenReturn(mockMessage);
when(mockMessage.getSOAPBody()).thenThrow(new SOAPException());
jaxWsSoapContextHandler.captureServiceAndOperationNames(mockSoapMessageContext);
RequestInfo requestInfo = jaxWsSoapContextHandler.getLastRequestInfoBuilder().build();
assertEquals(wsdlService.getLocalPart(), requestInfo.getServiceName());
assertEquals("", requestInfo.getMethodName());
}
/**
* Gives a list of Reference Parameters in the Message
* <p>
* Headers which have attribute wsa:IsReferenceParameter="true"
* This is not cached as one may reset the Message.
*<p>
*/
@Property(MessageContext.REFERENCE_PARAMETERS)
public
@NotNull
List<Element> getReferenceParameters() {
Message msg = getMessage();
List<Element> refParams = new ArrayList<Element>();
if (msg == null) {
return refParams;
}
MessageHeaders hl = msg.getHeaders();
for (Header h : hl.asList()) {
String attr = h.getAttribute(AddressingVersion.W3C.nsUri, "IsReferenceParameter");
if (attr != null && (attr.equals("true") || attr.equals("1"))) {
Document d = DOMUtil.createDom();
SAX2DOMEx s2d = new SAX2DOMEx(d);
try {
h.writeTo(s2d, XmlUtil.DRACONIAN_ERROR_HANDLER);
refParams.add((Element) d.getLastChild());
} catch (SAXException e) {
throw new WebServiceException(e);
}
/*
DOMResult result = new DOMResult(d);
XMLDOMWriterImpl domwriter = new XMLDOMWriterImpl(result);
try {
h.writeTo(domwriter);
refParams.add((Element) result.getNode().getLastChild());
} catch (XMLStreamException e) {
throw new WebServiceException(e);
}
*/
}
}
return refParams;
}
@Override
protected void initiateClosing(MessageContext mc) {
if (getBinding().getSOAPVersion() != null) {
super.initiateClosing(mc);
} else {
close(mc);
super.initiateClosing(mc);
}
}
@Override
public boolean handleFault(SOAPMessageContext context) {
boolean isOut = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
// inbound
if (isOut == false) {
getTargetServer(context);
}
return true;
}
public DOMSource invoke(DOMSource request) {
QName qn = (QName)ctx.getMessageContext().get(MessageContext.WSDL_OPERATION);
if (qn == null) {
throw new RuntimeException("No Operation Name");
}
//XMLUtils.writeTo(request, System.out);
DOMSource response = new DOMSource();
try {
SOAPMessage msg = factory.createMessage();
msg.getSOAPPart().setContent(request);
SOAPBody body = msg.getSOAPBody();
Node n = body.getFirstChild();
while (n.getNodeType() != Node.ELEMENT_NODE) {
n = n.getNextSibling();
}
if (n.getLocalName().equals(sayHi.getLocalPart())) {
response.setNode(sayHiResponse.getSOAPPart());
} else if (n.getLocalName().equals(greetMe.getLocalPart())) {
response.setNode(greetMeResponse.getSOAPPart());
}
} catch (Exception ex) {
ex.printStackTrace();
}
return response;
}
Packet createPacket(SOAPMessage arg) {
Iterator iter = arg.getMimeHeaders().getAllHeaders();
Headers ch = new Headers();
while(iter.hasNext()) {
MimeHeader mh = (MimeHeader) iter.next();
ch.add(mh.getName(), mh.getValue());
}
Packet packet = new Packet(SAAJFactory.create(arg));
packet.invocationProperties.put(MessageContext.HTTP_REQUEST_HEADERS, ch);
return packet;
}
public MessageContext getMessageContext() {
Packet packet = getRequestPacket();
if (packet == null) {
throw new IllegalStateException("getMessageContext() can only be called while servicing a request");
}
return new EndpointMessageContextImpl(packet);
}
final void insertFaultMessage(C context,
ProtocolException exception) {
if(exception instanceof HTTPException) {
context.put(MessageContext.HTTP_RESPONSE_CODE,((HTTPException)exception).getStatusCode());
}
if (context != null) {
// non-soap case
context.setPacketMessage(Messages.createEmpty(binding.getSOAPVersion()));
}
}
/**
* Captures the raw XML message behind a SOAP interaction.
*
* @param context the context of the SOAP message passing through this handler
*/
private void captureSoapXml(SOAPMessageContext context) {
SOAPMessage message = context.getMessage();
if ((Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)) {
// Outbound message (request).
requestInfoXPathSet.parseMessage(lastRequestInfo, message);
} else {
// Inbound message (response).
responseInfoXPathSet.parseMessage(lastResponseInfo, message);
}
}
private RequestLogEntry createLogEntry(String title) {
final ServletContext servletContext = (ServletContext) context
.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
final RequestLog log = (RequestLog) servletContext
.getAttribute(InitServlet.REQUESTLOG);
final RequestLogEntry entry = log.createEntry(
OperationService.class.getSimpleName() + "." + title,
RequestDirection.INBOUND);
ServletRequest request = (ServletRequest) context.getMessageContext()
.get(MessageContext.SERVLET_REQUEST);
entry.setHost(request.getRemoteHost());
return entry;
}
protected List<String> getHandlerInfoList(MessageContext ctx) {
List<String> handlerInfoList = null;
if (ctx.containsKey("handler.info")) {
handlerInfoList = CastUtils.cast((List<?>)ctx.get("handler.info"));
} else {
handlerInfoList = new ArrayList<>();
ctx.put("handler.info", handlerInfoList);
ctx.setScope("handler.info", MessageContext.Scope.APPLICATION);
}
return handlerInfoList;
}
@AroundInvoke
public Object invoke(final InvocationContext context) throws Exception {
/**
* For JAX-WS invocations context.getContextData() must return the
* JAX-WS MessageContex. As per the agreement between OpenEJB and the Web Service Provider
* the MessageContex should have been passed into the container.invoke method
* and the container should then ensure it's available via getContextData()
* for the duration of this call.
*/
final MessageContext messageContext = (MessageContext) context.getContextData();
org.junit.Assert.assertNotNull("message context should not be null", messageContext);
org.junit.Assert.assertTrue("the Web Service Provider's message context should be used", messageContext instanceof FakeMessageContext);
// Try to get JAX-RPC context, should throw an exception since it's JAX-WS
try {
ctx.getMessageContext();
org.junit.Assert.fail("Did not throw exception");
} catch (final IllegalStateException e) {
// that's expected since it's JAX-WS
}
// test @Resource WebServiceContext injection
org.junit.Assert.assertNotNull("web service context should not be null", wsContext);
org.junit.Assert.assertEquals("msg context should be the smae", messageContext, wsContext.getMessageContext());
org.junit.Assert.assertFalse("user in role 'foo'", wsContext.isUserInRole("foo"));
org.junit.Assert.assertNotNull("user principal", wsContext.getUserPrincipal());
calls.add(Call.Bean_Invoke_BEFORE);
final Object o = context.proceed();
calls.add(Call.Bean_Invoke_AFTER);
return o;
}
@Test
public void shouldHandleOutgoingContextInOutgoingMethod() {
final SOAPMessageContext messageContext = mock(SOAPMessageContext.class);
when(messageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)).thenReturn(Boolean.TRUE);
unit.handleMessage(messageContext);
verify(unit).handleOutgoing(messageContext);
}
/** {@inheritDoc} */
public void close(MessageContext arg0) {}
@Property(MessageContext.SERVLET_RESPONSE)
public Object getServletResponse() {
return httpExchange.getAttribute(MessageContext.SERVLET_RESPONSE);
}
@Test
public void testSOAPHandlerHandleMessageReturnTrueClient() throws Exception {
TestHandler<LogicalMessageContext> handler1 = new TestHandler<>(false);
TestHandler<LogicalMessageContext> handler2 = new TestHandler<LogicalMessageContext>(false) {
public boolean handleMessage(LogicalMessageContext ctx) {
super.handleMessage(ctx);
try {
Boolean outbound = (Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (!outbound) {
LogicalMessage msg = ctx.getMessage();
Source source = msg.getPayload();
assertNotNull(source);
}
} catch (Exception e) {
e.printStackTrace();
fail(e.toString());
}
return true;
}
};
TestSOAPHandler soapHandler1 = new TestSOAPHandler(false);
TestSOAPHandler soapHandler2 = new TestSOAPHandler(false);
addHandlersToChain((BindingProvider)handlerTest, handler1, handler2, soapHandler1, soapHandler2);
List<String> resp = handlerTest.ping();
assertNotNull(resp);
assertEquals("handle message was not invoked", 2, handler1.getHandleMessageInvoked());
assertEquals("handle message was not invoked", 2, handler2.getHandleMessageInvoked());
assertEquals("handle message was not invoked", 2, soapHandler1.getHandleMessageInvoked());
assertEquals("handle message was not invoked", 2, soapHandler2.getHandleMessageInvoked());
assertEquals("close must be called", 1, handler1.getCloseInvoked());
assertEquals("close must be called", 1, handler2.getCloseInvoked());
assertEquals("close must be called", 1, soapHandler1.getCloseInvoked());
assertEquals("close must be called", 1, soapHandler2.getCloseInvoked());
assertTrue(soapHandler2.getInvokeOrderOfClose()
< soapHandler1.getInvokeOrderOfClose());
assertTrue(soapHandler1.getInvokeOrderOfClose()
< handler2.getInvokeOrderOfClose());
assertTrue(handler2.getInvokeOrderOfClose()
< handler1.getInvokeOrderOfClose());
// the server has encoded into the response the order in
// which the handlers have been invoked, parse it and make
// sure everything is ok expected order for inbound interceptors
String[] handlerNames = {"soapHandler4", "soapHandler3", "handler2", "handler1", "servant",
"handler1", "handler2", "soapHandler3", "soapHandler4"};
assertEquals(handlerNames.length, resp.size());
Iterator<String> iter = resp.iterator();
for (String expected : handlerNames) {
assertEquals(expected, iter.next());
}
}