/** @param message */
  @Override
  public void handleMessage(SoapMessage message) throws Fault {
    long l = LOG.logStart();

    final OutputStream os = message.getContent(OutputStream.class);
    boolean isRequestor = MessageUtils.isRequestor(message);
    if (os == null) {
      LOG.logWarn("Could not log message because it not contains OutputStream!", null);
      return;
    }
    // create store file
    File fStore;
    if (isRequestor) {
      MSHOutMail rq = SoapUtils.getMSHOutMail(message);
      fStore = EBMSLogUtils.getOutboundFileName(true, rq.getId(), null);
    } else {
      // get base from input log file
      String base =
          (String) message.getExchange().get(EBMSConstants.EBMS_CP_BASE_LOG_SOAP_MESSAGE_FILE);
      fStore = EBMSLogUtils.getOutboundFileName(false, null, base);
    }

    LOG.log("Out " + (isRequestor ? "request" : "response") + " stored to:" + fStore.getName());
    message
        .getExchange()
        .put(
            EBMSConstants.EBMS_CP_BASE_LOG_SOAP_MESSAGE_FILE, EBMSLogUtils.getBaseFileName(fStore));
    message.getExchange().put(EBMSConstants.EBMS_CP_OUT_LOG_SOAP_MESSAGE_FILE, fStore);

    //  create FileOutputStream to log request
    FileOutputStream fos;
    try {
      fos = new FileOutputStream(fStore);
    } catch (FileNotFoundException ex) {
      String errmsg =
          "Could not log outbound message to file: '" + fStore.getAbsolutePath() + "'! ";
      LOG.logError(l, errmsg, ex);
      return;
    }

    // create  CacheAndWriteOutputStream
    final CacheAndWriteOutputStream newOut = new CacheAndWriteOutputStream(os);

    message.setContent(OutputStream.class, newOut);
    newOut.registerCallback(new LoggingCallback(fos, message, os, fStore));

    LOG.logEnd(l);
  }
  public void handleMessage(SoapMessage message) {
    if (getInvoker(message).getProtocolHandlers().isEmpty()) {
      return;
    }

    if (getInvoker(message).isOutbound()) {
      if (!chainAlreadyContainsSAAJ(message)) {
        SAAJ_OUT.handleMessage(message);
      }
      message.getInterceptorChain().add(ending);
    } else {
      boolean isFault = handleMessageInternal(message);
      SOAPMessage msg = message.getContent(SOAPMessage.class);
      if (msg != null) {
        XMLStreamReader xmlReader = createXMLStreamReaderFromSOAPMessage(msg);
        message.setContent(XMLStreamReader.class, xmlReader);
        // replace headers
        try {
          SAAJInInterceptor.replaceHeaders(msg, message);
        } catch (SOAPException e) {
          e.printStackTrace();
        }
      }
      if (isFault) {
        Endpoint ep = message.getExchange().get(Endpoint.class);
        message.getInterceptorChain().abort();
        if (ep.getInFaultObserver() != null) {
          ep.getInFaultObserver().onMessage(message);
        }
      }
    }
  }
 @Override
 public void handleMessage(SoapMessage message) throws Fault {
   final Header callHeader = message.getHeader(RequestCallbackFeature.CALL_ID_HEADER_NAME);
   if (callHeader == null) {
     return;
   }
   handleAddressing(message);
   final Header callbackHeader = message.getHeader(RequestCallbackFeature.CALLBACK_ID_HEADER_NAME);
   if (callbackHeader == null) {
     return;
   }
   final BindingOperationInfo boi = message.getExchange().getBindingOperationInfo();
   if (boi == null) {
     return;
   }
   final String action = SoapActionInInterceptor.getSoapAction(message);
   if (StringUtils.isEmpty(action)) {
     return;
   }
   final SoapOperationInfo soi = boi.getExtensor(SoapOperationInfo.class);
   if (soi == null) {
     return;
   }
   if (StringUtils.isEmpty(soi.getAction())) {
     soi.setAction(action);
   }
 }
  @Override
  public void handleMessage(SoapMessage msg) throws Fault {
    Endpoint ep = msg.getExchange().get(Endpoint.class);
    sdc.set(ep.getSecurityDomainContext());
    try {
      SecurityToken token = msg.get(SecurityToken.class);
      SecurityContext context = msg.get(SecurityContext.class);
      if (token == null || context == null || context.getUserPrincipal() == null) {
        super.handleMessage(msg);
        return;
      }
      UsernameToken ut = (UsernameToken) token;

      Subject subject =
          createSubject(
              ut.getName(), ut.getPassword(), ut.isHashed(), ut.getNonce(), ut.getCreatedTime());

      SecurityContext sc = doCreateSecurityContext(context.getUserPrincipal(), subject);
      msg.put(SecurityContext.class, sc);
    } finally {
      if (sdc != null) {
        sdc.remove();
      }
    }
  }
  private org.apache.xml.security.stax.securityToken.SecurityToken findEncryptedKeyToken()
      throws XMLSecurityException {
    @SuppressWarnings("unchecked")
    final List<SecurityEvent> incomingEventList =
        (List<SecurityEvent>) message.getExchange().get(SecurityEvent.class.getName() + ".in");
    if (incomingEventList != null) {
      for (SecurityEvent incomingEvent : incomingEventList) {
        if (WSSecurityEventConstants.ENCRYPTED_PART == incomingEvent.getSecurityEventType()
            || WSSecurityEventConstants.EncryptedElement == incomingEvent.getSecurityEventType()) {
          org.apache.xml.security.stax.securityToken.SecurityToken token =
              ((AbstractSecuredElementSecurityEvent) incomingEvent).getSecurityToken();
          if (token != null
              && token.getKeyWrappingToken() != null
              && token.getKeyWrappingToken().getSecretKey() != null
              && token.getKeyWrappingToken().getSha1Identifier() != null) {
            return token.getKeyWrappingToken();
          } else if (token != null
              && token.getSecretKey() != null
              && token.getSha1Identifier() != null) {
            return token;
          }
        }
      }

      // Fall back to a Signature in case there was no encrypted Element in the request
      for (SecurityEvent incomingEvent : incomingEventList) {
        if (WSSecurityEventConstants.SIGNED_PART == incomingEvent.getSecurityEventType()
            || WSSecurityEventConstants.SignedElement == incomingEvent.getSecurityEventType()) {
          org.apache.xml.security.stax.securityToken.SecurityToken token =
              ((AbstractSecuredElementSecurityEvent) incomingEvent).getSecurityToken();
          if (token != null
              && token.getKeyWrappingToken() != null
              && token.getKeyWrappingToken().getSecretKey() != null
              && token.getKeyWrappingToken().getSha1Identifier() != null) {
            return token.getKeyWrappingToken();
          } else if (token != null
              && token.getSecretKey() != null
              && token.getSha1Identifier() != null) {
            return token;
          }
        }
      }
    }
    return null;
  }
 private void handleAddressing(SoapMessage message) {
   final AddressingProperties maps =
       (AddressingProperties)
           message.getContextualProperty(JAXWSAConstants.ADDRESSING_PROPERTIES_INBOUND);
   if (maps == null) {
     return;
   }
   final EndpointReferenceType rpl = maps.getReplyTo();
   if (rpl == null) {
     return;
   }
   final AttributedURIType addr = rpl.getAddress();
   if (addr == null) {
     return;
   }
   final String replyTo = addr.getValue();
   final Exchange exchange = message.getExchange();
   if (exchange.getDestination() instanceof JMSDestination) {
     ContextUtils.storePartialResponseSent(message);
     if (!exchange.isOneWay()) {
       exchange.setOneWay(true);
     }
   } else {
     if (exchange.isOneWay()) {
       if (!Names.WSA_NONE_ADDRESS.equals(replyTo)) {
         // disable creation of "partial" response
         // by CXF decoupled response feature
         exchange.setOneWay(false);
       }
     } else {
       // A generic default exchange has been created.
       // Provide it to MAP aggregator as anon. request-response
       // and convert it afterwards to one-way.
       if (Names.WSA_NONE_ADDRESS.equals(replyTo)) {
         addr.setValue(Names.WSA_ANONYMOUS_ADDRESS);
       }
     }
   }
 }
  @Test
  public void testRequestorOutboundDispatchedSoapAction() throws Exception {
    SoapMessage message = setUpMessage();
    BindingOperationInfo dbop =
        setUpBindingOperationInfo(
            "http://foo/bar/d", "opDReq", "opDResp", SEI.class.getMethod("op", new Class[0]));
    SoapOperationInfo soi = new SoapOperationInfo();
    soi.setAction("http://foo/bar/d/SEI/opDReq");
    dbop.addExtensor(soi);

    BindingOperationInfo bop = message.getExchange().get(BindingOperationInfo.class);
    bop.setProperty("dispatchToOperation", dbop);

    interceptor.handleMessage(message);
    control.verify();

    Map<String, List<String>> reqHeaders =
        CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS));
    assertNotNull(reqHeaders);
    List<String> soapaction = reqHeaders.get("soapaction");
    assertTrue(null != soapaction && soapaction.size() == 1);
    assertEquals("\"http://foo/bar/d/SEI/opDReq\"", soapaction.get(0));
  }
