javax.xml.rpc.handler.MessageContext Java Examples

The following examples show how to use javax.xml.rpc.handler.MessageContext. 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: HandlerChainImpl.java    From tomee with Apache License 2.0 6 votes vote down vote up
public boolean handleFault(MessageContext context) {
    MessageSnapshot snapshot = new MessageSnapshot(context);
    try {
        for (Iterator iterator = invokedHandlers.iterator(); iterator.hasNext(); ) {
            Handler handler = (Handler) iterator.next();
            if (!handler.handleFault(context)) {
                return false;
            }
        }
    } finally {
        saveChanges(context);
    }
    if (!snapshot.equals(context)) {
        throw new IllegalStateException("The soap message operation or arguments were illegally modified by the HandlerChain");
    }
    return true;
}
 
Example #2
Source File: JaxRpcInvocationTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@AroundInvoke
public Object invoke(final InvocationContext context) throws Exception {

    /**
     * For JAX-RPC invocations the JAX-RPC MessageContex must be
     * available in the javax.ejb.SessionContext via the getMessageContext
     * method.  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 the SessionContext
     * for the duration of this call.
     */
    final MessageContext messageContext = ctx.getMessageContext();

    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);

    calls.add(Call.Bean_Invoke_BEFORE);
    final Object o = context.proceed();
    calls.add(Call.Bean_Invoke_AFTER);
    return o;
}
 
Example #3
Source File: HandlerChainImpl.java    From tomee with Apache License 2.0 6 votes vote down vote up
public MessageSnapshot(MessageContext soapMessage) {
    SOAPMessage message = ((SOAPMessageContext) soapMessage).getMessage();
    if (message == null || message.getSOAPPart() == null) {
        operationName = null;
        parameterNames = null;
    } else {
        SOAPBody body = getBody(message);

        SOAPElement operation = ((SOAPElement) body.getChildElements().next());
        this.operationName = operation.getElementName().toString();

        this.parameterNames = new ArrayList<String>();
        for (Iterator i = operation.getChildElements(); i.hasNext(); ) {
            SOAPElement parameter = (SOAPElement) i.next();
            String element = parameter.getElementName().toString();
            parameterNames.add(element);
        }
    }
}
 
Example #4
Source File: HandlerChainImpl.java    From tomee with Apache License 2.0 6 votes vote down vote up
public boolean handleResponse(MessageContext context) {
    MessageSnapshot snapshot = new MessageSnapshot(context);
    try {
        for (Iterator iterator = invokedHandlers.iterator(); iterator.hasNext(); ) {
            Handler handler = (Handler) iterator.next();
            if (!handler.handleResponse(context)) {
                return false;
            }
        }
    } finally {
        saveChanges(context);
    }
    if (!snapshot.equals(context)) {
        throw new IllegalStateException("The soap message operation or arguments were illegally modified by the HandlerChain");
    }
    return true;
}
 
Example #5
Source File: HandlerChainImpl.java    From tomee with Apache License 2.0 6 votes vote down vote up
public boolean handleRequest(MessageContext context) {
    MessageSnapshot snapshot = new MessageSnapshot(context);
    try {
        for (int i = 0; i < size(); i++) {
            Handler currentHandler = (Handler) get(i);
            invokedHandlers.addFirst(currentHandler);
            try {
                if (!currentHandler.handleRequest(context)) {
                    return false;
                }
            } catch (SOAPFaultException e) {
                throw e;
            }
        }
    } finally {
        saveChanges(context);
    }

    if (!snapshot.equals(context)) {
        throw new IllegalStateException("The soap message operation or arguments were illegally modified by the HandlerChain");
    }
    return true;
}
 
Example #6
Source File: JPlagClientAccessHandler.java    From jplag with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Adds an "Access" element to the SOAP header
 */
public boolean handleRequest(MessageContext msgct) {
	if (msgct instanceof SOAPMessageContext) {
		SOAPMessageContext smsgct = (SOAPMessageContext) msgct;
		try {
			SOAPMessage msg = smsgct.getMessage();
			SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
			SOAPHeader header = msg.getSOAPHeader();

			if (header == null)
				header = envelope.addHeader(); // add an header if non exists

			SOAPHeaderElement accessElement = header.addHeaderElement(envelope.createName("Access", "ns0", JPLAG_TYPES_NS));
			SOAPElement usernameelem = accessElement.addChildElement("username");
			usernameelem.addTextNode(username);
			SOAPElement passwordelem = accessElement.addChildElement("password");
			passwordelem.addTextNode(password);
			SOAPElement compatelem = accessElement.addChildElement("compatLevel");
			compatelem.addTextNode(compatibilityLevel + "");
		} catch (SOAPException x) {
			System.out.println("Unable to create access SOAP header!");
			x.printStackTrace();
		}
	}
	return true;
}
 
