Java Code Examples for org.apache.axis.Message

The following examples show how to use org.apache.axis.Message. 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: tomee   Source File: EjbRpcProvider.java    License: Apache License 2.0 6 votes vote down vote up
public void createResult(Object object) {
    messageContext.setPastPivot(true);
    try {
        Message requestMessage = messageContext.getRequestMessage();
        SOAPEnvelope requestEnvelope = requestMessage.getSOAPEnvelope();
        RPCElement requestBody = getBody(requestEnvelope, messageContext);

        Message responseMessage = messageContext.getResponseMessage();
        SOAPEnvelope responseEnvelope = responseMessage.getSOAPEnvelope();
        ServiceDesc serviceDescription = messageContext.getService().getServiceDescription();
        RPCElement responseBody = createResponseBody(requestBody, messageContext, operation, serviceDescription, object, responseEnvelope, getInOutParams());

        responseEnvelope.removeBody();
        responseEnvelope.addBodyElement(responseBody);
    } catch (Exception e) {
        throw new ServerRuntimeException("Failed while creating response message body", e);
    }
}
 
Example 2
Source Project: googleads-java-lib   Source File: HttpHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an HTTP request based on the message context.
 *
 * @param msgContext the Axis message context
 * @return a new {@link HttpRequest} with content and headers populated
 */
private HttpRequest createHttpRequest(MessageContext msgContext)
    throws SOAPException, IOException {
  Message requestMessage =
      Preconditions.checkNotNull(
          msgContext.getRequestMessage(), "Null request message on message context");
  
  // Construct the output stream.
  String contentType = requestMessage.getContentType(msgContext.getSOAPConstants());
  ByteArrayOutputStream bos = new ByteArrayOutputStream(BUFFER_SIZE);

  if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
    logger.debug("Compressing request");
    try (GZIPOutputStream gzipOs = new GZIPOutputStream(bos, BUFFER_SIZE)) {
      requestMessage.writeTo(gzipOs);
    }
  } else {
    logger.debug("Not compressing request");
    requestMessage.writeTo(bos);
  }

  HttpRequest httpRequest =
      requestFactory.buildPostRequest(
          new GenericUrl(msgContext.getStrProp(MessageContext.TRANS_URL)),
          new ByteArrayContent(contentType, bos.toByteArray()));

  int timeoutMillis = msgContext.getTimeout();
  if (timeoutMillis >= 0) {
    logger.debug("Setting read and connect timeout to {} millis", timeoutMillis);
    // These are not the same, but MessageContext has only one definition of timeout.
    httpRequest.setReadTimeout(timeoutMillis);
    httpRequest.setConnectTimeout(timeoutMillis);
  }

  // Copy the request headers from the message context to the post request.
  setHttpRequestHeaders(msgContext, httpRequest);

  return httpRequest;
}
 
Example 3
Source Project: googleads-java-lib   Source File: HttpHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new Axis Message based on the contents of the HTTP response.
 *
 * @param httpResponse the HTTP response
 * @return an Axis Message for the HTTP response
 * @throws IOException if unable to retrieve the HTTP response's contents
 * @throws AxisFault if the HTTP response's status or contents indicate an unexpected error, such
 *     as a 405.
 */
private Message createResponseMessage(HttpResponse httpResponse) throws IOException, AxisFault {
  int statusCode = httpResponse.getStatusCode();
  String contentType = httpResponse.getContentType();
  // The conditions below duplicate the logic in CommonsHTTPSender and HTTPSender.
  boolean shouldParseResponse =
      (statusCode > 199 && statusCode < 300)
          || (contentType != null
              && !contentType.equals("text/html")
              && statusCode > 499
              && statusCode < 600);
  // Wrap the content input stream in a notifying stream so the stream event listener will be
  // notified when it is closed.
  InputStream responseInputStream =
      new NotifyingInputStream(httpResponse.getContent(), inputStreamEventListener);
  if (!shouldParseResponse) {
    // The contents are not an XML response, so throw an AxisFault with
    // the HTTP status code and message details.
    String statusMessage = httpResponse.getStatusMessage();
    AxisFault axisFault =
        new AxisFault("HTTP", "(" + statusCode + ")" + statusMessage, null, null);
    axisFault.addFaultDetail(
        Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, String.valueOf(statusCode));
    try (InputStream stream = responseInputStream) {
      byte[] contentBytes = ByteStreams.toByteArray(stream);
      axisFault.setFaultDetailString(
          Messages.getMessage(
              "return01", String.valueOf(statusCode), new String(contentBytes, UTF_8)));
    }
    throw axisFault;
  }
  // Response is an XML response. Do not consume and close the stream in this case, since that
  // will happen later when the response is deserialized by Axis (as confirmed by unit tests for
  // this class).
  Message responseMessage =
      new Message(
          responseInputStream, false, contentType, httpResponse.getHeaders().getLocation());
  responseMessage.setMessageType(Message.RESPONSE);
  return responseMessage;
}
 
