01: package demo.ws_rm.common;
02:
03: import java.util.Iterator;
04:
05: import javax.xml.soap.Name;
06: import javax.xml.soap.SOAPException;
07: import javax.xml.soap.SOAPHeader;
08: import javax.xml.soap.SOAPHeaderElement;
09: import javax.xml.ws.handler.soap.SOAPMessageContext;
10:
11: /**
12: * Discards a protion of inbound application-level messages to simulate
13: * message loss. Note that out-of-band WS-RM protocol messages are always
14: * left intact.
15: */
16: public class MessageLossSimulator extends HandlerBase {
17:
18: /**
19: * Discard every second message
20: */
21: private static final int LOSS_FACTOR = 2;
22: private int inboundMessageCount;
23:
24: public boolean handleMessage(SOAPMessageContext context) {
25: return continueProcessing(context);
26: }
27:
28: public boolean handleFault(SOAPMessageContext context) {
29: return true;
30: }
31:
32: /**
33: * @return true if the current message should not be discarded
34: */
35: private synchronized boolean continueProcessing(
36: SOAPMessageContext context) {
37: if (!(isOutbound(context) || isRMOutOfBand(context))
38: && ++inboundMessageCount % LOSS_FACTOR == 0) {
39: discardWSHeaders(context);
40: System.out
41: .println("*** Discarding current inbound message ***");
42: return false;
43: }
44: return true;
45: }
46:
47: /**
48: * @return true if this is a WS-RM out-of-band protocol message
49: */
50: protected boolean isRMOutOfBand(SOAPMessageContext context) {
51: String action = getAction(context);
52: return action != null && action.startsWith(WSRM_NAMESPACE_URI);
53: }
54:
55: /**
56: * Discard any WS-* headers from the message
57: */
58: private void discardWSHeaders(SOAPMessageContext context) {
59: try {
60: SOAPHeader header = context.getMessage().getSOAPPart()
61: .getEnvelope().getHeader();
62: Iterator headerElements = header.examineAllHeaderElements();
63: while (headerElements.hasNext()) {
64: SOAPHeaderElement headerElement = (SOAPHeaderElement) headerElements
65: .next();
66: Name headerName = headerElement.getElementName();
67: if (WSRM_NAMESPACE_URI.equals(headerName.getURI())
68: || WSRM_NAMESPACE_URI.equals(headerName
69: .getURI())) {
70: headerElement.detachNode();
71: }
72: }
73: } catch (SOAPException e) {
74: System.out.println("discard WS headers failed: " + e);
75: }
76: }
77: }
|