FileDocCategorySizeDatePackage
MessageExchangeHelper.javaAPI DocGlassfish v2 API24731Fri May 04 22:30:28 BST 2007com.sun.enterprise.jbi.serviceengine.util.soap

MessageExchangeHelper

public class MessageExchangeHelper extends Object
This class helps in normalizing a SOAP message and denormalizing a normalized message into a SOAP Message
author
mu125243

Fields Summary
private static Logger
logger
private MessageExchange
messageExchange
private URL
wsdlLocation
private QName
serviceName
private String
endpointName
private List
handlers
private static ConcurrentHashMap
wsdlCache
private static String
WSDL11
Constructors Summary
public MessageExchangeHelper()
Creates a new instance of MessageExchangeHelper


           
      
        handlers = JBIHandlerFactory.getInstance().getHandlers();
    
Methods Summary
private EndpointMetaDatacreateEndpointMetaData(java.lang.String wsdlPath, javax.xml.namespace.QName serviceName, java.lang.String epName)

        EndpointMetaData emd = new EndpointMetaData(getWsdlDefinition(wsdlPath), 
                                                    serviceName, 
                                                    epName);
        emd.resolve();
        return emd;
    
public javax.xml.soap.SOAPMessagedenormalizeMessage(boolean inFlag)

        validateMessageExchange();
        NormalizedMessage normalizedMsg = null;
        
        if(inFlag) {
            if(isInOutMessageExchange()) {
                InOut inOutExchange = (InOut)messageExchange;
                normalizedMsg = inOutExchange.getInMessage();
                
            } else {
                InOnly inOnlyExchange = (InOnly)messageExchange;
                normalizedMsg = inOnlyExchange.getInMessage();
            }
        } else {
            // assumed that it's a inout message
            normalizedMsg = (messageExchange.getFault()!=null)? 
                    messageExchange.getFault() : ((InOut)messageExchange).getOutMessage();
        //create inonly or inout message exchange based on the instance
        }
        
        DefaultMessageExchangeTransport meTransport = 
                new DefaultMessageExchangeTransport(messageExchange);
        meTransport.setMessage(normalizedMsg);
        invokeHandlersForOutbound(meTransport);

        QName operationQName = messageExchange.getOperation();
        String pattern = messageExchange.getPattern().toString();
        
        Operation operation = new Operation(operationQName.getLocalPart(), pattern);
        // DeNormalize response msg to SOAP msg
        
        MessageDenormalizerImpl d = new MessageDenormalizerImpl();
        SOAPWrapper wrapper;
        if(messageExchange.getFault()!=null) {
            // Assuming soap binding does not wrap a fault message
            wrapper = d.denormalizeFaultMessage((Fault)normalizedMsg);
        } else {
            unWrapMessage(normalizedMsg, inFlag);
            wrapper = d.denormalizeMessage(normalizedMsg, operation, !inFlag);
        }
        SOAPMessage message = wrapper.getMessage();
        printSOAPMessage( "Denormalizing in ? "+ inFlag + "message :" , message) ;
        return message;
        
    
public voiddispatchMessage()

        if(messageExchange != null) {
            MessageSender messageSender = new MessageSender();
            messageSender.setMessageExchange(messageExchange);
            messageSender.send();
            Exception exception = messageSender.getException();
            if(exception != null)
                throw new ServiceEngineException(exception);
        }
    
private EndpointMetaDatagetEndPointMetaData(java.lang.String wsdlPath, javax.xml.namespace.QName serviceName, java.lang.String epName)
This is the client side WSDL cache. The Provider cache is stored in ServiceEngineEndpoint. Client caching can be disabled using a System property.

        String clientCache = System.getProperty(JBIConstants.CLIENT_CACHE);
        if("false".equalsIgnoreCase(clientCache)) {
            return createEndpointMetaData(wsdlPath, serviceName, epName);
        } else {
            EndpointMetaData emd = wsdlCache.get(wsdlPath);
            if(emd == null) {
                emd = createEndpointMetaData(wsdlPath, serviceName, epName);
                wsdlCache.put(wsdlPath, emd);
            }
            return emd;
        }
    
public MessageExchangegetMessageExchange()

        return messageExchange;
    
