/**
   * Handle the request.
   *
   * @param soapMessage The current message context.
   * @param installSubordinateTx true if a subordinate transaction should be interposed and false if
   *     the handler should just resume the incoming transaction. currently only works for AT
   *     transactions but will eventually be extended to work for BA transactions too.
   */
  protected boolean handleInboundMessage(
      final SOAPMessage soapMessage, boolean installSubordinateTx) {
    if (soapMessage != null) {
      try {
        final SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
        final SOAPHeader soapHeader = soapEnvelope.getHeader();
        final SOAPHeaderElement soapHeaderElement =
            getHeaderElement(
                soapHeader,
                CoordinationConstants.WSCOOR_NAMESPACE,
                CoordinationConstants.WSCOOR_ELEMENT_COORDINATION_CONTEXT);

        if (soapHeaderElement != null) {
          final CoordinationContextType cc =
              CoordinationContextHelper.deserialise(soapHeaderElement);
          final String coordinationType = cc.getCoordinationType();
          if (AtomicTransactionConstants.WSAT_PROTOCOL.equals(coordinationType)) {
            clearMustUnderstand(soapHeader, soapHeaderElement);
            TxContext txContext = new TxContextImple(cc);
            if (installSubordinateTx) {
              txContext = SubordinateImporter.importContext(cc);
            }
            TransactionManagerFactory.transactionManager().resume(txContext);
          } else if (BusinessActivityConstants.WSBA_PROTOCOL_ATOMIC_OUTCOME.equals(
              coordinationType)) {
            // interposition is not yet implemented for business activities
            clearMustUnderstand(soapHeader, soapHeaderElement);
            TxContext txContext = new com.arjuna.mwlabs.wst11.ba.context.TxContextImple(cc);
            if (installSubordinateTx) {
              txContext = com.arjuna.mwlabs.wst11.ba.SubordinateImporter.importContext(cc);
            }
            BusinessActivityManagerFactory.businessActivityManager().resume(txContext);
          } else {
            wstxLogger.i18NLogger.warn_mw_wst11_service_JaxHC11P_2(
                "com.arjuna.mw.wst11.service.JaxBaseHeaderContextProcessor.handleRequest(MessageContext context)",
                coordinationType);
          }
        }
      } catch (final Throwable th) {
        wstxLogger.i18NLogger.warn_mw_wst11_service_JaxHC11P_1(
            "com.arjuna.mw.wst11.service.JaxBaseHeaderContextProcessor.handleRequest(MessageContext context)",
            th);
      }
    }
    return true;
  }
  /**
   * @param messageContext
   * @throws SOAPException
   */
  private void ProcessSoapHeader(SOAPMessageContext messageContext) throws SOAPException {
    /*
     * Get the SOAP header
     */
    SOAPMessage soapMessage = messageContext.getMessage();
    SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
    SOAPHeader soapHeader = soapEnvelope.getHeader();
    if (soapHeader == null) {
      soapHeader = soapEnvelope.addHeader();
    }

    /*
     * Get authentication header information from the context and process
     */
    Object object = messageContext.get(AuthHeader.class.getSimpleName());
    if (object != null && object instanceof AuthHeader) {
      /*
       * AuthHeader
       */
      this.ProcessAuthHeader((AuthHeader) object, QnameFactory.getAuthHeaderQName(), soapHeader);
    }
  }
  @Override
  public boolean handleMessage(SOAPMessageContext context) {

    System.out.println("Client : handleMessage()......");

    Boolean isRequest = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    // if this is a request, true for outbound messages, false for inbound
    if (isRequest) {

      try {
        SOAPMessage soapMsg = context.getMessage();
        SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope();
        SOAPHeader soapHeader = soapEnv.getHeader();

        // if no header, add one
        if (soapHeader == null) {
          soapHeader = soapEnv.addHeader();
        }

        // add a soap header, name as "mac address"
        QName qname = new QName("http://service.coupon.ronx.com/", "couponList");
        SOAPHeaderElement soapHeaderElement = soapHeader.addHeaderElement(qname);

        soapHeaderElement.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT);
        //                soapHeaderElement.addTextNode(mac);
        soapMsg.saveChanges();

        // tracking
        soapMsg.writeTo(System.out);

      } catch (SOAPException | IOException e) {
        System.err.println(e);
      }
    }

    // continue other handler chain
    return true;
  }