Example #7
Source File: LoggingHandler.java    From jplag with GNU General Public License v3.0 6 votes vote down vote up
public boolean handleRequest(MessageContext context) {
//		System.out.println("Entering LoggingHandler::handleRequest()");
/*		try
		{
			SOAPMessageContext smsgct=(SOAPMessageContext) context;
			SOAPMessage msg=smsgct.getMessage();
			SOAPEnvelope envelope=msg.getSOAPPart().getEnvelope();
			SOAPHeader header=msg.getSOAPHeader();
			if(header==null)
			{
				header=envelope.addHeader();
			}
		
			SOAPHeaderElement accessElement=header.addHeaderElement(
					envelope.createName("logged","ns1",
					"http://example.com/jplag"));
			accessElement.addTextNode("You got logged!!");
		}
		catch(SOAPException e)
		{
			e.printStackTrace();
		}*/
		logMessage("request", context);
//		System.out.println("Leaving LoggingHandler::handleRequest()");
		return true;
	}
 
Example #8
Source File: LoggingHandler.java    From jplag with GNU General Public License v3.0 6 votes vote down vote up
private String logSOAPMessage(MessageContext context) {
		StringBuffer stringBuffer = new StringBuffer();
		SOAPMessageContext smc = (SOAPMessageContext) context;
		SOAPMessage soapMessage = smc.getMessage();
/*		try
		{
			SOAPBody soapBody = soapMessage.getSOAPBody();
			NodeList list=soapBody.getElementsByTagName("inputZipFile");
		}
		catch(Exception e)
		{
			// ignore filtering
		}*/

		ByteArrayOutputStream bout= new ByteArrayOutputStream();
		try {
			soapMessage.writeTo(bout);
		} catch(Exception e) {
			e.printStackTrace(System.out);
		}
		stringBuffer.append(bout.toString() + "\n");

		return stringBuffer.toString();
	}
 
Example #9
Source File: LoggingHandler.java    From jplag with GNU General Public License v3.0 6 votes vote down vote up
private void logMessage(String method, MessageContext context) {
     FileOutputStream fout = createFile();
     if(fout==null) return;
     LogOutputStream out = new LogOutputStream(fout, true);
     try {
         out.println("<" + method + ">");
         //Uncomment this statement to log the SOAP messages.
         out.println(logSOAPMessage(context));
         out.println("</" + method + ">");
     } catch (Exception ex) {
         ex.printStackTrace(System.out);
throw new JAXRPCException("LoggingHandler: Unable to log the message in " + method + " - {" + ex.getClass().getName() + "}"
		+ ex.getMessage());
     } finally {
         out.flush();
out.close();
     }
 }
 
Example #10
Source File: BaseSessionContext.java    From tomee with Apache License 2.0 5 votes vote down vote up
public MessageContext getMessageContext() throws IllegalStateException {
    doCheck(Call.getMessageContext);
    final ThreadContext threadContext = ThreadContext.getThreadContext();
    final MessageContext messageContext = threadContext.get(MessageContext.class);
    if (messageContext == null) {
        throw new IllegalStateException("Only calls on the service-endpoint have a MessageContext.");
    }
    return messageContext;
}
 
Example #11
Source File: HandlerChainImpl.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void saveChanges(MessageContext context) {
    try {
        SOAPMessage message = ((SOAPMessageContext) context).getMessage();
        if (message != null) {
            message.saveChanges();
        }
    } catch (SOAPException e) {
        throw new ServerRuntimeException("Unable to save changes to SOAPMessage : " + e.toString());
    }
}
 
Example #12
Source File: JPlagClientAccessHandler.java    From jplag with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Adds an "Access" element to the SOAP header
 */
