Java Code Examples for org.springframework.ws.WebServiceMessage

The following examples show how to use org.springframework.ws.WebServiceMessage. 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: spring-ws   Source File: TicketAgentClient.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public List<BigInteger> listFlights() {
  ObjectFactory factory = new ObjectFactory();
  TListFlights tListFlights = factory.createTListFlights();

  JAXBElement<TListFlights> request = factory.createListFlightsRequest(tListFlights);

  JAXBElement<TFlightsResponse> response = (JAXBElement<TFlightsResponse>) webServiceTemplate
      .marshalSendAndReceive(request, new WebServiceMessageCallback() {

        public void doWithMessage(WebServiceMessage message) {
          TransportContext context = TransportContextHolder.getTransportContext();
          HttpUrlConnection connection = (HttpUrlConnection) context.getConnection();
          connection.getConnection().addRequestProperty("Authorization",
              BasicAuthenticationUtil.generateBasicAutenticationHeader(clientConfig.getUserName(),
                  clientConfig.getUserPassword()));
        }
      });

  return response.getValue().getFlightNumber();
}
 
Example 2
Source Project: citrus-simulator   Source File: SoapMessageHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new SOAP message representation from given payload resource. Constructs a SOAP envelope
 * with empty header and payload as body.
 *
 * @param message
 * @return
 * @throws IOException
 */
public Message createSoapMessage(Message message) {
    try {
        String payload = message.getPayload().toString();

        LOG.info("Creating SOAP message from payload: " + payload);

        WebServiceMessage soapMessage = soapMessageFactory.createWebServiceMessage();
        transformerFactory.newTransformer().transform(
                new StringSource(payload), soapMessage.getPayloadResult());

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        soapMessage.writeTo(bos);

        return new SoapMessage(new String(bos.toByteArray()), message.getHeaders());
    } catch (Exception e) {
        throw new CitrusRuntimeException("Failed to create SOAP message from payload resource", e);
    }
}
 
Example 3
Source Project: j-road   Source File: AarXTeeConsumerCallback.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doWithMessage(WebServiceMessage request) throws IOException, TransformerException {
	callback.doWithMessage(request);

	SaajSoapMessage message = (SaajSoapMessage) request;
	SOAPMessage mes = message.getSaajMessage();

	try {
		SOAPBody body = mes.getSOAPBody();

		SOAPElement queryEle = (SOAPElement) body.getChildElements().next();
		SOAPElement kehaEle = (SOAPElement) queryEle.getChildElements().next();

		java.util.Iterator kehaChilds = kehaEle.getChildElements();
		while (kehaChilds.hasNext()) {
			Object nextEle = kehaChilds.next();
			if (nextEle instanceof SOAPElement) {
				addType((SOAPElement) nextEle);
			}
		}
	} catch(Exception ex) {
		ex.printStackTrace();
	}
}
 
Example 4
Source Project: j-road   Source File: Adsv5XTeeServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
  callback.doWithMessage(message);
  try {
    SaajSoapMessage saajMessage = (SaajSoapMessage) message;
    SOAPMessage soapmess = saajMessage.getSaajMessage();
    SOAPEnvelope env = soapmess.getSOAPPart().getEnvelope();
    env.addNamespaceDeclaration("xro", "http://x-road.ee/xsd/x-road.xsd");
    Iterator headers = env.getHeader().getChildElements();
    while (headers.hasNext()) {
      SOAPElement header = (SOAPElement) headers.next();
      if (header.getNamespaceURI().equalsIgnoreCase("http://x-rd.net/xsd/xroad.xsd")) {
        String localHeaderName = header.getLocalName();
        QName qName = new QName("http://x-road.ee/xsd/x-road.xsd", localHeaderName, "xro");
        header.setElementQName(qName);
      }
    }
  } catch (SOAPException e) {
    throw new RuntimeException(e);
  }

}
 
Example 5
Source Project: j-road   Source File: TorXTeeServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
  callback.doWithMessage(message);
  try {
    SaajSoapMessage saajMessage = (SaajSoapMessage) message;
    SOAPMessage soapmess = saajMessage.getSaajMessage();
    SOAPEnvelope env = soapmess.getSOAPPart().getEnvelope();
    env.addNamespaceDeclaration("xro", "http://x-road.ee/xsd/x-road.xsd");
    Iterator headers = env.getHeader().getChildElements();
    while (headers.hasNext()) {
      SOAPElement header = (SOAPElement) headers.next();
      if (header.getNamespaceURI().equalsIgnoreCase("http://x-rd.net/xsd/xroad.xsd")) {
        String localHeaderName = header.getLocalName();
        QName qName = new QName("http://x-road.ee/xsd/x-road.xsd", localHeaderName, "xro");
        header.setElementQName(qName);
      }
    }
  } catch (SOAPException e) {
    throw new RuntimeException(e);
  }

}
 
