Java Code Examples for org.springframework.xml.transform.StringResult

The following examples show how to use org.springframework.xml.transform.StringResult. These examples are extracted from open source projects. 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 Project: citrus-admin   Source File: WebSocketPushEventsListener.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Construct JSON test result from given test data.
 * @param test
 * @param cause
 * @param success
 * @return
 */
protected String getTestResult(TestCase test, Throwable cause, boolean success) {
    JSONObject resultObject = new JSONObject();
    JSONObject testObject = new JSONObject();

    testObject.put("name", test.getName());
    testObject.put("type", "JAVA");
    testObject.put("className", test.getTestClass().getSimpleName());
    testObject.put("packageName", test.getPackageName());

    resultObject.put("test", testObject);
    resultObject.put("processId", test.getName());
    resultObject.put("success", success);

    if (cause != null) {
        resultObject.put("errorMessage", cause.getMessage());
        resultObject.put("errorCause", cause.getCause() != null ? cause.getCause().getClass().getName() : cause.getClass().getName());

        StringResult stackTrace = new StringResult();
        cause.printStackTrace(new PrintWriter(stackTrace.getWriter()));
        resultObject.put("stackTrace", stackTrace.toString());
    }

    return resultObject.toJSONString();
}
 
Example 2
Source Project: citrus-simulator   Source File: SoapMessageHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Method reads SOAP body element from SOAP Envelope and transforms body payload to String.
 *
 * @param request
 * @return
 * @throws javax.xml.soap.SOAPException
 * @throws java.io.IOException
 * @throws javax.xml.transform.TransformerException
 */
public String getSoapBody(Message request) throws SOAPException, IOException, TransformerException {
    MessageFactory msgFactory = MessageFactory.newInstance();
    MimeHeaders mimeHeaders = new MimeHeaders();
    mimeHeaders.addHeader("Content-Type", "text/xml; charset=" + Charset.forName(System.getProperty("citrus.file.encoding", "UTF-8")));

    SOAPMessage message = msgFactory.createMessage(mimeHeaders, new ByteArrayInputStream(request.getPayload().toString().getBytes(System.getProperty("citrus.file.encoding", "UTF-8"))));
    SOAPBody soapBody = message.getSOAPBody();

    Document body = soapBody.extractContentAsDocument();

    StringResult result = new StringResult();
    transformerFactory.newTransformer().transform(new DOMSource(body), result);

    return result.toString();
}
 
Example 3
Source Project: j-road   Source File: KirXTeeServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void formatDate(SaajSoapMessage saajMsg, Date date) throws TransformerException {
    if (date == null) {
        return;
    }
    SOAPPart soapPart = saajMsg.getSaajMessage().getSOAPPart();
    Source source = new DOMSource(soapPart);
    StringResult stringResult = new StringResult();
    TransformerFactory.newInstance().newTransformer().transform(source, stringResult);
    try {
        String from = dateWithTimezone.format(date);
        String to = dateWithoutTimezone.format(date);
        String content = StringUtils.replace(stringResult.toString(), from, to);
        soapPart.setContent(new StringSource(content));
    } catch (Exception e) {
        throw new TransformerException(e);
    }
}
 
Example 4
Source Project: j-road   Source File: SOAPUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Substitutes all occurences of some given string inside the given {@link WebServiceMessage} with another value.
 *
 * @param message message to substitute in
 * @param from the value to substitute
 * @param to the value to substitute with
 * @throws TransformerException
 */
public static void substitute(WebServiceMessage message, String from, String to) throws TransformerException {
  SaajSoapMessage saajSoapMessage = (SaajSoapMessage) message;
  SOAPPart soapPart = saajSoapMessage.getSaajMessage().getSOAPPart();

  Source source = new DOMSource(soapPart);
  StringResult stringResult = new StringResult();

  TransformerFactory.newInstance().newTransformer().transform(source, stringResult);

  String content = stringResult.toString().replaceAll(from, to);

  try {
    soapPart.setContent(new StringSource(content));
  } catch (SOAPException e) {
    throw new TransformerException(e);
  }
}
 
Example 5
@Test
public void parseTpicHeaderFromResponseToBackend() throws Exception {
	final Map<String, String> context = new HashMap<>();
	context.put("our key", "is our value");
	final StringResult result = new StringResult();
	new SoapHeaderTransport().renderSoapHeader(context, result);
	final Source source = new StringSource(result.toString());

	final SoapHeader soapHeader = mock(SoapHeader.class);
	when(((SoapMessage) messageContext.getResponse()).getSoapHeader()).thenReturn(soapHeader);
	final SoapHeaderElement element = mock(SoapHeaderElement.class);
	when(element.getSource()).thenReturn(source);
	when(soapHeader.examineHeaderElements(eq(SOAP_HEADER_QNAME))).thenReturn(Collections.singletonList(element).iterator());

	unit.handleResponse(messageContext);
	assertThat(backend.size(), is(1));
	assertThat(backend.copyToMap(), hasEntry("our key", "is our value"));
}
 
