Example usage for javax.xml.bind JAXBElement JAXBElement

List of usage examples for javax.xml.bind JAXBElement JAXBElement

Introduction

In this page you can find the example usage for javax.xml.bind JAXBElement JAXBElement.

Prototype

public JAXBElement(QName name, Class<T> declaredType, T value) 

Source Link

Document

Construct an xml element instance.

Usage

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.DocLitWrappedMethodMarshaller.java

public Message marshalResponse(Object returnObject, Object[] signatureArgs, OperationDescription operationDesc,
        Protocol protocol) throws WebServiceException {

    EndpointInterfaceDescription ed = operationDesc.getEndpointInterfaceDescription();
    EndpointDescription endpointDesc = ed.getEndpointDescription();
    MarshalServiceRuntimeDescription marshalDesc = MethodMarshallerUtils.getMarshalDesc(endpointDesc);
    TreeSet<String> packages = marshalDesc.getPackages();
    String packagesKey = marshalDesc.getPackagesKey();

    // We want to respond with the same protocol as the request,
    // It the protocol is null, then use the Protocol defined by the binding
    if (protocol == null) {
        protocol = Protocol.getProtocolForBinding(endpointDesc.getBindingType());
    }/*from w w  w  .  jav  a2s .co  m*/

    // Note all exceptions are caught and rethrown with a WebServiceException
    try {
        // Sample Document message
        // ..
        // <soapenv:body>
        //    <m:operationResponse ... >
        //       <param>hello</param>
        //    </m:operationResponse>
        // </soapenv:body>
        //
        // Important points.
        //   1) There is no operation element in the message
        //   2) The data blocks are located underneath the body element. 
        //   3) The name of the data block (m:operationResponse) is defined by the schema.
        //      It matches the operation name + "Response", and it has a corresponding JAXB element.
        //      This element is called the wrapper element
        //   4) The parameters are (param) are child elements of the wrapper element.

        // Get the operation information
        ParameterDescription[] pds = operationDesc.getParameterDescriptions();

        // Create the message 
        MessageFactory mf = marshalDesc.getMessageFactory();
        Message m = mf.create(protocol);

        // In usage=WRAPPED, there will be a single block in the body.
        // The signatureArguments represent the child elements of that block
        // The first step is to convert the signature arguments into a list
        // of parameter values
        List<PDElement> pdeList = MethodMarshallerUtils.getPDElements(marshalDesc, pds, signatureArgs, false, // output
                true, false);

        String wrapperName = marshalDesc.getResponseWrapperClassName(operationDesc);
        Class cls = loadClass(wrapperName, endpointDesc);
        JAXBWrapperTool wrapperTool = new JAXBWrapperToolImpl();
        Object object = null;

        // Add the return object to the nameList and objectList
        Class returnType = operationDesc.getResultActualType();

        // Now we want to create a single JAXB element that contains the 
        // ParameterValues.  We will use the wrapper tool to do this.
        // Create the inputs to the wrapper tool
        if (pdeList.size() == 0) {
            if (returnType == void.class) {
                // Use the short-cut for void return
                object = wrapperTool.wrap(cls, (String) null, null, null, null);
            } else {
                // Use the short-cut for a single return
                String childName = operationDesc.getResultName();
                object = wrapperTool.wrap(cls, childName, returnObject, returnType,
                        marshalDesc.getPropertyDescriptorMap(cls).get(childName));
            }
        } else {

            // Now we want to create a single JAXB element that contains the 
            // ParameterValues.  We will use the wrapper tool to do this.
            // Create the inputs to the wrapper tool
            ArrayList<String> nameList = new ArrayList<String>();
            Map<String, Object> objectList = new HashMap<String, Object>();
            Map<String, Class> declaredClassMap = new HashMap<String, Class>();

            for (PDElement pde : pdeList) {
                String name = pde.getParam().getParameterName();

                // The object list contains type rendered objects
                Object value = pde.getElement().getTypeValue();
                Class dclClass = pde.getParam().getParameterActualType();

                nameList.add(name);
                objectList.put(name, value);
                declaredClassMap.put(name, dclClass);
            }

            // Add the return type
            if (returnType != void.class) {
                String name = operationDesc.getResultName();
                nameList.add(name);
                objectList.put(name, returnObject);
                declaredClassMap.put(name, returnType);
            }

            object = wrapperTool.wrap(cls, nameList, objectList, declaredClassMap,
                    marshalDesc.getPropertyDescriptorMap(cls));
        }

        QName wrapperQName = new QName(operationDesc.getResponseWrapperTargetNamespace(),
                operationDesc.getResponseWrapperLocalName());

        // Make sure object can be rendered as an element
        if (!marshalDesc.getAnnotationDesc(cls).hasXmlRootElement()) {
            object = new JAXBElement(wrapperQName, cls, object);
        }

        // Enable SWA for nested SwaRef attachments
        if (operationDesc.hasResponseSwaRefAttachments()) {
            m.setDoingSWA(true);
        }

        // Put the object into the message
        JAXBBlockFactory factory = (JAXBBlockFactory) FactoryRegistry.getFactory(JAXBBlockFactory.class);
        JAXBBlockContext blockContext = new JAXBBlockContext(packages, packagesKey);
        blockContext.setWebServiceNamespace(ed.getTargetNamespace());
        Block block = factory.createFrom(object, blockContext, wrapperQName);
        m.setBodyBlock(block);

        return m;
    } catch (Exception e) {
        throw ExceptionFactory.makeWebServiceException(e);
    }
}

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.DocLitWrappedMethodMarshaller.java