Example 4
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));
  }
}
 
Example 5
Source Project: iaf   Source File: SoapWrapper.java    License: Apache License 2.0 4 votes vote down vote up
public String signMessage(String soapMessage, String user, String password, boolean passwordDigest) {
	try {
		WSSecurityEngine secEngine = WSSecurityEngine.getInstance();
		WSSConfig config = secEngine.getWssConfig();
		config.setPrecisionInMilliSeconds(false);

		// create context
		AxisClient tmpEngine = new AxisClient(new NullProvider());
		MessageContext msgContext = new MessageContext(tmpEngine);

		InputStream in = new ByteArrayInputStream(soapMessage.getBytes(StreamUtil.DEFAULT_INPUT_STREAM_ENCODING));
		Message msg = new Message(in);
		msg.setMessageContext(msgContext);

		// create unsigned envelope
		SOAPEnvelope unsignedEnvelope = msg.getSOAPEnvelope();
		Document doc = unsignedEnvelope.getAsDocument();

		// create security header and insert it into unsigned envelope
		WSSecHeader secHeader = new WSSecHeader();
		secHeader.insertSecurityHeader(doc);

		// add a UsernameToken
		WSSecUsernameToken tokenBuilder = new WSSecUsernameToken();
		if (passwordDigest) {
			tokenBuilder.setPasswordType(WSConstants.PASSWORD_DIGEST);
		} else {
			tokenBuilder.setPasswordType(WSConstants.PASSWORD_TEXT);
		}
		tokenBuilder.setUserInfo(user, password);
		tokenBuilder.addNonce();
		tokenBuilder.addCreated();
		tokenBuilder.prepare(doc);

		WSSecSignature sign = new WSSecSignature();
		sign.setUsernameToken(tokenBuilder);
		sign.setKeyIdentifierType(WSConstants.UT_SIGNING);
		sign.setSignatureAlgorithm(XMLSignature.ALGO_ID_MAC_HMAC_SHA1);
		sign.build(doc, null, secHeader);

		tokenBuilder.prependToHeader(secHeader);

		// add a Timestamp
		WSSecTimestamp timestampBuilder = new WSSecTimestamp();
		timestampBuilder.setTimeToLive(300);
		timestampBuilder.prepare(doc);
		timestampBuilder.prependToHeader(secHeader);

		Document signedDoc = doc;

		return DOM2Writer.nodeToString(signedDoc);

	} catch (Exception e) {
		throw new RuntimeException("Could not sign message", e);
	}
}
 
