예제 #1
0
  public static InterceptorChain getOutInterceptorChain(Exchange ex, SortedSet<Phase> phases) {
    Bus bus = ex.get(Bus.class);
    PhaseInterceptorChain chain = new PhaseInterceptorChain(phases);

    Endpoint ep = ex.get(Endpoint.class);
    List<Interceptor> il = ep.getOutInterceptors();
    if (LOG.isLoggable(Level.FINE)) {
      LOG.fine("Interceptors contributed by endpoint: " + il);
    }
    chain.add(il);
    il = ep.getService().getOutInterceptors();
    if (LOG.isLoggable(Level.FINE)) {
      LOG.fine("Interceptors contributed by service: " + il);
    }
    chain.add(il);
    il = bus.getOutInterceptors();
    if (LOG.isLoggable(Level.FINE)) {
      LOG.fine("Interceptors contributed by bus: " + il);
    }
    chain.add(il);

    if (ep.getService().getDataBinding() instanceof InterceptorProvider) {
      il = ((InterceptorProvider) ep.getService().getDataBinding()).getOutInterceptors();
      if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Interceptors contributed by databinding: " + il);
      }
      chain.add(il);
    }

    return chain;
  }
예제 #2
0
 /**
  * Get interceptor chain for retransmitting a message.
  *
  * @return chain (<code>null</code> if none set)
  */
 public PhaseInterceptorChain getRetransmitChain(Message msg) {
   Endpoint ep = msg.getExchange().getEndpoint();
   PhaseInterceptorChain pic = (PhaseInterceptorChain) ep.get(WSRM_RETRANSMIT_CHAIN);
   if (pic == null) {
     return null;
   }
   return pic.cloneChain();
 }
예제 #3
0
 protected static PhaseInterceptorChain setupInInterceptorChain(ClientConfiguration cfg) {
   PhaseManager pm = cfg.getBus().getExtension(PhaseManager.class);
   List<Interceptor<? extends Message>> i1 = cfg.getBus().getInInterceptors();
   List<Interceptor<? extends Message>> i2 = cfg.getInInterceptors();
   List<Interceptor<? extends Message>> i3 =
       cfg.getConduitSelector().getEndpoint().getInInterceptors();
   PhaseInterceptorChain chain = new PhaseChainCache().get(pm.getInPhases(), i1, i2, i3);
   chain.add(new ClientResponseFilterInterceptor());
   return chain;
 }
예제 #4
0
 /**
  * Clones and saves the interceptor chain the first time this is called, so that it can be used
  * for retransmission. Calls after the first are ignored.
  *
  * @param msg
  */
 public void initializeInterceptorChain(Message msg) {
   Endpoint ep = msg.getExchange().getEndpoint();
   synchronized (ep) {
     if (ep.get(WSRM_RETRANSMIT_CHAIN) == null) {
       LOG.info("Setting retransmit chain from message");
       PhaseInterceptorChain chain = (PhaseInterceptorChain) msg.getInterceptorChain();
       chain = chain.cloneChain();
       ep.put(WSRM_RETRANSMIT_CHAIN, chain);
     }
   }
 }