public Message marshalRequest(Object[] signatureArguments, OperationDescription operationDesc,
        Map<String, Object> requestContext) throws WebServiceException {

    EndpointInterfaceDescription ed = operationDesc.getEndpointInterfaceDescription();
    EndpointDescription endpointDesc = ed.getEndpointDescription();
    Protocol protocol = Protocol.getProtocolForBinding(endpointDesc.getClientBindingID());
    MarshalServiceRuntimeDescription marshalDesc = MethodMarshallerUtils.getMarshalDesc(endpointDesc);
    TreeSet<String> packages = marshalDesc.getPackages();
    String packagesKey = marshalDesc.getPackagesKey();

    // Note all exceptions are caught and rethrown with a WebServiceException
    try {//  w  w  w  .j  a  v a 2  s.  c  o m
        // Sample Document message
        // ..
        // <soapenv:body>
        //    <m:operation>
        //      <param>hello</param>
        //    </m:operation>
        // </soapenv:body>
        //
        // Important points.
        //   1) There is no operation element under the body.
        //   2) The data blocks are located underneath the body.  
        //   3) The name of the data block (m:operation) is defined by the schema and match the name of the operation.
        //      This is called the wrapper element.  The wrapper element has a corresponding JAXB element pojo.
        //   4) The parameters (m:param) are child elements of the wrapper element.

        // Get the operation information
        ParameterDescription[] pds = operationDesc.getParameterDescriptions();

        // Create the message 
        MessageFactory mf = marshalDesc.getMessageFactory();
        Message m = mf.create(protocol);

        // In usage=WRAPPED, there will be a single block in the body.
        // The signatureArguments represent the child elements of that block
        // The first step is to convert the signature arguments into list
        // of parameter values
        List<PDElement> pvList = MethodMarshallerUtils.getPDElements(marshalDesc, pds, signatureArguments, true, // input
                true, false);

        String wrapperName = marshalDesc.getRequestWrapperClassName(operationDesc);
        Class cls = loadClass(wrapperName, endpointDesc);
        JAXBWrapperTool wrapperTool = new JAXBWrapperToolImpl();
        Object object = null;

        // Now we want to create a single JAXB element that contains the 
        // ParameterValues.  We will use the wrapper tool to do this.
        // Create the inputs to the wrapper tool
        if (pvList.size() == 0) {
            // Use the short-cut for 0 children
            object = wrapperTool.wrap(cls, (String) null, null, null, null);
        } else if (pvList.size() == 1) {
            // Use the short-cut for 1 child
            PDElement pde = pvList.get(0);
            String childName = pde.getParam().getParameterName();
            object = wrapperTool.wrap(cls, childName, pde.getElement().getTypeValue(),
                    pde.getParam().getParameterActualType(),
                    marshalDesc.getPropertyDescriptorMap(cls).get(childName));

        } else {
            ArrayList<String> nameList = new ArrayList<String>();
            Map<String, Object> objectList = new HashMap<String, Object>();
            Map<String, Class> declaredClassMap = new HashMap<String, Class>();

            for (PDElement pv : pvList) {
                String name = pv.getParam().getParameterName();

                // The object list contains type rendered objects
                Object value = pv.getElement().getTypeValue();
                Class dclClass = pv.getParam().getParameterActualType();
                nameList.add(name);
                objectList.put(name, value);
                declaredClassMap.put(name, dclClass);
            }

            object = wrapperTool.wrap(cls, nameList, objectList, declaredClassMap,
                    marshalDesc.getPropertyDescriptorMap(cls));
        }

        QName wrapperQName = new QName(operationDesc.getRequestWrapperTargetNamespace(),
                operationDesc.getRequestWrapperLocalName());

        // Make sure object can be rendered as an element
        if (!marshalDesc.getAnnotationDesc(cls).hasXmlRootElement()) {
            object = new JAXBElement(wrapperQName, cls, object);
        }

        // Enable SWA for nested SwaRef attachments
        if (operationDesc.hasRequestSwaRefAttachments()) {
            m.setDoingSWA(true);
        }

        // Put the object into the message
        JAXBBlockFactory factory = (JAXBBlockFactory) FactoryRegistry.getFactory(JAXBBlockFactory.class);
        JAXBBlockContext blockContext = new JAXBBlockContext(packages, packagesKey);
        blockContext.setWebServiceNamespace(ed.getTargetNamespace());
        Block block = factory.createFrom(object, blockContext, wrapperQName);
        m.setBodyBlock(block);

        return m;
    } catch (Exception e) {
        throw ExceptionFactory.makeWebServiceException(e);
    }
}

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.DocLitWrappedMinimalMethodMarshaller.java