Example 6
@Test
public void parseTpicHeaderFromFaultResponseToBackend() throws Exception {
	final Map<String, String> context = new HashMap<>();
	context.put("our key", "is our value");
	final StringResult result = new StringResult();
	new SoapHeaderTransport().renderSoapHeader(context, result);
	final Source source = new StringSource(result.toString());

	final SoapHeader soapHeader = mock(SoapHeader.class);
	when(((SoapMessage) messageContext.getResponse()).getSoapHeader()).thenReturn(soapHeader);
	final SoapHeaderElement element = mock(SoapHeaderElement.class);
	when(element.getSource()).thenReturn(source);
	when(soapHeader.examineHeaderElements(eq(SOAP_HEADER_QNAME))).thenReturn(Collections.singletonList(element).iterator());

	unit.handleFault(messageContext);
	assertThat(backend.size(), is(1));
	assertThat(backend.copyToMap(), hasEntry("our key", "is our value"));
}
 
Example 7
@Test
public void parseTpicHeaderFromRequestToTraceeBackend() throws Exception {
	final Map<String, String> context = new HashMap<>();
	context.put("our key", "is our value");
	final StringResult result = new StringResult();
	new SoapHeaderTransport().renderSoapHeader(context, result);
	final Source source = new StringSource(result.toString());

	final SoapHeader soapHeader = mock(SoapHeader.class);
	when(((SoapMessage) messageContext.getRequest()).getSoapHeader()).thenReturn(soapHeader);
	final SoapHeaderElement element = mock(SoapHeaderElement.class);
	when(element.getSource()).thenReturn(source);
	when(soapHeader.examineHeaderElements(eq(SOAP_HEADER_QNAME))).thenReturn(singletonList(element).iterator());

	unit.handleRequest(messageContext, new Object());
	assertThat(backend.size(), is(2));
	assertThat(backend.copyToMap(), hasKey(INVOCATION_ID_KEY));
	assertThat(backend.copyToMap(), hasEntry("our key", "is our value"));
}
 
Example 8
Source Project: j-road   Source File: AbstractXTeeAxisEndpoint.java    License: Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected void invokeInternalEx(XTeeMessage<Document> request,
                                XTeeMessage<Element> response,
                                SOAPMessage requestMessage,
                                SOAPMessage responseMessage) throws Exception {
  requestMessage.getSOAPHeader().detachNode();
  Node bodyNode;
  if (XRoadProtocolVersion.V2_0 == version) {
    bodyNode = SOAPUtil.getNodeByXPath(requestMessage.getSOAPBody(), "//keha");
  } else {
    bodyNode = requestMessage.getSOAPBody();
  }
  Node reqNode = bodyNode.getParentNode();
  NodeList nl = bodyNode.getChildNodes();
  for (int i = 0; i < nl.getLength(); i++) {
    Node curNode = nl.item(i);
    reqNode.appendChild(curNode.cloneNode(true));
  }
  reqNode.removeChild(bodyNode);

  // Since Axis needs the XML as a String a transformation is required.
  StringResult result = new StringResult();
  Transformer transformer = TransformerFactory.newInstance().newTransformer();
  transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
  transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  transformer.transform(new DOMSource(requestMessage.getSOAPPart().getEnvelope()), result);

  Message axisMessage = new Message(result.toString());
  // The context is very important, as the binding stub creates all the type bindings for proper unmarshalling.
  axisMessage.setMessageContext(getContextHelper().getMessageContext());

  // Adding the attachments is needed to handle "href" attributes where the data is in an attachment.
  for (Iterator<AttachmentPart> i = requestMessage.getAttachments(); i.hasNext();) {
    axisMessage.addAttachmentPart(i.next());
  }

  XTeeMessage<P> axisRequestMessage = new BeanXTeeMessage<P>(request.getHeader(),
                                                             (P) axisMessage.getSOAPEnvelope().getFirstBody().getObjectValue(getParingKehaClass()),
                                                             request.getAttachments());
  XTeeMessage<V> axisResponseMessage =
      new BeanXTeeMessage<V>(response.getHeader(), null, new ArrayList<XTeeAttachment>());

  invoke(axisRequestMessage, axisResponseMessage);

  V responseBean = axisResponseMessage.getContent();
  // If response is null we return <keha/>, otherwise some marshalling needs to be done.
  if (responseBean != null) {
    String responseXml = AxisUtil.serialize(responseBean);
    Document doc =
        DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(responseXml.getBytes("UTF-8")));
    Node parent = response.getContent().getParentNode();
    parent.removeChild(response.getContent());
    parent.appendChild(parent.getOwnerDocument().importNode(doc.getFirstChild(), true));
  }
}