Example 6
Source Project: tomee   Source File: EjbRpcProvider.java    License: Apache License 2.0 4 votes vote down vote up
private Object[] demarshallArguments() throws Exception {
    SOAPMessage message = messageContext.getMessage();
    messageContext.setProperty(org.apache.axis.SOAPPart.ALLOW_FORM_OPTIMIZATION, Boolean.TRUE);
    if (message != null) {
        message.saveChanges();
    }

    try {
        Message reqMsg = messageContext.getRequestMessage();
        SOAPEnvelope requestEnvelope = reqMsg.getSOAPEnvelope();
        RPCElement body = getBody(requestEnvelope, messageContext);
        body.setNeedDeser(true);
        Vector args = null;
        try {
            args = body.getParams();
        } catch (SAXException e) {
            if (e.getException() != null) {
                throw e.getException();
            }
            throw e;
        }

        Object[] argValues = new Object[operation.getNumParams()];

        for (int i = 0; i < args.size(); i++) {
            RPCParam rpcParam = (RPCParam) args.get(i);
            Object value = rpcParam.getObjectValue();

            ParameterDesc paramDesc = rpcParam.getParamDesc();

            if (paramDesc != null && paramDesc.getJavaType() != null) {
                value = JavaUtils.convert(value, paramDesc.getJavaType());
                rpcParam.setObjectValue(value);
            }
            int order = (paramDesc == null || paramDesc.getOrder() == -1) ? i : paramDesc.getOrder();
            argValues[order] = value;
        }
        return argValues;
    } finally {
        messageContext.setProperty(org.apache.axis.SOAPPart.ALLOW_FORM_OPTIMIZATION, Boolean.FALSE);
    }
}
 
Example 7
Source Project: uima-uimaj   Source File: BinarySerializer.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Serialize an element named name, with the indicated attributes and value.
 *
 * @param name          is the element name
 * @param attributes          are the attributes...serializer is free to add more.
 * @param value          is the value
 * @param context          is the SerializationContext
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Override
public void serialize(QName name, Attributes attributes, Object value,
        SerializationContext context) throws IOException {
  if (value instanceof Serializable) {
    byte[] bytes = SerializationUtils.serialize((Serializable) value);

    // Should we use an attachment? Do so if:
    // (a) attachment support exists and mUseAttachments == true and
    // (b) if we are the server, the client sent us an attachment
    // (so we know client wants attachment support as well)]
    Message msg = context.getCurrentMessage();
    Attachments attachments = msg.getAttachmentsImpl();
    boolean useAttachments = (attachments != null) && mUseAttachments;
    if (useAttachments) {
      useAttachments = !context.getMessageContext().getPastPivot()
              || context.getMessageContext().getRequestMessage().getAttachments().hasNext();
    }
    // if we have attachment support, do this as an attachment
    if (useAttachments) {
      // System.out.println("Creating attachment"); //DEBUG
      SOAPConstants soapConstants = context.getMessageContext().getSOAPConstants();
      DataHandler dataHandler = new DataHandler(new OctetStreamDataSource("test",
              new OctetStream(bytes)));
      Part attachmentPart = attachments.createAttachmentPart(dataHandler);

      AttributesImpl attrs = new AttributesImpl();
      if (attributes != null && 0 < attributes.getLength())
        attrs.setAttributes(attributes); // copy the existing ones.

      int typeIndex = -1;
      if ((typeIndex = attrs.getIndex(Constants.URI_DEFAULT_SCHEMA_XSI, "type")) != -1) {
        // Found a xsi:type which should not be there for attachments.
        attrs.removeAttribute(typeIndex);
      }

      attrs.addAttribute("", soapConstants.getAttrHref(), soapConstants.getAttrHref(), "CDATA",
              attachmentPart.getContentIdRef());
      context.startElement(name, attrs);
      context.endElement();
    } else {
      // no attachment support - Base64 encode
      // System.out.println("No attachment support"); //DEBUG
      context.startElement(name, attributes);

      String base64str = Base64.encode(bytes);
      context.writeChars(base64str.toCharArray(), 0, base64str.length());
      context.endElement();
    }

  } else {
    throw new IOException(value.getClass().getName() + " is not serializable.");
  }
}
 