Example 6
Source Project: j-road   Source File: KirXTeeServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
    callback.doWithMessage(message);
    try {
        SaajSoapMessage saajMsg = (SaajSoapMessage) message;
        SOAPMessage soapMsg = saajMsg.getSaajMessage();
        SOAPEnvelope env = soapMsg.getSOAPPart().getEnvelope();
        env.addNamespaceDeclaration(ns, nsV31Uri);

        Iterator headers = env.getHeader().getChildElements();
        while (headers.hasNext()) {
            SOAPElement header = (SOAPElement) headers.next();
            if (header.getNamespaceURI().equalsIgnoreCase(nsV30Uri)) {
                QName qName = new QName(nsV31Uri, header.getLocalName(), ns);
                header.setElementQName(qName);
            }
        }

        formatDate(saajMsg, startDate);
        formatDate(saajMsg, endDate);
    } catch (SOAPException e) {
        throw new RuntimeException(e);
    }
}
 
Example 7
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 8
Source Project: j-road   Source File: XRoadMessageCallback.java    License: Apache License 2.0 6 votes vote down vote up
public void doWithMessage(WebServiceMessage message) {
  SaajSoapMessage saajMessage = (SaajSoapMessage) message;
  try {
    // Add attachments
    if (attachments != null) {
      for (XRoadAttachment attachment : attachments) {
        saajMessage.addAttachment("<" + attachment.getCid() + ">", attachment, attachment.getContentType());
      }
    }
    SOAPMessage soapmess = saajMessage.getSaajMessage();
    SOAPEnvelope env = soapmess.getSOAPPart().getEnvelope();

    protocolVersionStrategy.addNamespaces(env);
    protocolVersionStrategy.addXTeeHeaderElements(env, serviceConfiguration);
  } catch (SOAPException e) {
    throw new RuntimeException(e);
  }
}
 