Beispiel #8
0
  /**
   * @param message
   * @param endpoint
   * @param to
   * @return
   */
  protected Conduit buildConduit(
      SoapMessage message, final Endpoint endpoint, AttributedURIType to) {
    Conduit c;
    final String address = to.getValue();
    ConduitSelector cs =
        new DeferredConduitSelector() {
          @Override
          public synchronized Conduit selectConduit(Message message) {
            Conduit conduit = null;
            EndpointInfo endpointInfo = endpoint.getEndpointInfo();
            EndpointReferenceType original = endpointInfo.getTarget();
            try {
              if (null != address) {
                endpointInfo.setAddress(address);
              }
              conduit = super.selectConduit(message);
            } finally {
              endpointInfo.setAddress(original);
            }
            return conduit;
          }
        };

    cs.setEndpoint(endpoint);
    c = cs.selectConduit(message);
    // REVISIT
    // use application endpoint message observer instead?
    c.setMessageObserver(
        new MessageObserver() {
          public void onMessage(Message message) {
            LOG.fine("Ignoring response to resent message.");
          }
        });

    message.getExchange().setConduit(c);
    return c;
  }
  @Override
  protected MessageContext createProtocolMessageContext(SoapMessage message) {
    SOAPMessageContextImpl sm = new SOAPMessageContextImpl(message);

    Exchange exch = message.getExchange();
    setupBindingOperationInfo(exch, sm);
    SOAPMessage msg = sm.getMessage();
    try {
      List<SOAPElement> params = new ArrayList<SOAPElement>();
      message.put(MessageContext.REFERENCE_PARAMETERS, params);
      SOAPHeader head = msg.getSOAPHeader();
      if (head != null) {
        Iterator<Node> it = CastUtils.cast(head.getChildElements());
        while (it != null && it.hasNext()) {
          Node nd = it.next();
          if (nd instanceof SOAPElement) {
            SOAPElement el = (SOAPElement) nd;
            if (el.hasAttributeNS(Names.WSA_NAMESPACE_NAME, "IsReferenceParameter")
                && ("1".equals(el.getAttributeNS(Names.WSA_NAMESPACE_NAME, "IsReferenceParameter"))
                    || Boolean.parseBoolean(
                        el.getAttributeNS(Names.WSA_NAMESPACE_NAME, "IsReferenceParameter")))) {
              params.add(el);
            }
          }
        }
      }
      if (msg.getSOAPPart().getEnvelope().getBody() != null
          && msg.getSOAPPart().getEnvelope().getBody().hasFault()) {
        return null;
      }
    } catch (SOAPException e) {
      throw new Fault(e);
    }

    return sm;
  }
  public void handleMessage(Message m) throws Fault {
    if (!(m instanceof SoapMessage)) {
      return;
    }

    SoapMessage message = (SoapMessage) m;
    if (!message.hasHeaders()) {
      return;
    }
    Header mule_header = message.getHeader(MULE_HEADER_Q);
    if (mule_header == null) {
      return;
    }
    Object obj = mule_header.getObject();
    if (!(obj instanceof Element)) {
      // Error? We can't work with it at any rate.
      return;
    }

    Element header_element = (Element) obj;
    NodeList mule_headers = header_element.getChildNodes();
    int idx = 0;
    Node child;
    while ((child = mule_headers.item(idx++)) != null) {
      if (child.getNodeType() != Node.ELEMENT_NODE) {
        continue;
      }
      Element child_el = (Element) child;
      if (child_el.getNamespaceURI() == null || !child_el.getNamespaceURI().equals(MULE_NS_URI)) {
        continue;
      }

      if (SUPPORTED_HEADERS.contains(child_el.getLocalName())) {
        message.put(child_el.getLocalName(), collectTextFrom(child_el));
      }
    }

    MuleMessage reqMsg =
        ((MuleEvent) message.getExchange().get(CxfConstants.MULE_EVENT)).getMessage();

    // Copy correlation headers nto message
    String replyTo = (String) message.get(MuleProperties.MULE_REPLY_TO_PROPERTY);
    if (replyTo != null) {
      reqMsg.setReplyTo(replyTo);
    }

    String corId = (String) message.get(MuleProperties.MULE_CORRELATION_ID_PROPERTY);
    if (corId != null) {
      reqMsg.setCorrelationId(corId);
    }

    String corGroupSize = (String) message.get(MuleProperties.MULE_CORRELATION_GROUP_SIZE_PROPERTY);
    if (corGroupSize != null) {
      reqMsg.setCorrelationGroupSize(Integer.valueOf(corGroupSize));
    }

    String corSeq = (String) message.get(MuleProperties.MULE_CORRELATION_SEQUENCE_PROPERTY);
    if (corSeq != null) {
      reqMsg.setCorrelationSequence(Integer.valueOf(corSeq));
    }
  }
  private void handleAbort(SoapMessage message, MessageContext context) {
    if (isRequestor(message)) {
      // client side outbound
      if (getInvoker(message).isOutbound()) {
        message.getInterceptorChain().abort();

        MessageObserver observer =
            (MessageObserver) message.getExchange().get(MessageObserver.class);
        if (!message.getExchange().isOneWay() && observer != null) {
          Endpoint e = message.getExchange().get(Endpoint.class);
          Message responseMsg = e.getBinding().createMessage();

          // the request message becomes the response message
          message.getExchange().setInMessage(responseMsg);
          SOAPMessage soapMessage = ((SOAPMessageContext) context).getMessage();

          if (soapMessage != null) {
            responseMsg.setContent(SOAPMessage.class, soapMessage);
            XMLStreamReader xmlReader = createXMLStreamReaderFromSOAPMessage(soapMessage);
            responseMsg.setContent(XMLStreamReader.class, xmlReader);
          }
          responseMsg.put(
              PhaseInterceptorChain.STARTING_AT_INTERCEPTOR_ID,
              SOAPHandlerInterceptor.class.getName());
          observer.onMessage(responseMsg);
        }
        // We dont call onCompletion here, as onCompletion will be called by inbound
        // LogicalHandlerInterceptor
      } else {
        // client side inbound - Normal handler message processing
        // stops, but the inbound interceptor chain still continues, dispatch the message
        // By onCompletion here, we can skip following Logical handlers
        onCompletion(message);
      }
    } else {
      if (!getInvoker(message).isOutbound()) {
        // server side inbound
        message.getInterceptorChain().abort();
        Endpoint e = message.getExchange().get(Endpoint.class);
        Message responseMsg = e.getBinding().createMessage();
        if (!message.getExchange().isOneWay()) {
          message.getExchange().setOutMessage(responseMsg);
          SOAPMessage soapMessage = ((SOAPMessageContext) context).getMessage();

          responseMsg.setContent(SOAPMessage.class, soapMessage);

          InterceptorChain chain =
              OutgoingChainInterceptor.getOutInterceptorChain(message.getExchange());
          responseMsg.setInterceptorChain(chain);
          // so the idea of starting interceptor chain from any
          // specified point does not work
          // well for outbound case, as many outbound interceptors
          // have their ending interceptors.
          // For example, we can not skip MessageSenderInterceptor.
          chain.doInterceptStartingAfter(
              responseMsg, SoapPreProtocolOutInterceptor.class.getName());
        }

      } else {
        // server side outbound - Normal handler message processing
        // stops, but still continue the outbound interceptor chain, dispatch the message
      }
    }
  }