Example 8
Source Project: uima-uimaj   Source File: BinarySerializer_Axis11.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Serialize an element named name, with the indicated attributes and value.
 *
 * @param name          is the element name
 * @param attributes          are the attributes...serializer is free to add more.
 * @param value          is the value
 * @param context          is the SerializationContext
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Override
public void serialize(QName name, Attributes attributes, Object value,
        SerializationContext context) throws IOException {
  if (value instanceof Serializable) {
    byte[] bytes = SerializationUtils.serialize((Serializable) value);

    // Should we use an attachment? Do so if:
    // (a) attachment support exists and mUseAttachments == true and
    // (b) if we are the server, the client sent us an attachment
    // (so we know client wants attachment support as well)]
    Message msg = context.getCurrentMessage();
    Attachments attachments = msg.getAttachmentsImpl();
    boolean useAttachments = (attachments != null) && mUseAttachments;
    if (useAttachments) {
      useAttachments = !context.getMessageContext().getPastPivot()
              || context.getMessageContext().getRequestMessage().getAttachments().hasNext();
    }
    // if we have attachment support, do this as an attachment
    if (useAttachments) {
      // System.out.println("Creating attachment"); //DEBUG
      SOAPConstants soapConstants = context.getMessageContext().getSOAPConstants();
      DataHandler dataHandler = new DataHandler(new OctetStreamDataSource("test",
              new OctetStream(bytes)));
      Part attachmentPart = attachments.createAttachmentPart(dataHandler);

      AttributesImpl attrs = new AttributesImpl();
      if (attributes != null && 0 < attributes.getLength())
        attrs.setAttributes(attributes); // copy the existing ones.

      int typeIndex = -1;
      if ((typeIndex = attrs.getIndex(Constants.URI_DEFAULT_SCHEMA_XSI, "type")) != -1) {
        // Found a xsi:type which should not be there for attachments.
        attrs.removeAttribute(typeIndex);
      }

      attrs.addAttribute("", soapConstants.getAttrHref(), soapConstants.getAttrHref(), "CDATA",
              attachmentPart.getContentIdRef());
      context.startElement(name, attrs);
      context.endElement();
    } else {
      // no attachment support - Base64 encode
      // System.out.println("No attachment support"); //DEBUG
      context.startElement(name, attributes);

      String base64str = Base64.encode(bytes);
      context.writeChars(base64str.toCharArray(), 0, base64str.length());
      context.endElement();
    }

  } else {
    throw new IOException(value.getClass().getName() + " is not serializable.");
  }
}
 
Example 9
Source Project: googleads-java-lib   Source File: AxisDeserializer.java    License: Apache License 2.0 4 votes vote down vote up
public <ResultT> List<ResultT> deserializeBatchJobMutateResults(
    URL url,
    List<TypeMapping> serviceTypeMappings,
    Class<ResultT> resultClass,
    QName resultQName,
    int startIndex,
    int numberResults)
    throws Exception {

  List<ResultT> results = Lists.newArrayList();

  // Build a wrapped input stream from the response.
  InputStream wrappedStream =
      ByteSource.concat(
              ByteSource.wrap(SOAP_START_BODY.getBytes(UTF_8)),
              batchJobHelperUtility.buildWrappedByteSource(url, startIndex, numberResults),
              ByteSource.wrap(SOAP_END_BODY.getBytes(UTF_8)))
          .openStream();

  // Create a MessageContext with a new TypeMappingRegistry that will only
  // contain deserializers derived from serviceTypeMappings and the
  // result class/QName pair.
  MessageContext messageContext = new MessageContext(new AxisClient());
  TypeMappingRegistryImpl typeMappingRegistry = new TypeMappingRegistryImpl(true);
  messageContext.setTypeMappingRegistry(typeMappingRegistry);

  // Construct an Axis deserialization context.
  DeserializationContext deserializationContext =
      new DeserializationContext(
          new InputSource(wrappedStream), messageContext, Message.RESPONSE);

  // Register all type mappings with the new type mapping registry.
  TypeMapping registryTypeMapping =
      typeMappingRegistry.getOrMakeTypeMapping(messageContext.getEncodingStyle());
  registerTypeMappings(registryTypeMapping, serviceTypeMappings);

  // Parse the wrapped input stream.
  deserializationContext.parse();

  // Read the deserialized mutate results from the parsed stream.
  SOAPEnvelope envelope = deserializationContext.getEnvelope();
  MessageElement body = envelope.getFirstBody();

  for (Iterator<?> iter = body.getChildElements(); iter.hasNext(); ) {
    Object child = iter.next();
    MessageElement childElm = (MessageElement) child;
    @SuppressWarnings("unchecked")
    ResultT mutateResult = (ResultT) childElm.getValueAsType(resultQName, resultClass);
    results.add(mutateResult);
  }
  return results;
}