Ejemplo n.º 4
0
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {

    String retval = "<html> <H4>";

    try {
      // Create a message factory.
      MessageFactory mf = MessageFactory.newInstance();

      // Create a message from the message factory.
      SOAPMessage msg = mf.createMessage();

      // Message creation takes care of creating the SOAPPart - a
      // required part of the message as per the SOAP 1.1
      // specification.
      SOAPPart sp = msg.getSOAPPart();

      // Retrieve the envelope from the soap part to start building
      // the soap message.
      SOAPEnvelope envelope = sp.getEnvelope();

      // Create a soap header from the envelope.
      SOAPHeader hdr = envelope.getHeader();

      // Create a soap body from the envelope.
      SOAPBody bdy = envelope.getBody();

      // Add a soap body element to the soap body
      SOAPBodyElement gltp =
          bdy.addBodyElement(
              envelope.createName("GetLastTradePrice", "ztrade", "http://wombat.ztrade.com"));

      gltp.addChildElement(envelope.createName("symbol", "ztrade", "http://wombat.ztrade.com"))
          .addTextNode("SUNW");

      StringBuffer urlSB = new StringBuffer();
      urlSB.append(req.getScheme()).append("://").append(req.getServerName());
      urlSB.append(":").append(req.getServerPort()).append(req.getContextPath());
      String reqBase = urlSB.toString();

      if (data == null) {
        data = reqBase + "/index.html";
      }

      // Want to set an attachment from the following url.
      // Get context
      URL url = new URL(data);

      AttachmentPart ap = msg.createAttachmentPart(new DataHandler(url));

      ap.setContentType("text/html");

      // Add the attachment part to the message.
      msg.addAttachmentPart(ap);

      // Create an endpoint for the recipient of the message.
      if (to == null) {
        to = reqBase + "/receiver";
      }

      URL urlEndpoint = new URL(to);

      System.err.println("Sending message to URL: " + urlEndpoint);
      System.err.println("Sent message is logged in \"sent.msg\"");

      retval += " Sent message (check \"sent.msg\") and ";

      FileOutputStream sentFile = new FileOutputStream("sent.msg");
      msg.writeTo(sentFile);
      sentFile.close();

      // Send the message to the provider using the connection.
      SOAPMessage reply = con.call(msg, urlEndpoint);

      if (reply != null) {
        FileOutputStream replyFile = new FileOutputStream("reply.msg");
        reply.writeTo(replyFile);
        replyFile.close();
        System.err.println("Reply logged in \"reply.msg\"");
        retval += " received reply (check \"reply.msg\").</H4> </html>";

      } else {
        System.err.println("No reply");
        retval += " no reply was received. </H4> </html>";
      }

    } catch (Throwable e) {
      e.printStackTrace();
      logger.severe("Error in constructing or sending message " + e.getMessage());
      retval += " There was an error " + "in constructing or sending message. </H4> </html>";
    }

    try {
      OutputStream os = resp.getOutputStream();
      os.write(retval.getBytes());
      os.flush();
      os.close();
    } catch (IOException e) {
      e.printStackTrace();
      logger.severe("Error in outputting servlet response " + e.getMessage());
    }
  }
Ejemplo n.º 5
0
  /**
   * Creates a DOM Document using the SOAP Envelope.
   *
   * @param env An org.apache.axiom.soap.SOAPEnvelope instance
   * @return Returns the DOM Document of the given SOAP Envelope.
   * @throws Exception
   */
  public static Document getDocumentFromSOAPEnvelope(SOAPEnvelope env, boolean useDoom)
      throws WSSecurityException {
    try {
      if (env instanceof Element) {
        return ((Element) env).getOwnerDocument();
      }

      if (useDoom) {
        env.build();

        // Workaround to prevent a bug in AXIOM where
        // there can be an incomplete OMElement as the first child body
        OMElement firstElement = env.getBody().getFirstElement();
        if (firstElement != null) {
          firstElement.build();
        }

        // Get processed headers
        SOAPHeader soapHeader = env.getHeader();
        ArrayList processedHeaderQNames = new ArrayList();
        if (soapHeader != null) {
          Iterator headerBlocs = soapHeader.getChildElements();
          while (headerBlocs.hasNext()) {
            SOAPHeaderBlock element = (SOAPHeaderBlock) headerBlocs.next();
            if (element.isProcessed()) {
              processedHeaderQNames.add(element.getQName());
            }
          }
        }

        // Check the namespace and find SOAP version and factory
        String nsURI = null;
        SOAPFactory factory;
        if (env.getNamespace()
            .getNamespaceURI()
            .equals(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI)) {
          nsURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
          factory = DOOMAbstractFactory.getSOAP11Factory();
        } else {
          nsURI = SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI;
          factory = DOOMAbstractFactory.getSOAP12Factory();
        }

        StAXSOAPModelBuilder stAXSOAPModelBuilder =
            new StAXSOAPModelBuilder(env.getXMLStreamReader(), factory, nsURI);
        SOAPEnvelope envelope = (stAXSOAPModelBuilder).getSOAPEnvelope();
        ((OMNode) envelope.getParent()).build();

        // Set the processed flag of the processed headers
        SOAPHeader header = envelope.getHeader();
        for (Iterator iter = processedHeaderQNames.iterator(); iter.hasNext(); ) {
          QName name = (QName) iter.next();
          Iterator omKids = header.getChildrenWithName(name);
          if (omKids.hasNext()) {
            ((SOAPHeaderBlock) omKids.next()).setProcessed();
          }
        }

        Element envElem = (Element) envelope;
        return envElem.getOwnerDocument();
      } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        env.build();
        env.serialize(baos);
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        return factory.newDocumentBuilder().parse(bais);
      }
    } catch (Exception e) {
      throw new WSSecurityException("Error in converting SOAP Envelope to Document", e);
    }
  }