private OperationgetOperation(javax.xml.soap.SOAPMessage soapMessage, javax.xml.namespace.QName svcQName, java.lang.String opName)

        try {
            // Get operation name from the localpart of the first child
            // of <env:Body> in SOAP msg
            SOAPPart sp = soapMessage.getSOAPPart();
            SOAPEnvelope env = sp.getEnvelope();
            SOAPBody body = env.getBody();
             // first child of body is like <ns0:sayHello>
            org.w3c.dom.Node firstChild = body.getFirstChild();
            String namespacePrefix = firstChild.getPrefix();
            
            // Get WSDL operation QName. This is in the same namespace as the
            // service, declared in the <definitions> element in the WSDL file.
            String svcNamespace = svcQName.getNamespaceURI();
            
            // namespace URI for body content is the WSDL "types" namespace
            // as in the <schema> element in the WSDL file.
            String namespaceURI = null;
            if(namespacePrefix != null)
                namespaceURI = env.getNamespaceURI(namespacePrefix);
            else
                namespaceURI = svcNamespace;
            
            // Normalize Message
            Operation operation = new Operation(opName, "in-out");
            // TODO Does JAXRPC2.0 allow WSDL 2.0's uri or multipart styles ?
            operation.setStyle("rpc");
            operation.setInputNamespace(namespaceURI);
            operation.setOutputNamespace(namespaceURI);
            return operation;
            
        } catch(Exception e) {
            e.printStackTrace();
            
            throw new ServiceEngineException(e.getMessage());
        }
    
private DefinitiongetWsdlDefinition(java.lang.String wsdl)

        javax.wsdl.factory.WSDLFactory mFactory = WSDLFactory.newInstance();
        javax.wsdl.xml.WSDLReader mReader = mFactory.newWSDLReader();
        return mReader.readWSDL(wsdl);
    
public voidhandleException(java.lang.Exception exception)

        try { 
            messageExchange.setStatus(ExchangeStatus.ERROR);
            if((messageExchange instanceof  InOut) || 
               (messageExchange instanceof RobustInOnly)){
                normalizeException(exception);
            }
            dispatchMessage();
        } catch(Exception e) {
           logger.log(Level.SEVERE, e.getMessage());
        }
    
public voidhandleResponse(javax.xml.soap.SOAPMessage response, boolean flag)

        try {
            if(messageExchange instanceof  InOut)  {
                normalizeMessage(response, flag);
            } else if((messageExchange instanceof InOnly ) ||
                (messageExchange instanceof RobustInOnly)) {
                messageExchange.setStatus(ExchangeStatus.DONE);
            }
            dispatchMessage();
        } catch(Exception e) {
           logger.log(Level.SEVERE, e.getMessage());
        }
    
public voidinitializeMessageExchange(com.sun.enterprise.deployment.ServiceRefPortInfo portInfo, boolean oneWay)
This will only be called during JAX-RPC invocation

        ServiceReferenceDescriptor serviceRef = portInfo.getServiceReference();
        QName serviceName = serviceRef.getServiceName();
        String endpointName = portInfo.hasWsdlPort()? 
                                        portInfo.getWsdlPort().getLocalPart() : 
                                        portInfo.getName();
        URL wsdlFileUrl = serviceRef.getWsdlFileUrl();
        initializeMessageExchange(wsdlFileUrl, serviceName, endpointName, oneWay);
    
public voidinitializeMessageExchange(java.net.URL wsdlLocation, javax.xml.namespace.QName service, java.lang.String endpointName, boolean oneWay)

        try {
            this.wsdlLocation = wsdlLocation;
            this.serviceName = service;
            this.endpointName = endpointName;
            DeliveryChannel channel =
                    JavaEEServiceEngineContext.getInstance(). getDeliveryChannel();
            // Create MessageExchange
            MessageExchangeFactory factory =
                    channel.createExchangeFactoryForService(serviceName);
            
            MessageExchange msgExchange = null;
            NormalizedMessage inMsg = null;
            
            if(oneWay) {
                InOnly inMessageExchange =  factory.createInOnlyExchange();
                inMsg = inMessageExchange.createMessage();
                inMessageExchange.setInMessage(inMsg);
                msgExchange = inMessageExchange;
            } else {
                InOut inOutMessageExchange =  factory.createInOutExchange();
                inMsg = inOutMessageExchange.createMessage();
                inOutMessageExchange.setInMessage(inMsg);
                msgExchange = inOutMessageExchange;
            }
            msgExchange.setService(serviceName);
            setMessageExchange(msgExchange);
        } catch(Exception e) {
            throw new ServiceEngineException(e);
        }
    