public boolean handleRequest(MessageContext msgct) {
	if(msgct instanceof SOAPMessageContext) {
		SOAPMessageContext smsgct=(SOAPMessageContext) msgct;
		try	{
			SOAPMessage msg=smsgct.getMessage();
			SOAPEnvelope envelope=msg.getSOAPPart().getEnvelope();
			SOAPHeader header=msg.getSOAPHeader();
			
			if(header==null)
				header=envelope.addHeader(); // add an header if non exists
			
			SOAPHeaderElement accessElement=header.addHeaderElement(
					envelope.createName("Access","ns0",
							"http://www.ipd.uni-karlsruhe.de/jplag/types"));
			SOAPElement usernameelem=accessElement.addChildElement(
                       "username");
			usernameelem.addTextNode(username);
			SOAPElement passwordelem=accessElement.addChildElement(
                       "password");
			passwordelem.addTextNode(password);
               SOAPElement compatelem=accessElement.addChildElement(
                       "compatLevel");
               compatelem.addTextNode(compatibilityLevel+"");
		} catch (SOAPException x) {
			System.out.println("Unable to create access SOAP header!");
			x.printStackTrace();
		}
	}
	return true;
}
 
Example #13
Source File: WsServlet.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public MessageContext getMessageContext() {
    return getContext().getMessageContext();
}
 
Example #14
Source File: ManagedContext.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public MessageContext getMessageContext() throws IllegalStateException {
    throw new IllegalStateException("@ManagedBeans do not support Web Service interfaces");
}
 
Example #15
Source File: StatefulContext.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public MessageContext getMessageContext() throws IllegalStateException {
    throw new IllegalStateException("@Stateful beans do not support Web Service interfaces");
}
 
Example #16
Source File: JaxRpcInvocationContext.java    From tomee with Apache License 2.0 4 votes vote down vote up
public JaxRpcInvocationContext(final Operation operation, final List<Interceptor> interceptors, final Object target, final Method method, final MessageContext messageContext, final Object... parameters) {
    super(operation, interceptors, target, method, parameters);
    getContextData().put(MessageContext.class.getName(), messageContext);
}
 
Example #17
Source File: WsServlet.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public MessageContext getMessageContext() {
    throw new IllegalStateException("Method cannot be called outside a request context");
}
 
Example #18
Source File: WsServlet.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public MessageContext getMessageContext() {
    return (MessageContext) request.getAttribute(WsConstants.MESSAGE_CONTEXT);
}
 
Example #19
Source File: LoggingHandler.java    From jplag with GNU General Public License v3.0 4 votes vote down vote up
public boolean handleResponse(MessageContext context) {
	logMessage("response", context);
	return true;
}
 
Example #20
Source File: TestSessionContext.java    From development with Apache License 2.0 4 votes vote down vote up
@Override
public MessageContext getMessageContext() throws IllegalStateException {
    throw new UnsupportedOperationException();
}
 
Example #21
Source File: LoggingHandler.java    From jplag with GNU General Public License v3.0 4 votes vote down vote up
public boolean handleFault(MessageContext context) {
	logMessage("fault", context);
	return true;
}
 
Example #22
Source File: JPlagServerAccessHandler.java    From jplag with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Checks whether the SOAP message contains a valid Access element (correct
 * username + password) and whether the account may still be used
 */
