private boolean checkAndReplaceEnvelope(OMElement resultElement, MessageContext synCtx) {
   OMElement firstChild = resultElement.getFirstElement();
   QName resultQName = firstChild.getQName();
   if (resultQName.getLocalPart().equals("Envelope")
       && (resultQName.getNamespaceURI().equals(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI)
           || resultQName.getNamespaceURI().equals(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI))) {
     SOAPEnvelope soapEnvelope = AXIOMUtils.getSOAPEnvFromOM(resultElement.getFirstElement());
     if (soapEnvelope != null) {
       try {
         soapEnvelope.buildWithAttachments();
         synCtx.setEnvelope(soapEnvelope);
       } catch (AxisFault axisFault) {
         handleException("Unable to attach SOAPEnvelope", axisFault, synCtx);
       }
     }
   } else {
     return false;
   }
   return true;
 }
 private boolean mediate(MessageContext synCtx, String format) {
   if (!isDoingXml(synCtx) && !isDoingJson(synCtx)) {
     log.error(
         "#mediate. Could not identify the payload format of the existing payload prior to mediate.");
     return false;
   }
   org.apache.axis2.context.MessageContext axis2MessageContext =
       ((Axis2MessageContext) synCtx).getAxis2MessageContext();
   StringBuffer result = new StringBuffer();
   StringBuffer resultCTX = new StringBuffer();
   regexTransformCTX(resultCTX, synCtx, format);
   replace(resultCTX.toString(), result, synCtx);
   String out = result.toString().trim();
   if (log.isDebugEnabled()) {
     log.debug("#mediate. Transformed payload format>>> " + out);
   }
   if (mediaType.equals(XML_TYPE)) {
     try {
       JsonUtil.removeJsonPayload(axis2MessageContext);
       OMElement omXML = AXIOMUtil.stringToOM(out);
       if (!checkAndReplaceEnvelope(
           omXML,
           synCtx)) { // check if the target of the PF 'format' is the entire SOAP envelop, not
                      // just the body.
         axis2MessageContext.getEnvelope().getBody().addChild(omXML.getFirstElement());
       }
     } catch (XMLStreamException e) {
       handleException("Error creating SOAP Envelope from source " + out, synCtx);
     }
   } else if (mediaType.equals(JSON_TYPE)) {
     JsonUtil.newJsonPayload(axis2MessageContext, out, true, true);
   } else if (mediaType.equals(TEXT_TYPE)) {
     JsonUtil.removeJsonPayload(axis2MessageContext);
     axis2MessageContext.getEnvelope().getBody().addChild(getTextElement(out));
   }
   // need to honour a content-type of the payload media-type as output from the payload
   // {re-merging patch https://wso2.org/jira/browse/ESBJAVA-3014}
   setContentType(synCtx);
   return true;
 }