private voidinvokeHandlersForInbound(com.sun.enterprise.jbi.serviceengine.comm.MessageExchangeTransport meTransport)

        for (JBIHandler handler : handlers)
            try {
                handler.handleInbound(meTransport);
            } catch (Exception e) {
                logger.log(Level.SEVERE, e.getMessage(), e);
                throw new ServiceEngineException(e);
            }
    
private voidinvokeHandlersForOutbound(com.sun.enterprise.jbi.serviceengine.comm.MessageExchangeTransport meTransport)

        for (JBIHandler handler : handlers)
            try {
                handler.handleOutbound(meTransport);
            } catch (Exception e) {
                logger.log(Level.SEVERE, e.getMessage(), e);
                throw new ServiceEngineException(e);
            }
    
public booleanisInOutMessageExchange()

        return messageExchange instanceof InOut;
    
private booleanisWsdl11(Definition mDefinition)

       try
       {
           if (mDefinition != null) {
               String xmlns = mDefinition.getNamespace ("");
               if (xmlns.trim ().equals(WSDL11)) {
                   return true;
               }
           }
       }
       catch (Exception e)
       {
           throw new Wsdl11WrapperHelperException("Cannot get version", e);
       }
       return false;
    
private voidnormalizeAndWrapMessage(NormalizedMessage normalizedMsg, javax.xml.soap.SOAPMessage soapMessage, boolean server)

        try {
            String endpointName = null;
            QName serviceName = null;
            EndpointMetaData emd = null;
            ServiceEndpoint serviceEndpoint = messageExchange.getEndpoint();
            if(serviceEndpoint != null) {
                EndpointRegistry endpointRegistry = EndpointRegistry.getInstance();
                endpointName = serviceEndpoint.getEndpointName();
                serviceName = serviceEndpoint.getServiceName();
                ServiceEngineEndpoint serviceEngineEndpoint = endpointRegistry.get(
                serviceName, endpointName);
                if(serviceEngineEndpoint != null && server)
                    emd = serviceEngineEndpoint.getEndpointMetaData();
            }
            if(!server && wsdlLocation != null) {
                String wsdl = wsdlLocation.toURI().toString();
                serviceName = this.serviceName;
                endpointName = this.endpointName;
                emd  = getEndPointMetaData(wsdl, serviceName, endpointName);
            }

            Definition mDefinition = emd.getDefinition();
            Wsdl11WrapperHelper helper = new Wsdl11WrapperHelper(mDefinition);
            if(isWsdl11(mDefinition)) {
                //String operationName = messageExchange.getOperation().getLocalPart();
                String operationName = null;
                Operation operation = null;
                if (messageExchange.getOperation() == null) {
                    operationName = emd.getOperationName(soapMessage);
		    if (logger.isLoggable(Level.FINEST))
                        logger.finest("Operation Name is :" + operationName);
                    QName opQName = new QName(
                                    messageExchange.getService().getNamespaceURI(), 
                                    operationName);
                    messageExchange.setOperation(opQName);
                    operation = getOperation(soapMessage, 
                                    serviceName, operationName);
                } else {
                    operationName = messageExchange.getOperation().getLocalPart();
                    operation = new Operation(operationName,
                                    messageExchange.getPattern().toString());
                }

                SOAPWrapper wrapper = new SOAPWrapper(soapMessage);
                MessageNormalizerImpl normalizer = new MessageNormalizerImpl();
                normalizer.normalizeMessage(wrapper, normalizedMsg, operation);
                Document wrappedDoc = null;
                Source source = normalizedMsg.getContent();
                boolean isProvider = messageExchange.getRole().equals(MessageExchange.Role.PROVIDER);
                wrappedDoc = helper.wrapMessage(source, serviceName, endpointName, operationName,!isProvider);

                normalizedMsg.setContent(new DOMSource(wrappedDoc));
             }
        }catch(Exception e) {
            e.printStackTrace();
        }        
        
    