public Message marshalResponse(Object returnObject, Object[] signatureArgs, OperationDescription operationDesc,
        Protocol protocol) throws WebServiceException {

    if (log.isDebugEnabled()) {
        log.debug("enter marshalResponse operationDesc = " + operationDesc.getName());
    }// w  w  w.ja va  2s .  co m

    EndpointInterfaceDescription ed = operationDesc.getEndpointInterfaceDescription();
    EndpointDescription endpointDesc = ed.getEndpointDescription();
    // We want to respond with the same protocol as the request,
    // It the protocol is null, then use the Protocol defined by the binding
    if (protocol == null) {
        protocol = Protocol.getProtocolForBinding(endpointDesc.getBindingType());
    }

    // Note all exceptions are caught and rethrown with a WebServiceException
    try {
        // Sample Document message
        // ..
        // <soapenv:body>
        //    <m:operationResponse ... >
        //       <param>hello</param>
        //    </m:operationResponse>
        // </soapenv:body>
        //
        // Important points.
        //   1) There is no operation element in the message
        //   2) The data blocks are located underneath the body element. 
        //   3) The name of the data block (m:operationResponse) is defined by the schema.
        //      It matches the operation name + "Response", and it has a corresponding JAXB element.
        //      This element is called the wrapper element
        //   4) The parameters are (param) are child elements of the wrapper element.
        //   5) For "minimal" the pojo bean representing the OperationResponse is missing.

        // Get the operation information
        ParameterDescription[] pds = operationDesc.getParameterDescriptions();
        MarshalServiceRuntimeDescription marshalDesc = MethodMarshallerUtils.getMarshalDesc(endpointDesc);
        TreeSet<String> packages = marshalDesc.getPackages();

        // Create the message 
        MessageFactory mf = (MessageFactory) FactoryRegistry.getFactory(MessageFactory.class);
        Message m = mf.create(protocol);

        // Indicate the style and wrapper element name.  This triggers the message to
        // put the data blocks underneath the operation element
        m.setStyle(Style.DOCUMENT);
        m.setIndirection(1);
        QName responseOp = getResponseWrapperQName(operationDesc);
        m.setOperationElement(responseOp);

        // Put the return object onto the message
        Class returnType = operationDesc.getResultActualType();
        String returnNS = null;
        String returnLocalPart = null;
        if (operationDesc.isResultHeader()) {
            returnNS = operationDesc.getResultTargetNamespace();
            returnLocalPart = operationDesc.getResultName();
        } else {
            returnNS = operationDesc.getResultTargetNamespace();
            returnLocalPart = operationDesc.getResultPartName();
        }

        if (returnType != void.class) {
            Element returnElement = null;
            QName returnQName = new QName(returnNS, returnLocalPart);
            if (representAsOccurrence(returnObject, returnType)) {
                if (log.isDebugEnabled()) {
                    log.debug("Return element isListOrArray");
                }
                OccurrenceArray occurrenceArray = new OccurrenceArray(returnObject);
                JAXBElement jaxb = new JAXBElement(returnQName, returnType, occurrenceArray);
                returnElement = new Element(jaxb, returnQName);
            } else if (marshalDesc.getAnnotationDesc(returnType).hasXmlRootElement()) {
                returnElement = new Element(returnObject, returnQName);
            } else {
                returnElement = new Element(returnObject, returnQName, returnType);
            }
            MethodMarshallerUtils.toMessage(returnElement, returnType, operationDesc.isListType(), marshalDesc,
                    m, returnType, // force marshal by type
                    operationDesc.isResultHeader());
        }

        // Convert the holder objects into a list of JAXB objects for marshalling
        List<PDElement> pdeList = MethodMarshallerUtils.getPDElements(marshalDesc, pds, signatureArgs, false, // output
                true, // doc/lit wrapped
                false); // not rpc

        // We want to use "by Java Type" marshalling for 
        // all objects
        for (int i = 0; i < pdeList.size(); i++) {

            PDElement pde = pdeList.get(i);

            // If the actual value is an array or list
            // this should be modeled as an 
            // occurrence of elements
            pde = processOccurrence(pde);
            pdeList.set(i, pde);

            // Set by java type marshaling
            ParameterDescription pd = pde.getParam();
            Class type = pd.getParameterActualType();
            pde.setByJavaTypeClass(type);
        }

        // TODO Should we check for null output body values?  Should we check for null output header values ?
        // Put values onto the message
        MethodMarshallerUtils.toMessage(pdeList, m, packages, null);

        // Enable SWA for nested SwaRef attachments
        if (operationDesc.hasResponseSwaRefAttachments()) {
            m.setDoingSWA(true);
        }

        if (log.isDebugEnabled()) {
            log.debug("exit marshalResponse");
        }
        return m;
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("fail marshalResponse e= " + e);
            log.debug(" " + JavaUtils.stackToString(e));
        }
        throw ExceptionFactory.makeWebServiceException(e);
    }
}

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.DocLitWrappedMinimalMethodMarshaller.java