예제 #5
0
  protected Message createMessage(
      Object body,
      String httpMethod,
      MultivaluedMap<String, String> headers,
      URI currentURI,
      Exchange exchange,
      Map<String, Object> invocationContext,
      boolean proxy) {
    Message m = cfg.getConduitSelector().getEndpoint().getBinding().createMessage();
    m.put(Message.REQUESTOR_ROLE, Boolean.TRUE);
    m.put(Message.INBOUND_MESSAGE, Boolean.FALSE);

    m.put(Message.HTTP_REQUEST_METHOD, httpMethod);
    m.put(Message.PROTOCOL_HEADERS, headers);
    if (currentURI.isAbsolute() && currentURI.getScheme().startsWith(HTTP_SCHEME)) {
      m.put(Message.ENDPOINT_ADDRESS, currentURI.toString());
    } else {
      m.put(Message.ENDPOINT_ADDRESS, state.getBaseURI().toString());
    }

    Object requestURIProperty = cfg.getRequestContext().get(Message.REQUEST_URI);
    if (requestURIProperty == null) {
      m.put(Message.REQUEST_URI, currentURI.toString());
    } else {
      m.put(Message.REQUEST_URI, requestURIProperty.toString());
    }

    m.put(Message.CONTENT_TYPE, headers.getFirst(HttpHeaders.CONTENT_TYPE));

    body = checkIfBodyEmpty(body);
    setEmptyRequestPropertyIfNeeded(m, body);

    m.setContent(List.class, getContentsList(body));

    m.put(URITemplate.TEMPLATE_PARAMETERS, getState().getTemplates());

    PhaseInterceptorChain chain = setupOutInterceptorChain(cfg);
    chain.setFaultObserver(setupInFaultObserver(cfg));
    m.setInterceptorChain(chain);

    exchange = createExchange(m, exchange);
    exchange.put(Message.REST_MESSAGE, Boolean.TRUE);
    exchange.setOneWay("true".equals(headers.getFirst(Message.ONE_WAY_REQUEST)));
    exchange.put(Retryable.class, new RetryableImpl());

    // context
    setContexts(m, exchange, invocationContext, proxy);

    // setup conduit selector
    prepareConduitSelector(m, currentURI, proxy);

    return m;
  }
예제 #6
0
  @Test
  public void testOrder() throws Exception {
    // make sure the interceptors get ordered correctly
    SortedSet<Phase> phases = new TreeSet<Phase>();
    phases.add(new Phase(Phase.PRE_PROTOCOL, 1));

    List<Interceptor<? extends Message>> lst = new ArrayList<Interceptor<? extends Message>>();
    lst.add(new MustUnderstandInterceptor());
    lst.add(new WSS4JInInterceptor());
    lst.add(new SAAJInInterceptor());
    PhaseInterceptorChain chain = new PhaseInterceptorChain(phases);
    chain.add(lst);
    String output = chain.toString();
    assertTrue(output.contains("MustUnderstandInterceptor, SAAJInInterceptor, WSS4JInInterceptor"));
  }
 private HttpSession getSession() {
   Message message = PhaseInterceptorChain.getCurrentMessage();
   HttpServletRequest request =
       (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
   HttpSession session = request.getSession(true);
   return session;
 }
 @Override
 protected SecurityContext createSecurityContext(final Principal p) {
   Message msg = PhaseInterceptorChain.getCurrentMessage();
   if (msg == null) {
     throw new IllegalStateException("Current message is not available");
   }
   return doCreateSecurityContext(p, msg.get(Subject.class));
 }
예제 #9
0
 /**
  * Retrieves the client IP for a SOAP request that is currently being handled by the calling
  * thread.
  *
  * @return the client IP for a current SOAP request being handled, or null if an error occured
  */
 public static String getClientIPForCurrentContext() {
   Message message = PhaseInterceptorChain.getCurrentMessage();
   if (message == null) {
     LOGGER.error("No SOAP message found in context while trying to determine client IP");
     return null;
   }
   Request object = (Request) message.get(AbstractHTTPDestination.HTTP_REQUEST);
   if (object == null) {
     LOGGER.error("No HTTP request attached to SOAP message while trying to determine client IP");
     return null;
   }
   return object.getRemoteAddr();
 }
 protected void setSubject(
     String name, String password, boolean isDigest, String nonce, String created)
     throws WSSecurityException {
   Message msg = PhaseInterceptorChain.getCurrentMessage();
   if (msg == null) {
     throw new IllegalStateException("Current message is not available");
   }
   Subject subject = null;
   try {
     subject = createSubject(name, password, isDigest, nonce, created);
   } catch (Exception ex) {
     String errorMessage = "Failed Authentication : Subject has not been created";
     LOG.severe(errorMessage);
     throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
   }
   if (subject == null
       || subject.getPrincipals().size() == 0
       || !checkUserPrincipal(subject.getPrincipals(), name)) {
     String errorMessage = "Failed Authentication : Invalid Subject";
     LOG.severe(errorMessage);
     throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
   }
   msg.put(Subject.class, subject);
 }
예제 #11
0
 public static void logError(String log) {
   Message message = PhaseInterceptorChain.getCurrentMessage();
   SECURITY_LOGGER.error(log + requestIpAndPortMessage(message));
 }
예제 #12
0
 public static void logWarn(String log, Throwable throwable) {
   Message message = PhaseInterceptorChain.getCurrentMessage();
   SECURITY_LOGGER.warn(log + requestIpAndPortMessage(message), throwable);
 }
예제 #13
0
 /**
  * Get the IP related to this request
  *
  * @return the request remote address
  */
 protected String getUserIp() {
   Message message = PhaseInterceptorChain.getCurrentMessage();
   HttpServletRequest request =
       (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
   return request.getRemoteAddr();
 }
예제 #14
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);
    }
  }