Ejemplo n.º 6
0
  /**
   * Builds a SOAPEnvelope from DOM Document.
   *
   * @param doc - The dom document that contains a SOAP message
   * @param useDoom
   * @return
   * @throws WSSecurityException
   */
  public static SOAPEnvelope getSOAPEnvelopeFromDOMDocument(Document doc, boolean useDoom)
      throws WSSecurityException {

    if (useDoom) {
      try {
        // Get processed headers
        SOAPEnvelope env = (SOAPEnvelope) doc.getDocumentElement();
        ArrayList processedHeaderQNames = new ArrayList();
        SOAPHeader soapHeader = env.getHeader();

        if (soapHeader != null) {
          Iterator headerBlocs = soapHeader.getChildElements();
          while (headerBlocs.hasNext()) {

            OMElement element = (OMElement) headerBlocs.next();
            SOAPHeaderBlock header = null;

            if (element instanceof SOAPHeaderBlock) {
              header = (SOAPHeaderBlock) element;

              // If a header block is not an instance of SOAPHeaderBlock, it means that
              // it is a header we have added in rampart eg. EncryptedHeader and should
              // be converted to SOAPHeaderBlock for processing
            } else {
              header = soapHeader.addHeaderBlock(element.getLocalName(), element.getNamespace());
              Iterator attrIter = element.getAllAttributes();
              while (attrIter.hasNext()) {
                OMAttribute attr = (OMAttribute) attrIter.next();
                header.addAttribute(
                    attr.getLocalName(), attr.getAttributeValue(), attr.getNamespace());
              }
              Iterator nsIter = element.getAllDeclaredNamespaces();
              while (nsIter.hasNext()) {
                OMNamespace ns = (OMNamespace) nsIter.next();
                header.declareNamespace(ns);
              }
              // retrieve all child nodes (including any text nodes)
              // and re-attach to header block
              Iterator children = element.getChildren();
              while (children.hasNext()) {
                OMNode child = (OMNode) children.next();
                child.detach();
                header.addChild(child);
              }

              element.detach();

              soapHeader.build();

              header.setProcessed();
            }

            if (header.isProcessed()) {
              processedHeaderQNames.add(element.getQName());
            }
          }
        }
        XMLStreamReader reader = ((OMElement) doc.getDocumentElement()).getXMLStreamReader();
        StAXSOAPModelBuilder stAXSOAPModelBuilder = new StAXSOAPModelBuilder(reader, null);
        SOAPEnvelope envelope = stAXSOAPModelBuilder.getSOAPEnvelope();

        // Set the processed flag of the processed headers
        SOAPHeader header = envelope.getHeader();
        for (Iterator iter = processedHeaderQNames.iterator(); iter.hasNext(); ) {
          QName name = (QName) iter.next();
          Iterator omKids = header.getChildrenWithName(name);
          if (omKids.hasNext()) {
            ((SOAPHeaderBlock) omKids.next()).setProcessed();
          }
        }

        envelope.build();

        return envelope;

      } catch (FactoryConfigurationError e) {
        throw new WSSecurityException(e.getMessage());
      }
    } else {
      try {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        XMLUtils.outputDOM(doc.getDocumentElement(), os, true);
        ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray());

        StAXSOAPModelBuilder stAXSOAPModelBuilder =
            new StAXSOAPModelBuilder(
                XMLInputFactory.newInstance().createXMLStreamReader(bais), null);
        return stAXSOAPModelBuilder.getSOAPEnvelope();
      } catch (Exception e) {
        throw new WSSecurityException(e.getMessage());
      }
    }
  }
  /**
   * Actual transformation of the current message into a fault message
   *
   * @param synCtx the current message context
   * @param soapVersion SOAP version of the resulting fault desired
   * @param synLog the Synapse log to use
   */
  private void makeSOAPFault(MessageContext synCtx, int soapVersion, SynapseLog synLog) {

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Creating a SOAP " + (soapVersion == SOAP11 ? "1.1" : "1.2") + " fault");
    }

    // get the correct SOAP factory to be used
    SOAPFactory factory =
        (soapVersion == SOAP11
            ? OMAbstractFactory.getSOAP11Factory()
            : OMAbstractFactory.getSOAP12Factory());

    // create the SOAP fault document and envelope
    OMDocument soapFaultDocument = factory.createOMDocument();
    SOAPEnvelope faultEnvelope = factory.getDefaultFaultEnvelope();
    soapFaultDocument.addChild(faultEnvelope);

    // create the fault element  if it is need
    SOAPFault fault = faultEnvelope.getBody().getFault();
    if (fault == null) {
      fault = factory.createSOAPFault();
    }

    // populate it
    setFaultCode(synCtx, factory, fault, soapVersion);
    setFaultReason(synCtx, factory, fault, soapVersion);
    setFaultNode(factory, fault);
    setFaultRole(factory, fault);
    setFaultDetail(synCtx, factory, fault);

    // set the all headers of original SOAP Envelope to the Fault Envelope
    if (synCtx.getEnvelope() != null) {
      SOAPHeader soapHeader = synCtx.getEnvelope().getHeader();
      if (soapHeader != null) {
        for (Iterator iter = soapHeader.examineAllHeaderBlocks(); iter.hasNext(); ) {
          Object o = iter.next();
          if (o instanceof SOAPHeaderBlock) {
            SOAPHeaderBlock header = (SOAPHeaderBlock) o;
            faultEnvelope.getHeader().addChild(header);
          } else if (o instanceof OMElement) {
            faultEnvelope.getHeader().addChild((OMElement) o);
          }
        }
      }
    }

    if (synLog.isTraceOrDebugEnabled()) {
      String msg =
          "Original SOAP Message : "
              + synCtx.getEnvelope().toString()
              + "Fault Message created : "
              + faultEnvelope.toString();
      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace(msg);
      }
      if (log.isTraceEnabled()) {
        log.trace(msg);
      }
    }

    // overwrite current message envelope with new fault envelope
    try {
      synCtx.setEnvelope(faultEnvelope);
    } catch (AxisFault af) {
      handleException(
          "Error replacing current SOAP envelope " + "with the fault envelope", af, synCtx);
    }

    if (synCtx.getFaultTo() != null) {
      synCtx.setTo(synCtx.getFaultTo());
    } else if (synCtx.getReplyTo() != null) {
      synCtx.setTo(synCtx.getReplyTo());
    } else {
      synCtx.setTo(null);
    }

    // set original messageID as relatesTo
    if (synCtx.getMessageID() != null) {
      RelatesTo relatesTo = new RelatesTo(synCtx.getMessageID());
      synCtx.setRelatesTo(new RelatesTo[] {relatesTo});
    }

    synLog.traceOrDebug("End : Fault mediator");
  }
  public boolean handleMessage(SOAPMessageContext smc) {
    Boolean outbound = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (outbound) {
      // outbound message

      // *** #8 ***
      // get token from response context
      String propertyValue = (String) smc.get(RESPONSE_PROPERTY);
      System.out.printf("%s received '%s'%n", CLASS_NAME, propertyValue);

      // put token in response SOAP header
      try {
        // get SOAP envelope
        SOAPMessage msg = smc.getMessage();
        SOAPPart sp = msg.getSOAPPart();
        SOAPEnvelope se = sp.getEnvelope();

        // add header
        SOAPHeader sh = se.getHeader();
        if (sh == null) sh = se.addHeader();

        // add header element (name, namespace prefix, namespace)
        Name name = se.createName(RESPONSE_HEADER, "e", RESPONSE_NS);
        SOAPHeaderElement element = sh.addHeaderElement(name);

        // *** #9 ***
        // add header element value
        String newValue = propertyValue + "," + TOKEN;
        element.addTextNode(newValue);

        System.out.printf("%s put token '%s' on response message header%n", CLASS_NAME, TOKEN);

      } catch (SOAPException e) {
        System.out.printf("Failed to add SOAP header because of %s%n", e);
      }

    } else {
      // inbound message

      // get token from request SOAP header
      try {
        // get SOAP envelope header
        SOAPMessage msg = smc.getMessage();
        SOAPPart sp = msg.getSOAPPart();
        SOAPEnvelope se = sp.getEnvelope();
        SOAPHeader sh = se.getHeader();

        // check header
        if (sh == null) {
          System.out.println("Header not found.");
          return true;
        }

        // get Ticket header element
        Name nameTicket = se.createName(REQUEST_TICKET_HEADER, "e", REQUEST_NS);
        Iterator it = sh.getChildElements(nameTicket);
        // check header element
        if (!it.hasNext()) {
          System.out.printf("Header element %s not found.%n", REQUEST_TICKET_HEADER);
          return true;
        }
        SOAPElement elementTicket = (SOAPElement) it.next();

        // *** #4 ***
        // get header element value
        String headerTicketValue = elementTicket.getValue();
        System.out.printf("%s got '%s'%n", CLASS_NAME, headerTicketValue);

        // *** #5 ***
        // put Ticket token in request context
        System.out.printf("%s put token '%s' on request context%n", CLASS_NAME, headerTicketValue);
        smc.put(REQUEST_TICKET_PROPERTY, headerTicketValue);
        // set property scope to application so that server class can access property
        smc.setScope(REQUEST_TICKET_PROPERTY, Scope.APPLICATION);

        // get Author header element
        Name nameAuthor = se.createName(REQUEST_AUTHOR_HEADER, "e", REQUEST_NS);
        Iterator itAuthor = sh.getChildElements(nameAuthor);
        // check header element
        if (!itAuthor.hasNext()) {
          System.out.printf("Header element %s not found.%n", REQUEST_AUTHOR_HEADER);
          return true;
        }
        SOAPElement elementAuthor = (SOAPElement) itAuthor.next();

        // *** #4 ***
        // get Author header element value
        String headerAuthorValue = elementAuthor.getValue();
        System.out.printf("%s got '%s'%n", CLASS_NAME, headerAuthorValue);

        // *** #5 ***
        // put Author token in request context
        System.out.printf("%s put token '%s' on request context%n", CLASS_NAME, headerAuthorValue);
        smc.put(REQUEST_AUTHOR_PROPERTY, headerAuthorValue);
        // set property scope to application so that server class can access property
        smc.setScope(REQUEST_AUTHOR_PROPERTY, Scope.APPLICATION);

        // MAC
        // get MAC header element
        Name nameMac = se.createName(REQUEST_MAC_HEADER, "e", REQUEST_NS);
        Iterator itMac = sh.getChildElements(nameAuthor);
        // check header element
        if (!itMac.hasNext()) {
          System.out.printf("Header element %s not found.%n", REQUEST_MAC_HEADER);
          return true;
        }
        SOAPElement elementMac = (SOAPElement) itMac.next();

        // *** #4 ***
        // get MAC header element value
        String headerMacValue = elementMac.getTextContent();

        System.out.printf("%s got '%s'%n", CLASS_NAME, headerMacValue);

        // *** #5 ***
        // put MAC token in request context
        System.out.printf("%s put token '%s' on request context%n", CLASS_NAME, headerMacValue);
        smc.put(REQUEST_MAC_PROPERTY, headerMacValue);
        // set property scope to application so that server class can access property
        smc.setScope(REQUEST_MAC_PROPERTY, Scope.APPLICATION);

        String bodyValue = se.getBody().getTextContent();
        // *** #5 ***
        // put Body token in request context
        System.out.printf("%s put token '%s' on request context%n", CLASS_NAME, bodyValue);
        smc.put(REQUEST_BODY_PROPERTY, bodyValue);
        // set property scope to application so that server class can access property
        smc.setScope(REQUEST_BODY_PROPERTY, Scope.APPLICATION);

        msg.writeTo(System.out);

      } catch (SOAPException e) {
        System.out.printf("Failed to get SOAP header because of %s%n", e);
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return true;
  }