Best Citrus code snippet using com.consol.citrus.ws.server.WebServiceEndpoint.addSoapFault
Source:WebServiceEndpoint.java  
...97            SoapMessage response = (SoapMessage) messageContext.getResponse();98            99            //add soap fault or normal soap body to response100            if (replyMessage instanceof SoapFault) {101                addSoapFault(response, (SoapFault) replyMessage);102            } else {103                addSoapBody(response, replyMessage);104            }105            addSoapAttachments(response, replyMessage);106            addSoapHeaders(response, replyMessage);107            addMimeHeaders(response, replyMessage);108        } else {109            if (log.isDebugEnabled()) {110                log.debug("No reply message from endpoint adapter '" + endpointAdapter + "'");111            }112            log.warn("No SOAP response for calling client");113        }114    }115    private void addSoapAttachments(MimeMessage response, Message replyMessage) {116        if (replyMessage instanceof com.consol.citrus.ws.message.SoapMessage) {117            List<SoapAttachment> soapAttachments = ((com.consol.citrus.ws.message.SoapMessage) replyMessage).getAttachments();118            soapAttachments.stream()119                    .filter(soapAttachment -> !soapAttachment.isMtomInline())120                    .forEach(soapAttachment -> {121                        String contentId = soapAttachment.getContentId();122                        if (!contentId.startsWith("<")) {123                            contentId = "<" + contentId + ">";124                        }125                        response.addAttachment(contentId, soapAttachment.getDataHandler());126                    });127        }128    }129    /**130     * If Http status code is set on reply message headers simulate Http error with status code.131     * No SOAP response is sent back in this case.132     * @param replyMessage133     * @return134     * @throws IOException 135     */136    private boolean simulateHttpStatusCode(Message replyMessage) throws IOException {137        if (replyMessage == null || CollectionUtils.isEmpty(replyMessage.getHeaders())) {138            return false;139        }140        141        for (Entry<String, Object> headerEntry : replyMessage.getHeaders().entrySet()) {142            if (headerEntry.getKey().equalsIgnoreCase(SoapMessageHeaders.HTTP_STATUS_CODE)) {143                WebServiceConnection connection = TransportContextHolder.getTransportContext().getConnection();144                145                int statusCode = Integer.valueOf(headerEntry.getValue().toString());146                if (connection instanceof HttpServletConnection) {147                    ((HttpServletConnection)connection).setFault(false);148                    ((HttpServletConnection)connection).getHttpServletResponse().setStatus(statusCode);149                    return true;150                } else {151                    log.warn("Unable to set custom Http status code on connection other than HttpServletConnection (" + connection.getClass().getName() + ")");152                }153            }154        }155        156        return false;157    }158    /**159     * Adds mime headers outside of SOAP envelope. Header entries that go to this header section 160     * must have internal http header prefix defined in {@link com.consol.citrus.ws.message.SoapMessageHeaders}.161     * @param response the soap response message.162     * @param replyMessage the internal reply message.163     */164    private void addMimeHeaders(SoapMessage response, Message replyMessage) {165        for (Entry<String, Object> headerEntry : replyMessage.getHeaders().entrySet()) {166            if (headerEntry.getKey().toLowerCase().startsWith(SoapMessageHeaders.HTTP_PREFIX)) {167                String headerName = headerEntry.getKey().substring(SoapMessageHeaders.HTTP_PREFIX.length());168                169                if (response instanceof SaajSoapMessage) {170                    SaajSoapMessage saajSoapMessage = (SaajSoapMessage) response;171                    MimeHeaders headers = saajSoapMessage.getSaajMessage().getMimeHeaders();172                    headers.setHeader(headerName, headerEntry.getValue().toString());173                } else if (response instanceof AxiomSoapMessage) {174                    log.warn("Unable to set mime message header '" + headerName + "' on AxiomSoapMessage - unsupported");175                } else {176                    log.warn("Unsupported SOAP message implementation - unable to set mime message header '" + headerName + "'");177                }178            }179        }180    }181    /**182     * Add message payload as SOAP body element to the SOAP response.183     * @param response184     * @param replyMessage185     */186    private void addSoapBody(SoapMessage response, Message replyMessage) throws TransformerException {187        if (!(replyMessage.getPayload() instanceof String) || 188                StringUtils.hasText(replyMessage.getPayload(String.class))) {189            Source responseSource = getPayloadAsSource(replyMessage.getPayload());190            191            TransformerFactory transformerFactory = TransformerFactory.newInstance();192            Transformer transformer = transformerFactory.newTransformer();193            194            transformer.transform(responseSource, response.getPayloadResult());195        }196    }197    198    /**199     * Translates message headers to SOAP headers in response.200     * @param response201     * @param replyMessage202     */203    private void addSoapHeaders(SoapMessage response, Message replyMessage) throws TransformerException {204        for (Entry<String, Object> headerEntry : replyMessage.getHeaders().entrySet()) {205            if (MessageHeaderUtils.isSpringInternalHeader(headerEntry.getKey()) ||206                    headerEntry.getKey().startsWith(DEFAULT_JMS_HEADER_PREFIX)) {207                continue;208            }209            if (headerEntry.getKey().equalsIgnoreCase(SoapMessageHeaders.SOAP_ACTION)) {210                response.setSoapAction(headerEntry.getValue().toString());211            } else if (!headerEntry.getKey().startsWith(MessageHeaders.PREFIX)) {212                SoapHeaderElement headerElement;213                if (QNameUtils.validateQName(headerEntry.getKey())) {214                    QName qname = QNameUtils.parseQNameString(headerEntry.getKey());215                    if (StringUtils.hasText(qname.getNamespaceURI())) {216                        headerElement = response.getSoapHeader().addHeaderElement(qname);217                    } else {218                        headerElement = response.getSoapHeader().addHeaderElement(getDefaultQName(headerEntry.getKey()));219                    }220                } else {221                    throw new SoapHeaderException("Failed to add SOAP header '" + headerEntry.getKey() + "', " +222                            "because of invalid QName");223                }224                headerElement.setText(headerEntry.getValue().toString());225            }226        }227        for (String headerData : replyMessage.getHeaderData()) {228            TransformerFactory transformerFactory = TransformerFactory.newInstance();229            Transformer transformer = transformerFactory.newTransformer();230            transformer.transform(new StringSource(headerData),231                    response.getSoapHeader().getResult());232        }233    }234    /**235     * Adds a SOAP fault to the SOAP response body. The SOAP fault is declared236     * as QName string in the response message's header (see {@link com.consol.citrus.ws.message.SoapMessageHeaders})237     * 238     * @param response239     * @param replyMessage240     */241    private void addSoapFault(SoapMessage response, SoapFault replyMessage) throws TransformerException {242        SoapBody soapBody = response.getSoapBody();243        org.springframework.ws.soap.SoapFault soapFault;244        245        if (SoapFaultDefinition.SERVER.equals(replyMessage.getFaultCodeQName()) ||246                SoapFaultDefinition.RECEIVER.equals(replyMessage.getFaultCodeQName())) {247            soapFault = soapBody.addServerOrReceiverFault(replyMessage.getFaultString(),248                    replyMessage.getLocale());249        } else if (SoapFaultDefinition.CLIENT.equals(replyMessage.getFaultCodeQName()) ||250                SoapFaultDefinition.SENDER.equals(replyMessage.getFaultCodeQName())) {251            soapFault = soapBody.addClientOrSenderFault(replyMessage.getFaultString(),252                    replyMessage.getLocale());253        } else if (soapBody instanceof Soap11Body) {254            Soap11Body soap11Body = (Soap11Body) soapBody;255            soapFault = soap11Body.addFault(replyMessage.getFaultCodeQName(),...addSoapFault
Using AI Code Generation
1public class SoapFaultTest {2    private WebServiceEndpoint webServiceEndpoint;3    public void testSoapFault() {4        webServiceEndpoint.addSoapFault(new SoapFault(SoapFault.FaultCode.SERVER, "Server error"));5        webServiceEndpoint.createSoapFaultBuilder()6                .faultCode(SoapFault.FaultCode.SERVER)7                .faultString("Server error")8                .build();9    }10}11public class SoapFaultTest {12    private WebServiceServerBuilder webServiceServerBuilder;13    public void testSoapFault() {14        webServiceServerBuilder.addSoapFault(new SoapFault(SoapFault.FaultCode.SERVER, "Server error"));15        webServiceServerBuilder.createSoapFaultBuilder()16                .faultCode(SoapFault.FaultCode.SERVER)17                .faultString("Server error")18                .build();19    }20}addSoapFault
Using AI Code Generation
1@WebService(name = "HelloService", serviceName = "HelloService")2public class HelloService {3    public String sayHello(String name) {4        if (name == null) {5            throw new WebServiceException("Name is empty");6        }7        return "Hello " + name;8    }9}10@WebService(name = "HelloService", serviceName = "HelloService")11public class HelloService {12    public String sayHello(String name) {13        if (name == null) {14            throw new WebServiceException("Name is empty");15        }16        return "Hello " + name;17    }18}19@WebService(name = "HelloService", serviceName = "HelloService")20public class HelloService {21    public String sayHello(String name) {22        if (name == null) {23            throw new WebServiceException("Name is empty");24        }25        return "Hello " + name;26    }27}28@WebService(name = "HelloService", serviceName = "HelloService")29public class HelloService {30    public String sayHello(String name) {31        if (name == null) {32            throw new WebServiceException("Name is empty");33        }34        return "Hello " + name;35    }36}37@WebService(name = "HelloService", serviceName = "HelloService")38public class HelloService {39    public String sayHello(String name) {40        if (name == null) {41            throw new WebServiceException("Name is empty");42        }43        return "Hello " + name;44    }45}addSoapFault
Using AI Code Generation
1import com.consol.citrus.dsl.design.TestDesigner2import com.consol.citrus.dsl.design.TestDesignerRunner3import com.consol.citrus.message.MessageType4import com.consol.citrus.ws.message.SoapFault5import org.springframework.http.HttpStatus6import org.springframework.ws.soap.SoapFaultDetail7class SoapFaultTest implements TestDesignerRunner {8    void configure(TestDesigner test) {9        test.soap()10            .client("soapClient")11            .send()12            .soapAction("getQuote")13                    "<ns:symbol>citrus:randomNumber(4)</ns:symbol>" +14        test.soap()15            .server("soapServer")16            .receive()17                    "<ns:symbol>citrus:randomNumber(4)</ns:symbol>" +18            .extractFromPayload("/ns:getQuote/ns:request/ns:symbol", "symbol")19        test.echo("Received stock symbol: ${symbol}")20        test.soap()21            .server("soapServer")22            .send()23                    "<ns:symbol>${symbol}</ns:symbol>" +24        test.soap()25            .client("soapClient")26            .receive()27                    "<ns:symbol>${symbol}</ns:symbol>" +28        test.soap()addSoapFault
Using AI Code Generation
1package com.consol.citrus.samples;2import com.consol.citrus.annotations.CitrusTest;3import com.consol.citrus.dsl.junit.JUnit4CitrusTestRunner;4import com.consol.citrus.message.MessageType;5import com.consol.citrus.ws.message.SoapFault;6import org.testng.annotations.Test;7public class SoapFaultJavaIT extends JUnit4CitrusTestRunner {8    public void soapFaultJavaIT() {9        send("soapClient")10            .header("operation", "sayHelloFault")11            .header("citrus_soap_action", "sayHelloFault")12            .fork(true);13        receive("soapServer")14            .header("operation", "sayHelloFault")15            .header("citrus_soap_action", "sayHelloFault")16            .messageType(MessageType.XML);17        send("soapClient")18            .header("operation", "sayHelloFault")19            .header("citrus_soap_action", "sayHelloFault")20            .fork(true);21        receive("soapServer")Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