Example 9
Source Project: j-road   Source File: WSConsumptionLoggingInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
private boolean logMessage(MessageContext mc, MessageType messageType) {
  if (log.isDebugEnabled()) {
    WebServiceMessage message = MessageType.REQUEST.equals(messageType) ? mc.getRequest() : mc.getResponse();

    if (message instanceof SaajSoapMessage) {
      OutputStream out = new ByteArrayOutputStream();
      try {
        ((SaajSoapMessage) message).writeTo(out);
        log.debug(messageType + " message follows:\n" + out.toString());
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  }

  return true;
}
 
Example 10
protected void parseContextFromSoapHeader(final WebServiceMessage message, final Channel channel) {
	if (message instanceof SoapMessage) {
		final SoapMessage soapMessage = (SoapMessage) message;

		final TraceeFilterConfiguration filterConfiguration = backend.getConfiguration(profile);

		if (filterConfiguration.shouldProcessContext(channel)) {
			final SoapHeader soapHeader = soapMessage.getSoapHeader();
			if (soapHeader != null) {
				Iterator<SoapHeaderElement> tpicHeaders;
				try {
					tpicHeaders = soapHeader.examineHeaderElements(SOAP_HEADER_QNAME);
				} catch (SoapHeaderException ignored) {
					tpicHeaders = Collections.<SoapHeaderElement>emptyList().iterator();
				}
				if (tpicHeaders.hasNext()) {
					final Map<String, String> parsedTpic = soapHeaderTransport.parseTpicHeader(tpicHeaders.next().getSource());
					backend.putAll(filterConfiguration.filterDeniedParams(parsedTpic, channel));
				}
			}
		}
	} else {
		logger.info("Message is obviously no soap message - Not instance of Spring-WS SoapMessage");
	}
}
 
Example 11
protected void serializeContextToSoapHeader(final WebServiceMessage message, final Channel channel) {
	if (message instanceof SoapMessage) {
		final SoapMessage soapMessage = (SoapMessage) message;

		final TraceeFilterConfiguration filterConfiguration = backend.getConfiguration(profile);

		if (!backend.isEmpty() && filterConfiguration.shouldProcessContext(channel)) {
			final SoapHeader soapHeader = soapMessage.getSoapHeader();
			if (soapHeader != null) {

				final Map<String, String> context = filterConfiguration.filterDeniedParams(backend.copyToMap(), channel);
				soapHeaderTransport.renderSoapHeader(context, soapHeader.getResult());
			}
		}
	} else {
		logger.info("Message is obviously no soap message - Not instance of Spring-WS SoapMessage");
	}
}
 
Example 12
Source Project: spring-ws   Source File: OrderHistoryClient.java    License: MIT License 5 votes vote down vote up
public OrderHistory getOrderHistory(String userId) throws IOException {
  // create the request
  ObjectFactory factory = new ObjectFactory();
  GetOrderHistoryRequest getOrderHistoryRequest = factory.createGetOrderHistoryRequest();
  getOrderHistoryRequest.setUserId(userId);

  // marshal the request
  WebServiceMessage request = webServiceTemplate.getMessageFactory().createWebServiceMessage();
  MarshallingUtils.marshal(webServiceTemplate.getMarshaller(), getOrderHistoryRequest, request);

  // call the service
  DOMResult responseResult = new DOMResult();
  webServiceTemplate.sendSourceAndReceiveToResult(request.getPayloadSource(), responseResult);

  // extract the needed elements
  List<Order> orders = orderXPath.evaluate(responseResult.getNode(), new NodeMapper<Order>() {

    @Override
    public Order mapNode(Node node, int nodeNum) {
      // get the orderId
      String orderId = orderIdXPath.evaluateAsString(node);
      // create an order
      return new Order(orderId);
    }
  });

  OrderHistory result = new OrderHistory();
  result.setOrders(orders);
  LOGGER.info("found '{}' orders for userId='{}'", result.getOrders().size(), userId);

  return result;
}
 
Example 13
Source Project: spring-ws   Source File: HttpLoggingUtils.java    License: MIT License 5 votes vote down vote up
public static void logMessage(String id, WebServiceMessage webServiceMessage) {
  try {
    ByteArrayTransportOutputStream byteArrayTransportOutputStream =
        new ByteArrayTransportOutputStream();
    webServiceMessage.writeTo(byteArrayTransportOutputStream);

    String httpMessage = new String(byteArrayTransportOutputStream.toByteArray());
    LOGGER.info(NEW_LINE + "----------------------------" + NEW_LINE + id + NEW_LINE
        + "----------------------------" + NEW_LINE + httpMessage + NEW_LINE);
  } catch (Exception e) {
    LOGGER.error("Unable to log HTTP message.", e);
  }
}
 
Example 14
Source Project: spring-ws   Source File: TicketAgentEndpoint.java    License: MIT License 5 votes vote down vote up
@SoapAction(value = "http://example.com/TicketAgent/listFlights")
@ResponsePayload
public JAXBElement<TFlightsResponse> listFlights(
    @RequestPayload JAXBElement<TListFlights> request, MessageContext messageContext) {
  // access the SOAPAction value
  WebServiceMessage webServiceMessage = messageContext.getRequest();
  SoapMessage soapMessage = (SoapMessage) webServiceMessage;
  LOGGER.info("SOAPAction header: {}", soapMessage.getSoapAction());

  ObjectFactory factory = new ObjectFactory();
  TFlightsResponse tFlightsResponse = factory.createTFlightsResponse();
  tFlightsResponse.getFlightNumber().add(BigInteger.valueOf(101));

  return factory.createListFlightsResponse(tFlightsResponse);
}
 
Example 15
Source Project: spring-ws   Source File: SoapActionMatcher.java    License: MIT License 5 votes vote down vote up
@Override
public void match(URI uri, WebServiceMessage webServiceMessage)
    throws IOException, AssertionError {
  assertThat(webServiceMessage).isInstanceOf(SoapMessage.class);

  SoapMessage soapMessage = (SoapMessage) webServiceMessage;
  assertThat(soapMessage.getSoapAction()).isEqualTo(expectedSoapAction);
}
 
Example 16
Source Project: spring-ws   Source File: SoapActionCreator.java    License: MIT License 5 votes vote down vote up
@Override
public WebServiceMessage createRequest(WebServiceMessageFactory webServiceMessageFactory)
    throws IOException {
  WebServiceMessage webServiceMessage =
      new PayloadMessageCreator(payload).createMessage(webServiceMessageFactory);

  SoapMessage soapMessage = (SoapMessage) webServiceMessage;
  soapMessage.setSoapAction(soapAction);

  return webServiceMessage;
}
 
Example 17
@Override
public final WebServiceMessage createRequest(
        WebServiceMessageFactory messageFactory) throws IOException {
    final WebServiceMessage message; // Message to create

    message = adaptee.createMessage(messageFactory);
    if (message instanceof SoapMessage) {
        ((SoapMessage) message).setSoapAction(action);
    }

    return message;
}
 
Example 18
Source Project: j-road   Source File: TarnXTeeServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
  try {
    SaajSoapMessage saajMessage = (SaajSoapMessage) message;
    SOAPMessage soapmess = saajMessage.getSaajMessage();
    SOAPEnvelope env = soapmess.getSOAPPart().getEnvelope();
    env.addNamespaceDeclaration("eto", "http://producers.etoimik.xtee.riik.ee/producer/etoimik");
  } catch (SOAPException e) {
    throw new RuntimeException(e);
  }
  callback.doWithMessage(message);
}
 
Example 19
Source Project: j-road   Source File: TreasuryXTeeServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
  callback.doWithMessage(message);
  SOAPMessage extractedMessage = SOAPUtil.extractSoapMessage(message);
  try {
    Node operation = SOAPUtil.getFirstNonTextChild(extractedMessage.getSOAPBody());
    SOAPFactory factory = SOAPFactory.newInstance();
    SOAPElement p1 = factory.createElement("p1");
    p1.addAttribute(factory.createName("href"), "cid:manus");
    operation.appendChild(operation.getOwnerDocument().importNode(p1, true));
  } catch (SOAPException e) {
    throw new RuntimeException(e);
  }
}
 