/**
 * If the PDElement represents an array or List,
 * a new PDElement is returned that models the 
 * the array or List as a series of elements.
 * @param pde//from ww  w .j  av  a 2  s.  c o  m
 * @return new PDElement or same PDElement
 */
private static PDElement processOccurrence(PDElement pde) {
    // All arrays and lists should be marshaled as
    // separate (occurrence) elements
    Element element = pde.getElement();
    if (element != null) {
        Object elementValue = element.getElementValue();
        if (elementValue instanceof JAXBElement) {
            JAXBElement jaxb = (JAXBElement) elementValue;
            Object value = jaxb.getValue();
            if (representAsOccurrence(value, jaxb.getDeclaredType())) {
                if (log.isDebugEnabled()) {
                    log.debug("Build OccurrentArray");
                }
                OccurrenceArray occurrenceArray = new OccurrenceArray(value);
                JAXBElement newJAXBElement = new JAXBElement(jaxb.getName(), jaxb.getDeclaredType(),
                        occurrenceArray);
                element = new Element(newJAXBElement, jaxb.getName());
                pde = new PDElement(pde.getParam(), element, null);
            }
        }
    }
    return pde;
}

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.DocLitWrappedPlusMethodMarshaller.java

public Message marshalResponse(Object returnObject, Object[] signatureArgs, OperationDescription operationDesc,
        Protocol protocol) throws WebServiceException {
    if (log.isDebugEnabled()) {
        log.debug("Calling DocLitWrapperPlusMethodMarshaller.marshalResponse");
        log.debug(/*from w  ww  .  ja va2 s.c o  m*/
                "  The DocLitWrapped Plus marshaller is used when the web service method deviates from the normal doc/lit rules.");
    }
    EndpointInterfaceDescription ed = operationDesc.getEndpointInterfaceDescription();
    EndpointDescription endpointDesc = ed.getEndpointDescription();
    // We want to respond with the same protocol as the request,
    // It the protocol is null, then use the Protocol defined by the binding
    if (protocol == null) {
        protocol = Protocol.getProtocolForBinding(endpointDesc.getBindingType());
    }

    // Note all exceptions are caught and rethrown with a WebServiceException
    try {
        // Sample Document message
        // ..
        // <soapenv:body>
        //    <m:operationResponse ... >
        //       <param>hello</param>
        //    </m:operationResponse>
        // </soapenv:body>
        //
        // Important points.
        //   1) There is no operation element in the message
        //   2) The data blocks are located underneath the body element. 
        //   3) The name of the data block (m:operationResponse) is defined by the schema.
        //      It matches the operation name + "Response", and it has a corresponding JAXB element.
        //      This element is called the wrapper element
        //   4) The parameters are (param) are child elements of the wrapper element.

        // Get the operation information
        ParameterDescription[] pds = operationDesc.getParameterDescriptions();
        MarshalServiceRuntimeDescription marshalDesc = MethodMarshallerUtils.getMarshalDesc(endpointDesc);
        TreeSet<String> packages = marshalDesc.getPackages();
        String packagesKey = marshalDesc.getPackagesKey();

        // Create the message 
        MessageFactory mf = (MessageFactory) FactoryRegistry.getFactory(MessageFactory.class);
        Message m = mf.create(protocol);

        // In usage=WRAPPED, there will be a single block in the body.
        // The signatureArguments represent the child elements of that block
        // The first step is to convert the signature arguments into a list
        // of parameter values
        List<PDElement> pdeList = MethodMarshallerUtils.getPDElements(marshalDesc, pds, signatureArgs, false, // output
                true, false);

        // Now we want to create a single JAXB element that contains the 
        // parameter values.  We will use the wrapper tool to do this.
        // Create the inputs to the wrapper tool
        ArrayList<String> nameList = new ArrayList<String>();
        Map<String, Object> objectList = new HashMap<String, Object>();
        Map<String, Class> declaredClassMap = new HashMap<String, Class>();
        List<PDElement> headerPDEList = new ArrayList<PDElement>();

        Iterator<PDElement> it = pdeList.iterator();
        while (it.hasNext()) {
            PDElement pde = it.next();
            String name = pde.getParam().getParameterName();
            if (!pde.getParam().isHeader()) {
                // Normal case
                // The object list contains type rendered objects
                Object value = pde.getElement().getTypeValue();
                Class dclClass = pde.getParam().getParameterActualType();
                nameList.add(name);
                objectList.put(name, value);
                declaredClassMap.put(name, dclClass);
            } else {
                // Header Case:
                // Remove the header from the list, it will
                // not be placed in the wrapper
                it.remove();
                headerPDEList.add(pde);
            }
        }

        Class returnType = operationDesc.getResultActualType();
        if (!operationDesc.isResultHeader()) {
            // Normal (Body Result): Add the return object to the nameList and objectList

            if (returnType != void.class) {
                String name = operationDesc.getResultName();
                Class dclClass = operationDesc.getResultActualType();
                nameList.add(name);
                objectList.put(name, returnObject);
                declaredClassMap.put(name, dclClass);
            }
        } else {
            // Header Result:
            // Put the return object onto the message
            if (returnType != void.class) {
                Element returnElement = null;
                QName returnQName = new QName(operationDesc.getResultTargetNamespace(),
                        operationDesc.getResultName());
                if (marshalDesc.getAnnotationDesc(returnType).hasXmlRootElement()) {
                    returnElement = new Element(returnObject, returnQName);
                } else {
                    returnElement = new Element(returnObject, returnQName, returnType);
                }

                Class byJavaType = MethodMarshallerUtils.isNotJAXBRootElement(returnType, marshalDesc)
                        ? returnType
                        : null;

                MethodMarshallerUtils.toMessage(returnElement, returnType, operationDesc.isListType(),
                        marshalDesc, m, byJavaType, true);
            }
        }

        // Now create the single JAXB element
        String wrapperName = marshalDesc.getResponseWrapperClassName(operationDesc);
        Class cls = loadClass(wrapperName, endpointDesc);

        JAXBWrapperTool wrapperTool = new JAXBWrapperToolImpl();
        Object object = wrapperTool.wrap(cls, nameList, objectList, declaredClassMap,
                marshalDesc.getPropertyDescriptorMap(cls));

        QName wrapperQName = new QName(operationDesc.getResponseWrapperTargetNamespace(),
                operationDesc.getResponseWrapperLocalName());

        // Make sure object can be rendered as an element
        if (!marshalDesc.getAnnotationDesc(cls).hasXmlRootElement()) {
            object = new JAXBElement(wrapperQName, cls, object);
        }

        // Put the object into the message
        JAXBBlockFactory factory = (JAXBBlockFactory) FactoryRegistry.getFactory(JAXBBlockFactory.class);
        JAXBBlockContext blockContext = new JAXBBlockContext(packages, packagesKey);
        blockContext.setWebServiceNamespace(ed.getTargetNamespace());
        Block block = factory.createFrom(object, blockContext, wrapperQName); // The factory will get the qname from the value
        m.setBodyBlock(block);

        //  Now place the headers in the message
        if (headerPDEList.size() > 0) {

            // Use "by java type" marshalling if necessary
            for (PDElement pde : headerPDEList) {
                Class actualType = pde.getParam().getParameterActualType();
                if (MethodMarshallerUtils.isNotJAXBRootElement(actualType, marshalDesc)) {
                    pde.setByJavaTypeClass(actualType);
                }
            }
            MethodMarshallerUtils.toMessage(headerPDEList, m, packages, null);
        }

        // Enable SWA for nested SwaRef attachments
        if (operationDesc.hasResponseSwaRefAttachments()) {
            m.setDoingSWA(true);
        }

        return m;
    } catch (Exception e) {
        throw ExceptionFactory.makeWebServiceException(e);
    }
}

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.DocLitWrappedPlusMethodMarshaller.java

