예제 #1
0
  public static MessageContext sendUsingSwA(String fileName, String targetEPR) throws IOException {

    Options options = new Options();
    options.setTo(new EndpointReference(targetEPR));
    options.setAction("urn:uploadFileUsingSwA");
    options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE);

    ServiceClient sender = new ServiceClient();
    sender.setOptions(options);
    OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);

    MessageContext mc = new MessageContext();

    System.out.println("Sending file : " + fileName + " as SwA");
    FileDataSource fileDataSource = new FileDataSource(new File(fileName));
    DataHandler dataHandler = new DataHandler(fileDataSource);
    String attachmentID = mc.addAttachment(dataHandler);

    SOAPFactory factory = OMAbstractFactory.getSOAP11Factory();
    SOAPEnvelope env = factory.getDefaultEnvelope();
    OMNamespace ns = factory.createOMNamespace("http://services.samples/xsd", "m0");
    OMElement payload = factory.createOMElement("uploadFileUsingSwA", ns);
    OMElement request = factory.createOMElement("request", ns);
    OMElement imageId = factory.createOMElement("imageId", ns);
    imageId.setText(attachmentID);
    request.addChild(imageId);
    payload.addChild(request);
    env.getBody().addChild(payload);
    mc.setEnvelope(env);

    mepClient.addMessageContext(mc);
    mepClient.execute(true);
    MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);

    SOAPBody body = response.getEnvelope().getBody();
    String imageContentId =
        body.getFirstChildWithName(
                new QName("http://services.samples/xsd", "uploadFileUsingSwAResponse"))
            .getFirstChildWithName(new QName("http://services.samples/xsd", "response"))
            .getFirstChildWithName(new QName("http://services.samples/xsd", "imageId"))
            .getText();

    Attachments attachment = response.getAttachmentMap();
    dataHandler = attachment.getDataHandler(imageContentId);
    File tempFile = File.createTempFile("swa-", ".gif");
    FileOutputStream fos = new FileOutputStream(tempFile);
    dataHandler.writeTo(fos);
    fos.flush();
    fos.close();

    System.out.println("Saved response to file : " + tempFile.getAbsolutePath());

    return response;
  }
예제 #2
0
  public static void transferFile(File file, String destinationFile) throws Exception {

    Options options = new Options();
    options.setTo(targetEPR);
    options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE);
    options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
    // Increase the time out when sending large attachments
    options.setTimeOutInMilliSeconds(10000);
    options.setTo(targetEPR);
    options.setAction("urn:uploadFile");

    // assume the use runs this sample at
    // <axis2home>/samples/soapwithattachments/ dir
    ConfigurationContext configContext =
        ConfigurationContextFactory.createConfigurationContextFromFileSystem(
            "../../repository", null);

    ServiceClient sender = new ServiceClient(configContext, null);
    sender.setOptions(options);
    OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);

    MessageContext mc = new MessageContext();
    FileDataSource fileDataSource = new FileDataSource(file);

    // Create a dataHandler using the fileDataSource. Any implementation of
    // javax.activation.DataSource interface can fit here.
    DataHandler dataHandler = new DataHandler(fileDataSource);
    String attachmentID = mc.addAttachment(dataHandler);

    SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
    SOAPEnvelope env = fac.getDefaultEnvelope();
    OMNamespace omNs = fac.createOMNamespace("http://service.soapwithattachments.sample", "swa");
    OMElement uploadFile = fac.createOMElement("uploadFile", omNs);
    OMElement nameEle = fac.createOMElement("name", omNs);
    nameEle.setText(destinationFile);
    OMElement idEle = fac.createOMElement("attchmentID", omNs);
    idEle.setText(attachmentID);
    uploadFile.addChild(nameEle);
    uploadFile.addChild(idEle);
    env.getBody().addChild(uploadFile);
    mc.setEnvelope(env);

    mepClient.addMessageContext(mc);
    mepClient.execute(true);
    MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
    SOAPBody body = response.getEnvelope().getBody();
    OMElement element =
        body.getFirstElement()
            .getFirstChildWithName(
                new QName("http://service.soapwithattachments.sample", "return"));
    System.out.println(element.getText());
  }