예제 #15
0
  // CHECKSTYLE:OFF - spec requires a bunch of params
  public W3CEndpointReference createW3CEndpointReference(
      String address,
      QName interfaceName,
      QName serviceName,
      QName portName,
      List<Element> metadata,
      String wsdlDocumentLocation,
      List<Element> referenceParameters,
      List<Element> elements,
      Map<QName, String> attributes) {
    // CHECKSTYLE:ON
    if (serviceName != null
        && portName != null
        && wsdlDocumentLocation != null
        && interfaceName == null) {
      Bus bus = BusFactory.getThreadDefaultBus();
      WSDLManager wsdlManager = bus.getExtension(WSDLManager.class);
      try {
        Definition def = wsdlManager.getDefinition(wsdlDocumentLocation);
        interfaceName =
            def.getService(serviceName)
                .getPort(portName.getLocalPart())
                .getBinding()
                .getPortType()
                .getQName();
      } catch (Exception e) {
        // do nothing
      }
    }
    if (serviceName == null && portName == null && address == null) {
      throw new IllegalStateException(
          "Address in an EPR cannot be null, " + " when serviceName or portName is null");
    }
    try {
      W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
      writer.setPrefix(JAXWSAConstants.WSA_PREFIX, JAXWSAConstants.NS_WSA);
      writer.writeStartElement(
          JAXWSAConstants.WSA_PREFIX, JAXWSAConstants.WSA_ERF_NAME, JAXWSAConstants.NS_WSA);
      writer.writeNamespace(JAXWSAConstants.WSA_PREFIX, JAXWSAConstants.NS_WSA);

      writer.writeStartElement(
          JAXWSAConstants.WSA_PREFIX, JAXWSAConstants.WSA_ADDRESS_NAME, JAXWSAConstants.NS_WSA);
      address = address == null ? "" : address;
      writer.writeCharacters(address);
      writer.writeEndElement();

      if (referenceParameters != null) {
        writer.writeStartElement(
            JAXWSAConstants.WSA_PREFIX,
            JAXWSAConstants.WSA_REFERENCEPARAMETERS_NAME,
            JAXWSAConstants.NS_WSA);
        for (Element ele : referenceParameters) {
          StaxUtils.writeElement(ele, writer, true);
        }
        writer.writeEndElement();
      }

      if (wsdlDocumentLocation != null
          || interfaceName != null
          || serviceName != null
          || (metadata != null && metadata.size() > 0)) {

        writer.writeStartElement(
            JAXWSAConstants.WSA_PREFIX, JAXWSAConstants.WSA_METADATA_NAME, JAXWSAConstants.NS_WSA);
        writer.writeNamespace(JAXWSAConstants.WSAW_PREFIX, JAXWSAConstants.NS_WSAW);
        writer.writeNamespace(JAXWSAConstants.WSAM_PREFIX, JAXWSAConstants.NS_WSAM);

        if (wsdlDocumentLocation != null) {
          boolean includeLocationOnly = false;
          org.apache.cxf.message.Message message = PhaseInterceptorChain.getCurrentMessage();
          if (message != null) {
            includeLocationOnly =
                MessageUtils.isTrue(
                    message.getContextualProperty("org.apache.cxf.wsa.metadata.wsdlLocationOnly"));
          }
          String attrubuteValue =
              serviceName != null && !includeLocationOnly
                  ? serviceName.getNamespaceURI() + " " + wsdlDocumentLocation
                  : wsdlDocumentLocation;
          writer.writeNamespace(JAXWSAConstants.WSDLI_PFX, JAXWSAConstants.NS_WSDLI);
          writer.writeAttribute(
              JAXWSAConstants.WSDLI_PFX,
              JAXWSAConstants.NS_WSDLI,
              JAXWSAConstants.WSDLI_WSDLLOCATION,
              attrubuteValue);
        }
        if (interfaceName != null) {
          writer.writeStartElement(
              JAXWSAConstants.WSAM_PREFIX,
              JAXWSAConstants.WSAM_INTERFACE_NAME,
              JAXWSAConstants.NS_WSAM);
          String portTypePrefix = interfaceName.getPrefix();
          if (portTypePrefix == null || portTypePrefix.equals("")) {
            portTypePrefix = "ns1";
          }
          writer.writeNamespace(portTypePrefix, interfaceName.getNamespaceURI());
          writer.writeCharacters(portTypePrefix + ":" + interfaceName.getLocalPart());
          writer.writeEndElement();
        }

        String serviceNamePrefix = null;

        if (serviceName != null) {
          serviceNamePrefix =
              (serviceName.getPrefix() == null || serviceName.getPrefix().length() == 0)
                  ? "ns2"
                  : serviceName.getPrefix();

          writer.writeStartElement(
              JAXWSAConstants.WSAM_PREFIX,
              JAXWSAConstants.WSAM_SERVICENAME_NAME,
              JAXWSAConstants.NS_WSAM);

          if (portName != null) {
            writer.writeAttribute(JAXWSAConstants.WSAM_ENDPOINT_NAME, portName.getLocalPart());
          }
          writer.writeNamespace(serviceNamePrefix, serviceName.getNamespaceURI());
          writer.writeCharacters(serviceNamePrefix + ":" + serviceName.getLocalPart());

          writer.writeEndElement();
        }

        if (wsdlDocumentLocation != null) {

          writer.writeStartElement(
              WSDLConstants.WSDL_PREFIX,
              WSDLConstants.QNAME_DEFINITIONS.getLocalPart(),
              WSDLConstants.NS_WSDL11);
          writer.writeNamespace(WSDLConstants.WSDL_PREFIX, WSDLConstants.NS_WSDL11);
          writer.writeStartElement(
              WSDLConstants.WSDL_PREFIX,
              WSDLConstants.QNAME_IMPORT.getLocalPart(),
              WSDLConstants.QNAME_IMPORT.getNamespaceURI());
          if (serviceName != null) {
            writer.writeAttribute(WSDLConstants.ATTR_NAMESPACE, serviceName.getNamespaceURI());
          }
          writer.writeAttribute(WSDLConstants.ATTR_LOCATION, wsdlDocumentLocation);
          writer.writeEndElement();
          writer.writeEndElement();
        }

        if (metadata != null) {
          for (Element e : metadata) {
            StaxUtils.writeElement(e, writer, true);
          }
        }

        writer.writeEndElement();
      }

      if (elements != null) {
        for (Element e : elements) {
          StaxUtils.writeElement(e, writer, true);
        }
      }
      writer.writeEndElement();
      writer.flush();

      Unmarshaller unmarshaller = getJAXBContext().createUnmarshaller();
      return (W3CEndpointReference) unmarshaller.unmarshal(writer.getDocument());
    } catch (Exception e) {
      throw new WebServiceException(
          new Message("ERROR_UNMARSHAL_ENDPOINTREFERENCE", LOG).toString(), e);
    }
  }
 @Override
 public void filter(ContainerRequestContext context) throws IOException {
   InterceptorChain chain = PhaseInterceptorChain.getCurrentMessage().getInterceptorChain();
   chain.add(this);
 }