Example 20
Source Project: j-road   Source File: RmvikiXTeeServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
  callback.doWithMessage(message);
  SOAPMessage extractedMessage = SOAPUtil.extractSoapMessage(message);
  try {
    Node operation = SOAPUtil.getFirstNonTextChild(extractedMessage.getSOAPBody());
    SOAPFactory factory = SOAPFactory.newInstance();
    SOAPElement p1 = factory.createElement("p1");
    p1.addAttribute(factory.createName("href"), "cid:manus");
    operation.appendChild(operation.getOwnerDocument().importNode(p1, true));
  } catch (SOAPException e) {
    throw new RuntimeException(e);
  }
}
 
Example 21
Source Project: j-road   Source File: PkrXTeeServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
  callback.doWithMessage(message);

  if (useTestDatabase) {
    SOAPUtil.substitute(message, getDatabase(), TEST_DATABASE);
  }
}
 
Example 22
Source Project: j-road   Source File: PkrXTeeServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
public Object extractData(WebServiceMessage message) throws IOException, TransformerException {
  if (useTestDatabase) {
    SOAPUtil.substitute(message, TEST_DATABASE, getDatabase());
  }

  return extractor.extractData(message);
}
 
Example 23
Source Project: j-road   Source File: StandardXRoadConsumerCallback.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void doWithMessage(WebServiceMessage request) throws IOException, TransformerException {
  SaajSoapMessage message = (SaajSoapMessage) request;
  SOAPMessage mes = message.getSaajMessage();

  try {
    mes.getSOAPPart().getEnvelope().addNamespaceDeclaration(StandardXRoadConsumer.ROOT_NS,
                                                            metadata.getRequestElementNs());
    getMarshaller().marshal(object, new DOMResult(mes.getSOAPBody()));
  } catch (SOAPException e) {
    throw new RuntimeException("Invalid SOAP message");
  }
  callback.doWithMessage(request);
}
 
Example 24
Source Project: j-road   Source File: DhlXTeeServiceImpl.java    License: Apache License 2.0 4 votes vote down vote up
public XRoadMessage<GetSendStatusResponseTypeUnencoded> extractData(WebServiceMessage message) throws IOException, TransformerException {
    Attachment attachment = (Attachment) ((SaajSoapMessage) message).getAttachments().next();
    String xml = new String(unzipAndDecode(attachment.getInputStream()), DVK_MESSAGE_CHARSET);
    final GetSendStatusResponseTypeUnencoded content = getTypeFromXml(addCorrectNamespaces(xml), GetSendStatusResponseTypeUnencoded.class);
    return new XmlBeansXRoadMessage<GetSendStatusResponseTypeUnencoded>(content);
}
 
Example 25
Source Project: j-road   Source File: SOAPUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static SOAPMessage extractSoapMessage(WebServiceMessage webServiceMessage) {
  return ((SaajSoapMessage) webServiceMessage).getSaajMessage();
}
 
Example 26
@Test
public void skipProcessingWithWrongMessageTypeOnRequest() {
	when(messageContext.getRequest()).thenReturn(mock(WebServiceMessage.class));
	unit.handleRequest(messageContext);
	assertThat(backend.isEmpty(), is(true));
}
 
Example 27
@Test
public void skipProcessingWithWrongMessageTypeOnResponse() {
	when(messageContext.getResponse()).thenReturn(mock(WebServiceMessage.class));
	unit.handleResponse(messageContext);
	assertThat(backend.isEmpty(), is(true));
}
 
Example 28
@Test
public void skipProcessingWithWrongMessageTypeOnRequest() throws Exception {
	when(messageContext.getRequest()).thenReturn(mock(WebServiceMessage.class));
	unit.handleRequest(messageContext, new Object());
	assertThat(backend.copyToMap(), hasKey(TraceeConstants.INVOCATION_ID_KEY));
}
 
Example 29
@Test
public void skipProcessingWithWrongMessageTypeOnResponse() throws Exception {
	when(messageContext.getResponse()).thenReturn(mock(WebServiceMessage.class));
	unit.handleResponse(messageContext, new Object());
	assertThat(backend.isEmpty(), is(true));
}