예제 #3
0
  /**
   * Adds the payload content to the SOAP message. How the content is added to the message depends
   * on the <i>containment</i> of the payload ({@link IPayload#getContainment()}).
   *
   * <p>The default containment is {@link IPayload.Containment#ATTACHMENT} in which case the payload
   * content as added as a SOAP attachment. The payload will be referred to from the ebMS header by
   * the MIME Content-id of the MIME part. This Content-id MUST specified in the message meta-data
   * ({@link IPayload#getPayloadURI()}).
   *
   * <p>When the containment is specified as {@link IPayload.Containment#EXTERNAL} no content will
   * be added to SOAP message. It is assumed that transfer of the content takes place out of band.
   *
   * <p>When {@link IPayload.Containment#BODY} is specified as containment the content should be
   * added to the SOAP Body. This requires the payload content to be a XML document. If the
   * specified content is not, an exception is thrown.<br>
   * <b>NOTE:</b> A payload included in the body is referred to from the ebMS header by the <code>id
   * </code> attribute of the root element of the XML Document. The submitted message meta data
   * however can also included a reference ({@see IPayload#getPayloadURI()}). In case both the
   * payload and the message meta data included an id the submitter MUST ensure that the value is
   * the same. If not the payload will not be included in the message and this method will throw an
   * exception.
   *
   * @param p The payload that should be added to the message
   * @param mc The Axis2 message context for the outgoing message
   * @throws Exception When a problem occurs while adding the payload contents to the message
   */
  protected void addContent(IPayload p, MessageContext mc) throws Exception {
    File f = null;

    switch (p.getContainment()) {
      case ATTACHMENT:
        log.debug("Adding payload as attachment. Content located at " + p.getContentLocation());
        f = new File(p.getContentLocation());

        // Use specified MIME type or detect it when none is specified
        String mimeType = p.getMimeType();
        if (mimeType == null || mimeType.isEmpty()) {
          log.debug("Detecting MIME type of payload");
          mimeType = Utils.detectMimeType(f);
        }

        log.debug("Payload mime type is " + mimeType);
        // Use Axiom ConfigurableDataHandler to enable setting of mime type
        ConfigurableDataHandler dh = new ConfigurableDataHandler(new FileDataSource(f));
        dh.setContentType(mimeType);

        // Check if a Content-id is specified, if not generate one now
        String cid = p.getPayloadURI();
        if (cid == null || cid.isEmpty()) {
          log.warn("Content-id missing for payload.");
          throw new Exception("Content-id missing for payload");
        }

        log.debug("Add payload to message as attachment with Content-id: " + cid);
        mc.addAttachment(cid, dh);
        log.info("Payload content located at '" + p.getContentLocation() + "' added to message");

        return;
      case BODY:
        log.debug("Adding payload to SOAP body. Content located at " + p.getContentLocation());
        f = new File(p.getContentLocation());

        try {
          log.debug("Parse the XML from file so it can be added to SOAP body");
          OMXMLParserWrapper builder = OMXMLBuilderFactory.createOMBuilder(new FileReader(f));
          OMElement documentElement = builder.getDocumentElement();

          // Check that refence and id are equal if both specified
          String href = p.getPayloadURI();
          String xmlId = documentElement.getAttributeValue(new QName("id"));
          if (href != null && xmlId != null && !href.equals(xmlId)) {
            log.error(
                "Payload reference ["
                    + href
                    + "] and id of payload element ["
                    + xmlId
                    + "] are not equal! Can not create consistent message.");
            throw new Exception(
                "Payload reference ["
                    + href
                    + "] and id of payload element ["
                    + xmlId
                    + "] are not equal! Can not create consistent message.");
          } else if (href != null && Utils.isNullOrEmpty(xmlId)) {
            log.debug(
                "Set specified reference in meta data [" + href + "] as xml:id on root element");
            OMNamespace xmlIdNS =
                documentElement.declareNamespace(
                    EbMSConstants.QNAME_XMLID.getNamespaceURI(), "xml");
            documentElement.addAttribute(EbMSConstants.QNAME_XMLID.getLocalPart(), href, xmlIdNS);
          }

          log.debug("Add payload XML to SOAP Body");
          mc.getEnvelope().getBody().addChild(documentElement);
          log.info("Payload content located at '" + p.getContentLocation() + "' added to message");
        } catch (OMException parseError) {
          // The given document could not be parsed, probably not an XML document. Reject it as body
          // payload
          log.error("Failed to parse payload located at " + p.getContentLocation() + "!");
          throw new Exception(
              "Failed to parse payload located at " + p.getContentLocation() + "!", parseError);
        }
        return;
    }
  }