public voidnormalizeException(java.lang.Exception exception)

        if(exception != null) {
            try {
                MessageDenormalizerImpl d = new MessageDenormalizerImpl();
                SOAPWrapper soapWrapper = d.denormalizeMessage(exception);
                normalizeMessage(soapWrapper.getMessage(), false);
                
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    
public voidnormalizeMessage(javax.xml.soap.SOAPMessage soapMessage, boolean inFlag)

        validateMessageExchange();
        if(soapMessage != null) {
            
            
            printSOAPMessage( "normalizing in ? "+ inFlag + "message :" , soapMessage) ;
            NormalizedMessage normalizedMsg = null;
            try {
                
                boolean isFault = (soapMessage.getSOAPBody().getFault() != null);
                normalizedMsg = 
                        (isFault)? messageExchange.createFault() : messageExchange.createMessage();
                
                //soapMessage.writeTo(System.out);
                if(isFault) {
                    // Assuming soap binding does not unwrap a fault message
                    SOAPWrapper wrapper = new SOAPWrapper(soapMessage);
                    MessageNormalizerImpl normalizer = new MessageNormalizerImpl();
                    normalizer.normalizeFaultMessage(wrapper, normalizedMsg);
                } else {
                    //normalizer.normalizeMessage(wrapper, normalizedMsg, operation);
                    normalizeAndWrapMessage(normalizedMsg, soapMessage, !inFlag);
                }
                
                if(isFault)
                    messageExchange.setFault((javax.jbi.messaging.Fault)normalizedMsg);
                else if(inFlag) {
                    if(isInOutMessageExchange()) {
                        ((InOut)messageExchange).setInMessage(normalizedMsg);
                    } else {
                        ((InOnly)messageExchange).setInMessage(normalizedMsg);
                    }
                } else // inout assumed.
                    ((InOut)messageExchange).setOutMessage(normalizedMsg);
                DefaultMessageExchangeTransport meTransport = 
                        new DefaultMessageExchangeTransport(messageExchange);
                meTransport.setMessage(normalizedMsg);
                invokeHandlersForInbound(meTransport);
            } catch(Exception e) {
                e.printStackTrace();
            }
            
        }
        
    
protected voidprintSOAPContent(java.lang.String message, NormalizedMessage normalizedMessage)

        if(logger.isLoggable(Level.FINE)) {
            if(normalizedMessage != null) {
                javax.xml.transform.Source source = normalizedMessage.getContent() ;
                if(source != null) {
                    try {
                        javax.xml.transform.Transformer transformer = javax.xml.transform.TransformerFactory.newInstance().newTransformer();
                        System.out.print(message);
                        javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(System.out);
                        transformer.transform(source, result);
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                }
                
            }
        }
    
protected voidprintSOAPMessage(java.lang.String message, javax.xml.soap.SOAPMessage soapMessage)

        try {
            if(logger.isLoggable(Level.FINE)) {
                System.out.print(message);
                soapMessage.writeTo(System.out);
            }
        }catch(Exception e) {
            System.out.println(e.getMessage());
        }
    
public voidsetMessageExchange(MessageExchange messageExchange)

        this.messageExchange = messageExchange;
    
private voidunWrapMessage(NormalizedMessage normalizedMsg, boolean server)

        try {
            String endpointName = null;
            QName serviceName = null;
            EndpointMetaData emd = null;

            ServiceEndpoint serviceEndpoint = messageExchange.getEndpoint();
            if(serviceEndpoint != null) {
                EndpointRegistry endpointRegistry = EndpointRegistry.getInstance();
                endpointName = serviceEndpoint.getEndpointName();
                serviceName = serviceEndpoint.getServiceName();
                ServiceEngineEndpoint serviceEngineEndpoint = endpointRegistry.get(
                        serviceName, endpointName);
                if(serviceEngineEndpoint != null && server)
                    emd = serviceEngineEndpoint.getEndpointMetaData();
            }
            if(!server && wsdlLocation != null) {
                String wsdl = wsdlLocation.toURI().toString();
                serviceName = this.serviceName;
                endpointName = this.endpointName;
                emd  = getEndPointMetaData(wsdl, serviceName, endpointName);
            }

            // can emd be null?
            Definition mDefinition = emd.getDefinition();
            if(isWsdl11(mDefinition)) {
                Wsdl11WrapperHelper helper = new Wsdl11WrapperHelper(mDefinition);
                Source source = normalizedMsg.getContent();
                String operationName = messageExchange.getOperation().getLocalPart();
                boolean isProvider = messageExchange.getRole().equals(MessageExchange.Role.PROVIDER);
                Document unwrappedDoc = helper.unwrapMessage(source, 
                                                            serviceName,
                                                            endpointName,
                                                            operationName,
                                                            isProvider);
                normalizedMsg.setContent(new DOMSource(unwrappedDoc));
            }
        }catch(Exception e) {
            e.printStackTrace();
        }        
    
private voidvalidateMessageExchange()

        if(messageExchange == null)
            throw new ServiceEngineException("MessageExchange not set, use setMessageExchange()");