public Message marshalRequest(Object[] signatureArguments, OperationDescription operationDesc,
        Map<String, Object> requestContext) throws WebServiceException {
    if (log.isDebugEnabled()) {
        log.debug("Calling DocLitWrapperPlusMethodMarshaller.marshalRequest");
        log.debug(/*from   w ww  . j  a v  a  2 s.  c o m*/
                "  The DocLitWrapped Plus marshaller is used when the web service method deviates from the normal doc/lit rules.");
    }
    EndpointInterfaceDescription ed = operationDesc.getEndpointInterfaceDescription();
    EndpointDescription endpointDesc = ed.getEndpointDescription();
    Protocol protocol = Protocol.getProtocolForBinding(endpointDesc.getClientBindingID());
    MarshalServiceRuntimeDescription marshalDesc = MethodMarshallerUtils.getMarshalDesc(endpointDesc);
    TreeSet<String> packages = marshalDesc.getPackages();
    String packagesKey = marshalDesc.getPackagesKey();

    // Note all exceptions are caught and rethrown with a WebServiceException
    try {
        // Sample Document message
        // ..
        // <soapenv:body>
        //    <m:operation>
        //      <param>hello</param>
        //    </m:operation>
        // </soapenv:body>
        //
        // Important points.
        //   1) There is no operation element under the body.
        //   2) The data blocks are located underneath the body.  
        //   3) The name of the data block (m:operation) is defined by the schema and match the name of the operation.
        //      This is called the wrapper element.  The wrapper element has a corresponding JAXB element pojo.
        //   4) The parameters (m:param) are child elements of the wrapper element.

        // Get the operation information
        ParameterDescription[] pds = operationDesc.getParameterDescriptions();

        // Create the message 
        MessageFactory mf = (MessageFactory) FactoryRegistry.getFactory(MessageFactory.class);
        Message m = mf.create(protocol);

        // In usage=WRAPPED, there will be a single block in the body.
        // The signatureArguments represent the child elements of that block
        // The first step is to convert the signature arguments into list
        // of parameter values
        List<PDElement> pdeList = MethodMarshallerUtils.getPDElements(marshalDesc, pds, signatureArguments,
                true, // input
                true, false);

        // Now we want to create a single JAXB element that contains the 
        // ParameterValues.  We will use the wrapper tool to do this.
        // Create the inputs to the wrapper tool
        ArrayList<String> nameList = new ArrayList<String>();
        Map<String, Object> objectList = new HashMap<String, Object>();
        Map<String, Class> declardClassMap = new HashMap<String, Class>();
        List<PDElement> headerPDEList = new ArrayList<PDElement>();

        Iterator<PDElement> it = pdeList.iterator();
        while (it.hasNext()) {
            PDElement pde = it.next();
            String name = pde.getParam().getParameterName();
            if (!pde.getParam().isHeader()) {
                // Normal case:
                // The object list contains type rendered objects
                Object value = pde.getElement().getTypeValue();
                Class dclClass = pde.getParam().getParameterActualType();
                nameList.add(name);
                objectList.put(name, value);
                declardClassMap.put(name, dclClass);
            } else {
                // Header Case:
                // Remove the header from the list, it will
                // not be placed in the wrapper
                it.remove();
                headerPDEList.add(pde);
            }
        }

        // Now create the single JAXB element 
        String wrapperName = marshalDesc.getRequestWrapperClassName(operationDesc);
        Class cls = loadClass(wrapperName, endpointDesc);

        JAXBWrapperTool wrapperTool = new JAXBWrapperToolImpl();
        Object object = wrapperTool.wrap(cls, nameList, objectList, declardClassMap,
                marshalDesc.getPropertyDescriptorMap(cls));

        QName wrapperQName = new QName(operationDesc.getRequestWrapperTargetNamespace(),
                operationDesc.getRequestWrapperLocalName());

        // Make sure object can be rendered as an element
        if (!marshalDesc.getAnnotationDesc(cls).hasXmlRootElement()) {
            object = new JAXBElement(wrapperQName, cls, object);
        }

        // Put the object into the message
        JAXBBlockFactory factory = (JAXBBlockFactory) FactoryRegistry.getFactory(JAXBBlockFactory.class);
        JAXBBlockContext blockContext = new JAXBBlockContext(packages, packagesKey);
        blockContext.setWebServiceNamespace(ed.getTargetNamespace());
        Block block = factory.createFrom(object, blockContext, wrapperQName); // The factory will get the qname from the value
        m.setBodyBlock(block);

        // Now place the headers in the message
        if (headerPDEList.size() > 0) {

            // Use "by java type" marshalling if necessary
            for (PDElement pde : headerPDEList) {
                Class actualType = pde.getParam().getParameterActualType();
                if (MethodMarshallerUtils.isNotJAXBRootElement(actualType, marshalDesc)) {
                    pde.setByJavaTypeClass(actualType);
                }
            }

            MethodMarshallerUtils.toMessage(headerPDEList, m, packages, requestContext);
        }

        // Enable SWA for nested SwaRef attachments
        if (operationDesc.hasRequestSwaRefAttachments()) {
            m.setDoingSWA(true);
        }

        return m;
    } catch (Exception e) {
        throw ExceptionFactory.makeWebServiceException(e);
    }
}

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.MethodMarshallerUtils.java