Beispiel #12
0
  private void doResend(SoapMessage message) {
    try {

      // initialize copied interceptor chain for message
      PhaseInterceptorChain retransmitChain = manager.getRetransmitChain(message);
      ProtocolVariation protocol = RMContextUtils.getProtocolVariation(message);
      Endpoint endpoint = manager.getReliableEndpoint(message).getEndpoint(protocol);
      PhaseChainCache cache = new PhaseChainCache();
      boolean after = true;
      if (retransmitChain == null) {

        // no saved retransmit chain, so construct one from scratch (won't work for WS-Security on
        // server, so
        //  need to fix)
        retransmitChain = buildRetransmitChain(endpoint, cache);
        after = false;
      }
      message.setInterceptorChain(retransmitChain);

      // clear flag for SOAP out interceptor so envelope will be written
      message.remove(SoapOutInterceptor.WROTE_ENVELOPE_START);

      // discard all saved content
      Set<Class<?>> formats = message.getContentFormats();
      List<CachedOutputStreamCallback> callbacks = null;
      for (Class<?> clas : formats) {
        Object content = message.getContent(clas);
        if (content != null) {
          LOG.info(
              "Removing "
                  + clas.getName()
                  + " content of actual type "
                  + content.getClass().getName());
          message.removeContent(clas);
          if (clas == OutputStream.class && content instanceof WriteOnCloseOutputStream) {
            callbacks = ((WriteOnCloseOutputStream) content).getCallbacks();
          }
        }
      }

      // read SOAP headers from saved input stream
      RewindableInputStream is =
          (RewindableInputStream) message.get(RMMessageConstants.SAVED_CONTENT);
      is.rewind();
      XMLStreamReader reader = StaxUtils.createXMLStreamReader(is, "UTF-8");
      message.getHeaders().clear();
      if (reader.getEventType() != XMLStreamConstants.START_ELEMENT
          && reader.nextTag() != XMLStreamConstants.START_ELEMENT) {
        throw new IllegalStateException("No document found");
      }
      readHeaders(reader, message);
      int event;
      while ((event = reader.nextTag()) != XMLStreamConstants.START_ELEMENT) {
        if (event == XMLStreamConstants.END_ELEMENT) {
          throw new IllegalStateException("No body content present");
        }
      }

      // set message addressing properties
      AddressingProperties maps = new MAPCodec().unmarshalMAPs(message);
      RMContextUtils.storeMAPs(maps, message, true, MessageUtils.isRequestor(message));
      AttributedURIType to = null;
      if (null != maps) {
        to = maps.getTo();
      }
      if (null == to) {
        LOG.log(Level.SEVERE, "NO_ADDRESS_FOR_RESEND_MSG");
        return;
      }
      if (RMUtils.getAddressingConstants().getAnonymousURI().equals(to.getValue())) {
        LOG.log(Level.FINE, "Cannot resend to anonymous target");
        return;
      }

      // initialize conduit for new message
      Conduit c = message.getExchange().getConduit(message);
      if (c == null) {
        c = buildConduit(message, endpoint, to);
      }
      c.prepare(message);

      // replace standard message marshaling with copy from saved stream
      ListIterator<Interceptor<? extends Message>> iterator = retransmitChain.getIterator();
      while (iterator.hasNext()) {
        Interceptor<? extends Message> incept = iterator.next();

        // remove JAX-WS interceptors which handle message modes and such
        if (incept.getClass().getName().startsWith("org.apache.cxf.jaxws.interceptors")) {
          retransmitChain.remove(incept);
        } else if (incept instanceof PhaseInterceptor
            && (((PhaseInterceptor<?>) incept).getPhase() == Phase.MARSHAL)) {

          // remove any interceptors from the marshal phase
          retransmitChain.remove(incept);
        }
      }
      retransmitChain.add(new CopyOutInterceptor(reader));

      // restore callbacks on output stream
      if (callbacks != null) {
        OutputStream os = message.getContent(OutputStream.class);
        if (os != null) {
          WriteOnCloseOutputStream woc;
          if (os instanceof WriteOnCloseOutputStream) {
            woc = (WriteOnCloseOutputStream) os;
          } else {
            woc = new WriteOnCloseOutputStream(os);
            message.setContent(OutputStream.class, woc);
          }
          for (CachedOutputStreamCallback cb : callbacks) {
            woc.registerCallback(cb);
          }
        }
      }

      // send the message
      message.put(RMMessageConstants.RM_RETRANSMISSION, Boolean.TRUE);
      if (after) {
        retransmitChain.doInterceptStartingAfter(message, RMCaptureOutInterceptor.class.getName());
      } else {
        retransmitChain.doIntercept(message);
      }
      if (LOG.isLoggable(Level.INFO)) {
        RMProperties rmps = RMContextUtils.retrieveRMProperties(message, true);
        SequenceType seq = rmps.getSequence();
        LOG.log(
            Level.INFO,
            "Retransmitted message "
                + seq.getMessageNumber()
                + " in sequence "
                + seq.getIdentifier().getValue());
        rmps = new RMProperties();
      }

    } catch (Exception ex) {
      LOG.log(Level.SEVERE, "RESEND_FAILED_MSG", ex);
    }
  }