public boolean handleRequest(MessageContext context) {
	String username = null;
	String password = null;
	int compatLevel = 0;
	if (context instanceof SOAPMessageContext) {
		SOAPMessageContext smsg = (SOAPMessageContext) context;

		/*
		 * Iterator iter = context.getPropertyNames();
		 * System.out.println("Context properties:"); while(iter.hasNext())
		 * { String propname = (String) iter.next();
		 * System.out.println(propname + " = " +
		 * context.getProperty(propname).toString()); }
		 * 
		 * HttpServletRequest request = (HttpServletRequest)
		 * context.getProperty(
		 * "com.sun.xml.rpc.server.http.HttpServletRequest");
		 * System.out.println("Client IP: " + request.getRemoteAddr());
		 */

		try {
			SOAPHeader header = smsg.getMessage().getSOAPHeader();
			if (header != null) {
				@SuppressWarnings("unchecked")
				Iterator<SOAPHeaderElement> headers = header.examineAllHeaderElements();
				while (headers.hasNext()) {
					SOAPHeaderElement he = headers.next();

					if (he.getElementName().getLocalName().equals("Access")) {
						@SuppressWarnings("unchecked")
						Iterator<SOAPElement> elements = he.getChildElements();
						while (elements.hasNext()) {
							SOAPElement e = elements.next();
							String name = e.getElementName().getLocalName();
							if (name.equals("username"))
								username = e.getValue();
							else if (name.equals("password"))
								password = e.getValue();
							else if (name.equals("compatLevel")) {
								try {
									compatLevel = Integer.parseInt(e.getValue());
								} catch (NumberFormatException ex) {
									compatLevel = -1;
								}
							}
						}
					}
				}
				if (compatLevel < compatibilityLevel) {
					replaceByJPlagException(smsg, "Client outdated!", "Please update your client " + "to compatibility level "
							+ compatibilityLevel + ".");
					return false;
				}
				if (username != null && password != null) {
					int state = JPlagCentral.getInstance().getUserAdmin().getLoginState(username, password);
					if ((state & UserAdmin.MASK_EXPIRED) != 0) {
						replaceByJPlagException(smsg, "Access denied!", "Your account has " + "expired! Please contact the JPlag "
								+ "administrator to reactivate it!");
						return false;
					} else if ((state & UserAdmin.MASK_DEACTIVATED) != 0) {
						replaceByJPlagException(smsg, "Access denied!", "Your account has " + "been deactivated! Please contact the "
								+ "JPlag administrator to reactivate it!");
						return false;
					} else if (state != UserAdmin.USER_INVALID)
						return true;
				}
			} else {
				System.out.println("No header available!");
				replaceByJPlagException(smsg, "Access denied!", "The SOAP message doesn't contain an access header!");
				return false;
			}
		} catch (SOAPException x) {
			x.printStackTrace();
		}
		System.out.println("[" + new Date() + "] Access denied for user \"" + username + "\"!");

		replaceByJPlagException(smsg, "Access denied!", "Check your username and password!");
		return false;
	}
	System.out.println("Not a SOAP message context!!!");
	return false;
}
 
Example #23
Source File: JaxRpcInvocationTest.java    From tomee with Apache License 2.0 2 votes vote down vote up
public void testWebServiceInvocations() throws Exception {
    System.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, InitContextFactory.class.getName());

    final ConfigurationFactory config = new ConfigurationFactory();
    final Assembler assembler = new Assembler();

    assembler.createProxyFactory(config.configureService(ProxyFactoryInfo.class));
    assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class));
    assembler.createSecurityService(config.configureService(SecurityServiceInfo.class, "PseudoSecurityService", null, "PseudoSecurityService", null));

    assembler.createContainer(config.configureService(StatelessSessionContainerInfo.class));


    final EjbJarInfo ejbJar = config.configureApplication(buildTestApp());

    assembler.createApplication(ejbJar);

    final ContainerSystem containerSystem = SystemInstance.get().getComponent(ContainerSystem.class);

    final BeanContext beanContext = containerSystem.getBeanContext("EchoBean");

    assertNotNull(beanContext);

    assertEquals("ServiceEndpointInterface", EchoServiceEndpoint.class, beanContext.getServiceEndpointInterface());


    // OK, Now let's fake a web serivce invocation coming from any random
    // web service provider.  The web serivce provider needs supply
    // the MessageContext and an interceptor to do the marshalling as
    // the arguments of the standard container.invoke signature.

    // So let's create a fake message context.
    final MessageContext messageContext = new FakeMessageContext();

    // Now let's create a fake interceptor as would be supplied by the
    // web service provider.  Instead of writing "fake" marshalling
    // code that would pull the arguments from the soap message, we'll
    // just give it the argument values directly.
    final Object wsProviderInterceptor = new FakeWsProviderInterceptor("Hello world");

    // Ok, now we have the two arguments expected on a JAX-RPC Web Service
    // invocation as per the OpenEJB-specific agreement between OpenEJB
    // and the Web Service Provider
    final Object[] args = new Object[]{messageContext, wsProviderInterceptor};

    // Let's grab the container as the Web Service Provider would do and
    // perform an invocation
    final RpcContainer container = (RpcContainer) beanContext.getContainer();

    final Method echoMethod = EchoServiceEndpoint.class.getMethod("echo", String.class);

    final String value = (String) container.invoke("EchoBean", InterfaceType.SERVICE_ENDPOINT, echoMethod.getDeclaringClass(), echoMethod, args, null);

    assertCalls(Call.values());
    calls.clear();
    assertEquals("Hello world", value);

}