/**
 * Marshaling a fault is essentially the same for rpc/lit and doc/lit. This method is used by
 * all of the MethodMarshallers/*from ww  w  .  j  av a 2  s  .  c  om*/
 *
 * @param throwable     Throwable to marshal
 * @param operationDesc OperationDescription
 * @param packages      Packages needed to marshal the object
 * @param message       Message
 */
static void marshalFaultResponse(Throwable throwable, MarshalServiceRuntimeDescription marshalDesc,
        OperationDescription operationDesc, Message message) {
    // Get the root cause of the throwable object
    Throwable t = ClassUtils.getRootCause(throwable);
    if (log.isDebugEnabled()) {
        log.debug("Marshal Throwable =" + throwable.getClass().getName());
        log.debug("  rootCause =" + t.getClass().getName());
        log.debug("  exception=" + t.toString());
        log.debug("  stack=" + stackToString(t));
    }

    XMLFault xmlfault = null;

    try {

        // There are 5 different categories of exceptions.  
        // Each category has a little different marshaling code.
        // A) Service Exception that matches the JAX-WS 
        //    specification (chapter 2.5 of the spec)
        // B) Service Exception that matches the JAX-WS "legacy" 
        //    exception (chapter 3.7 of the spec)
        // C) SOAPFaultException
        // D) WebServiceException
        // E) Other runtime exceptions (i.e. NullPointerException)

        // Get the FaultDescriptor matching this Exception.
        // If FaultDescriptor is found, this is a JAX-B Service Exception.
        // If not found, this is a System Exception
        FaultDescription fd = operationDesc.resolveFaultByExceptionName(t.getClass().getCanonicalName());

        if (fd != null) {
            if (log.isErrorEnabled()) {
                log.debug("Marshal as a Service Exception");
            }
            // Create the JAXB Context
            JAXBBlockContext context = new JAXBBlockContext(marshalDesc.getPackages());

            // The exception is a Service Exception.  
            // It may be (A) JAX-WS compliant exception or 
            // (B) JAX-WS legacy exception

            // The faultBeanObject is a JAXB object that represents the data of the exception.
            // It is marshalled in the detail section of the soap fault.  
            // The faultBeanObject is obtained direction from the exception (A) or via 
            // the legacy exception rules (B).
            Object faultBeanObject = null;

            FaultBeanDesc faultBeanDesc = marshalDesc.getFaultBeanDesc(fd);
            String faultInfo = fd.getFaultInfo();
            if (faultInfo == null || faultInfo.length() == 0) {
                // Legacy Exception case
                faultBeanObject = LegacyExceptionUtil.createFaultBean(t, fd, marshalDesc);
            } else {
                // Normal case
                // Get the fault bean object.  
                Method getFaultInfo = t.getClass().getMethod("getFaultInfo", null);
                faultBeanObject = getFaultInfo.invoke(t, null);
            }

            if (log.isErrorEnabled()) {
                log.debug("The faultBean type is" + faultBeanObject.getClass().getName());
            }

            // Use "by java type" marshalling if necessary
            if (faultBeanObject == t
                    || (context.getConstructionType() != JAXBUtils.CONSTRUCTION_TYPE.BY_CONTEXT_PATH
                            && isNotJAXBRootElement(faultBeanObject.getClass(), marshalDesc))) {
                context.setProcessType(faultBeanObject.getClass());
            }

            QName faultBeanQName = new QName(faultBeanDesc.getFaultBeanNamespace(),
                    faultBeanDesc.getFaultBeanLocalName());
            // Make sure the faultBeanObject can be marshalled as an element
            if (!marshalDesc.getAnnotationDesc(faultBeanObject.getClass()).hasXmlRootElement()) {
                faultBeanObject = new JAXBElement(faultBeanQName, faultBeanObject.getClass(), faultBeanObject);
            }

            // Create a detailblock representing the faultBeanObject
            Block[] detailBlocks = new Block[1];
            detailBlocks[0] = factory.createFrom(faultBeanObject, context, faultBeanQName);

            if (log.isDebugEnabled()) {
                log.debug("Create the xmlFault for the Service Exception");
            }
            // Get the fault text using algorithm defined in JAX-WS 10.2.2.3
            String text = t.getMessage();
            if (text == null || text.length() == 0) {
                text = t.toString();
            }
            // Now make a XMLFault containing the detailblock
            xmlfault = new XMLFault(null, new XMLFaultReason(text), detailBlocks);
        } else {
            xmlfault = createXMLFaultFromSystemException(t);
        }
    } catch (Throwable e) {
        // If an exception occurs while demarshalling an exception, 
        // then rinse and repeat with a system exception
        if (log.isDebugEnabled()) {
            log.debug("An exception (" + e + ") occurred while marshalling exception (" + t + ")");
        }
        WebServiceException wse = ExceptionFactory.makeWebServiceException(e);
        xmlfault = createXMLFaultFromSystemException(wse);
    }

    // Add the fault to the message
    message.setXMLFault(xmlfault);
}

From source file:org.apache.axis2.jaxws.utility.PropertyDescriptorPlus.java

/**
 * Set the object/*from   ww  w  .j a v  a  2  s.c  om*/
 *
 * @param targetBean
 * @param propValue
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws JAXBWrapperException
 */
public void set(Object targetBean, Object propValue, Class dclClass)
        throws InvocationTargetException, IllegalAccessException, JAXBWrapperException {

    Method writeMethod = null;
    try {
        // No set occurs if the value is null
        if (propValue == null) {
            return;
        }

        // There are 3 different types of setters that can occur.
        // 1) Normal Attomic Setter : setFoo(type)
        // 2) Indexed Array Setter : setFoo(type[])
        // 3) No Setter case if the property is a List<T>.

        writeMethod = descriptor.getWriteMethod();
        if (descriptor instanceof IndexedPropertyDescriptor) {
            // Set for indexed  T[]
            setIndexedArray(targetBean, propValue, writeMethod);
        } else if (writeMethod == null) {
            // Set for List<T>
            setList(targetBean, propValue);
        } else if (descriptor.getPropertyType() == JAXBElement.class) {
            if (propValue != null) {
                Class clazz = dclClass != null ? dclClass : propValue.getClass();
                JAXBElement element = new JAXBElement(xmlName, clazz, propValue);
                setAtomic(targetBean, element, writeMethod);
            }
        } else {
            // Normal case
            setAtomic(targetBean, propValue, writeMethod);
        }
    } catch (RuntimeException e) {

        if (DEBUG_ENABLED) {
            String propClass = propValue.getClass().getName();
            log.debug("An exception occurred while attempting to set a property on "
                    + targetBean.getClass().getName());
            log.debug("The setter method is " + writeMethod);
            log.debug("The class of the argument is :" + propClass);
            log.debug("The PropertyDescriptor is: " + this.toString());
            log.debug("The exception is: " + e);
        }
        throw e;
    }
}

From source file:org.apache.camel.converter.jaxb.JaxbDataFormat.java

@SuppressWarnings("unchecked")
void marshal(Exchange exchange, Object graph, OutputStream stream, Marshaller marshaller)
        throws XMLStreamException, JAXBException {

    Object e = graph;//from   w  w w .j a v  a  2 s .c  om
    if (partialClass != null && getPartNamespace() != null) {
        e = new JAXBElement(getPartNamespace(), partialClass, graph);
    }

    if (needFiltering(exchange)) {
        marshaller.marshal(e, createFilteringWriter(stream));
    } else {
        marshaller.marshal(e, stream);
    }
}

From source file:org.apache.cxf.systest.jaxrs.JAXRS20ClientServerBookTest.java

@Test
public void testEchoBookElement() throws Exception {
    BookStore store = JAXRSClientFactory.create("http://localhost:" + PORT, BookStore.class);
    JAXBElement<Book> element = store
            .echoBookElement(new JAXBElement<Book>(new QName("", "Book"), Book.class, new Book("CXF", 123L)));
    Book book = element.getValue();
    assertEquals(123L, book.getId());/*from   ww  w  .ja  v  a  2 s . c  o  m*/
    assertEquals("CXF", book.getName());

    Book book2 = store.echoBookElement(new Book("CXF3", 128L));
    assertEquals(130L, book2.getId());
    assertEquals("CXF3", book2.getName());
}