Java Code Examples for org.apache.cxf.interceptor.Fault

The following examples show how to use org.apache.cxf.interceptor.Fault. 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: cxf   Source File: BaseHeaderTesterRpcLitImpl.java    License: Apache License 2.0 6 votes vote down vote up
public PingMeResponseT pingMe(PingMeT in) throws PingMeFault {
    String msgType = in.getFaultType();
    LOG.fine("Server: in pingMe:" + msgType);
    if ("USER".equals(msgType)) {

        FaultDetailT detail = new FaultDetailT();
        detail.setMajor((short)1);
        detail.setMinor((short)2);
        throw new PingMeFault("USER FAULT TEST", detail);
    } else if ("SYSTEM".equals(msgType)) {
        throw new Fault(new Message(HeaderTesterUtil.EX_STRING,
                                    (ResourceBundle)null,
                                    new Object[]{"FAULT TEST"}));
    } else if ("RUNTIME".equals(msgType)) {
        throw new IllegalArgumentException(HeaderTesterUtil.EX_STRING);
    }

    return new PingMeResponseT();
}
 
Example 2
Source Project: cxf   Source File: BraveStopInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handleMessage(Message message) throws Fault {
    Map<String, List<Object>> responseHeaders = CastUtils.cast((Map<?, ?>)message.get(Message.PROTOCOL_HEADERS));

    if (responseHeaders == null) {
        responseHeaders = new HashMap<>();
        message.put(Message.PROTOCOL_HEADERS, responseHeaders);
    }

    boolean isRequestor = MessageUtils.isRequestor(message);
    Message requestMessage = isRequestor ? message.getExchange().getOutMessage()
        : message.getExchange().getInMessage();
    Map<String, List<String>> requestHeaders =
        CastUtils.cast((Map<?, ?>)requestMessage.get(Message.PROTOCOL_HEADERS));

    @SuppressWarnings("unchecked")
    final TraceScopeHolder<TraceScope> holder =
        (TraceScopeHolder<TraceScope>)message.getExchange().get(TRACE_SPAN);

    Integer responseCode = (Integer)message.get(Message.RESPONSE_CODE);
    if (responseCode == null) {
        responseCode = 200;
    }

    super.stopTraceSpan(requestHeaders, responseHeaders, responseCode, holder);
}
 
Example 3
Source Project: steady   Source File: KerberosTokenInterceptorProvider.java    License: Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    AssertionInfoMap aim = message.get(AssertionInfoMap.class);
    // extract Assertion information
    if (aim != null) {
        Collection<AssertionInfo> ais = aim.get(SP12Constants.KERBEROS_TOKEN);
        if (ais == null) {
            return;
        }
        if (!isRequestor(message)) {
            List<WSHandlerResult> results = 
                CastUtils.cast((List<?>)message.get(WSHandlerConstants.RECV_RESULTS));
            if (results != null && results.size() > 0) {
                parseHandlerResults(results.get(0), message, aim);
            }
        } else {
            //client side should be checked on the way out
            for (AssertionInfo ai : ais) {
                ai.setAsserted(true);
            }                    
        }
    }
}
 
Example 4
Source Project: steady   Source File: HttpsTokenInterceptorProvider.java    License: Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    AssertionInfoMap aim = message.get(AssertionInfoMap.class);
    // extract Assertion information
    if (aim != null) {
        Collection<AssertionInfo> ais = aim.get(SP12Constants.HTTPS_TOKEN);
        if (ais == null) {
            return;
        }
        if (isRequestor(message)) {
            assertHttps(ais, message);
        } else {
            //server side should be checked on the way in
            for (AssertionInfo ai : ais) {
                ai.setAsserted(true);
            }                    
        }
    }
}
 
Example 5
Source Project: cxf   Source File: SoapOutInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
public void handleMessage(SoapMessage message) throws Fault {
    try {
        XMLStreamWriter xtw = message.getContent(XMLStreamWriter.class);
        if (xtw != null) {
            // Write body end
            xtw.writeEndElement();
            // Write Envelope end element
            xtw.writeEndElement();
            xtw.writeEndDocument();

            xtw.flush();
        }
    } catch (XMLStreamException e) {
        if (e.getCause() instanceof EOFException) {
            //Nothing we can do about this, some clients will close the connection early if
            //they fully parse everything they need
        } else {
            SoapVersion soapVersion = message.getVersion();
            throw new SoapFault(new org.apache.cxf.common.i18n.Message("XML_WRITE_EXC", BUNDLE), e,
                                soapVersion.getSender());
        }
    }
}
 
Example 6
Source Project: steady   Source File: IssuedTokenInterceptorProvider.java    License: Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    AssertionInfoMap aim = message.get(AssertionInfoMap.class);
    // extract Assertion information
    if (aim != null) {
        Collection<AssertionInfo> ais = aim.get(SP12Constants.ISSUED_TOKEN);
        if (ais == null) {
            return;
        }
        if (!isRequestor(message)) {
            List<WSHandlerResult> results = 
                CastUtils.cast((List<?>)message.get(WSHandlerConstants.RECV_RESULTS));
            if (results != null && results.size() > 0) {
                parseHandlerResults(results.get(0), message, aim);
            }
        } else {
            //client side should be checked on the way out
            for (AssertionInfo ai : ais) {
                ai.setAsserted(true);
            }                    
        }
    }
}
 
Example 7
Source Project: steady   Source File: SpnegoContextTokenInInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
public void handleMessage(SoapMessage message) throws Fault {
    boolean foundSCT = NegotiationUtils.parseSCTResult(message);
    
    AssertionInfoMap aim = message.get(AssertionInfoMap.class);
    // extract Assertion information
    if (aim != null) {
        Collection<AssertionInfo> ais = aim.get(SP12Constants.SPNEGO_CONTEXT_TOKEN);
        if (ais == null || ais.isEmpty()) {
            return;
        }
        for (AssertionInfo inf : ais) {
            if (foundSCT) {
                inf.setAsserted(true);
            } else {
                inf.setNotAsserted("No SecurityContextToken token found in message.");
            }
        }
    }
}
 
Example 8
Source Project: cxf   Source File: JAXWSMethodInvokerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFaultAvoidHeadersCopy() throws Throwable {
    ExceptionService serviceObject = new ExceptionService();
    Method serviceMethod = ExceptionService.class.getMethod("invoke", new Class[]{});

    Exchange ex = new ExchangeImpl();
    prepareInMessage(ex, false);


    JAXWSMethodInvoker jaxwsMethodInvoker = prepareJAXWSMethodInvoker(ex, serviceObject, serviceMethod);
    try {
        jaxwsMethodInvoker.invoke(ex, new MessageContentsList(new Object[]{}));
        fail("Expected fault");
    } catch (Fault fault) {
        Message outMsg = ex.getOutMessage();
        assertNull(outMsg);
    }
}
 
Example 9
@Override
public void handleMessage(SoapMessage message) throws Fault {
    Fault fault = (Fault) message.getContent(Exception.class);
    LOG.warn("Error: " + fault, fault);

    if (fault.getCause() instanceof SonosSoapFault) {
        SonosSoapFault cause = (SonosSoapFault) fault.getCause();
        fault.setFaultCode(new QName(cause.getFaultCode()));
        fault.setMessage(cause.getFaultCode());

        Document document = DOMUtils.createDocument();
        Element details = document.createElement("detail");
        fault.setDetail(details);

        details.appendChild(document.createElement("ExceptionInfo"));

        Element sonosError = document.createElement("SonosError");
        sonosError.setTextContent(String.valueOf(cause.getSonosError()));
        details.appendChild(sonosError);
    }
}
 
Example 10
@Override
public void handleMessage(SoapMessage msg) throws Fault {
    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);
}
 
Example 11
Source Project: cxf   Source File: JettyHTTPServerEngine.java    License: Apache License 2.0 6 votes vote down vote up
protected void checkRegistedContext(URL url) {

        String path = url.getPath();
        for (String registedPath : registedPaths) {
            if (path.equals(registedPath)) {
                throw new Fault(new Message("ADD_HANDLER_CONTEXT_IS_USED_MSG", LOG, url, registedPath));
            }
            // There are some context path conflicts which could cause the JettyHTTPServerEngine
            // doesn't route the message to the right JettyHTTPHandler
            if (path.equals(HttpUriMapper.getContextName(registedPath))) {
                throw new Fault(new Message("ADD_HANDLER_CONTEXT_IS_USED_MSG", LOG, url, registedPath));
            }
            if (registedPath.equals(HttpUriMapper.getContextName(path))) {
                throw new Fault(new Message("ADD_HANDLER_CONTEXT_CONFILICT_MSG", LOG, url, registedPath));
            }
        }

    }
 
Example 12
Source Project: cxf   Source File: SAMLUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static SamlAssertionWrapper createAssertion(CallbackHandler handler,
                                               SelfSignInfo info) throws Fault {

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(handler, samlCallback);

    try {
        SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
        assertion.signAssertion(info.getUser(),
                                info.getPassword(),
                                info.getCrypto(),
                                false);
        return assertion;
    } catch (Exception ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        LOG.warning(sw.toString());
        throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
    }

}
 
Example 13
Source Project: steady   Source File: SecureConversationInInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
public void handleMessage(SoapMessage message) throws Fault {
    boolean foundSCT = NegotiationUtils.parseSCTResult(message);

    AssertionInfoMap aim = message.get(AssertionInfoMap.class);
    // extract Assertion information
    if (aim != null) {
        Collection<AssertionInfo> ais = aim.get(SP12Constants.SECURE_CONVERSATION_TOKEN);
        if (ais == null || ais.isEmpty()) {
            return;
        }
        for (AssertionInfo inf : ais) {
            if (foundSCT) {
                inf.setAsserted(true);
            } else {
                inf.setNotAsserted("No SecureConversation token found in message.");
            }
        }
    }
}
 
Example 14
Source Project: steady   Source File: IssuedTokenInterceptorProvider.java    License: Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    AssertionInfoMap aim = message.get(AssertionInfoMap.class);
    // extract Assertion information
    if (aim != null) {
        Collection<AssertionInfo> ais = aim.get(SP12Constants.ISSUED_TOKEN);
        if (ais == null) {
            return;
        }
        if (!isRequestor(message)) {
            List<WSHandlerResult> results = 
                CastUtils.cast((List<?>)message.get(WSHandlerConstants.RECV_RESULTS));
            if (results != null && results.size() > 0) {
                parseHandlerResults(results.get(0), message, aim);
            }
        } else {
            //client side should be checked on the way out
            for (AssertionInfo ai : ais) {
                ai.setAsserted(true);
            }                    
        }
    }
}
 
Example 15
Source Project: steady   Source File: CryptoCoverageCheckerTest.java    License: Apache License 2.0 6 votes vote down vote up
private void runInterceptorAndValidate(
        String document,
        Map<String, String> prefixes, 
        List<XPathExpression> xpaths,
        boolean pass) throws Exception {
    
    final Document doc = this.readDocument(document);
    final SoapMessage msg = this.getSoapMessageForDom(doc);
    final CryptoCoverageChecker checker = new CryptoCoverageChecker(prefixes, xpaths);
    final PhaseInterceptor<SoapMessage> wss4jInInterceptor = this.getWss4jInInterceptor();
    
    wss4jInInterceptor.handleMessage(msg);
    
    try {
        checker.handleMessage(msg);
        if (!pass) {
            fail("Passed interceptor erroneously.");
        }
    } catch (Fault e) {
        if (pass) {
            fail("Failed interceptor erroneously.");
        }
        
        assertTrue(e.getMessage().contains("element found matching XPath"));
    }
}
 
Example 16
Source Project: cxf   Source File: XmlSecOutInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message mc) throws Fault {
    try {
        XMLStreamWriter xtw = mc.getContent(XMLStreamWriter.class);
        if (xtw != null) {
            xtw.writeEndDocument();
            xtw.flush();
            xtw.close();
        }

        OutputStream os = (OutputStream) mc.get(OUTPUT_STREAM_HOLDER);
        if (os != null) {
            mc.setContent(OutputStream.class, os);
        }
        mc.removeContent(XMLStreamWriter.class);
    } catch (XMLStreamException e) {
        throw new Fault(e);
    }
}
 
Example 17
Source Project: steady   Source File: SamlTokenInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
public void handleMessage(SoapMessage message) throws Fault {

        boolean isReq = MessageUtils.isRequestor(message);
        boolean isOut = MessageUtils.isOutbound(message);
        
        if (isReq != isOut) {
            //outbound on server side and inbound on client side doesn't need
            //any saml token stuff, assert policies and return
            assertSamlTokens(message);
            return;
        }
        if (isReq) {
            if (message.containsKey(PolicyBasedWSS4JOutInterceptor.SECURITY_PROCESSED)) {
                //The full policy interceptors handled this
                return;
            }
            addSamlToken(message);
        } else {
            if (message.containsKey(WSS4JInInterceptor.SECURITY_PROCESSED)) {
                //The full policy interceptors handled this
                return;
            }
            processSamlToken(message);
        }
    }
 
Example 18
Source Project: steady   Source File: AbstractBindingBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public Crypto getEncryptionCrypto(TokenWrapper wrapper) throws WSSecurityException {
    Crypto crypto = getCrypto(wrapper, SecurityConstants.ENCRYPT_CRYPTO,
                              SecurityConstants.ENCRYPT_PROPERTIES);
    boolean enableRevocation = MessageUtils.isTrue(
                                   message.getContextualProperty(SecurityConstants.ENABLE_REVOCATION));
    if (enableRevocation && crypto != null) {
        CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
        String encrUser = (String)message.getContextualProperty(SecurityConstants.ENCRYPT_USERNAME);
        if (encrUser == null) {
            try {
                encrUser = crypto.getDefaultX509Identifier();
            } catch (WSSecurityException e1) {
                throw new Fault(e1);
            }
        }
        cryptoType.setAlias(encrUser);
        X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
        if (certs != null && certs.length > 0) {
            crypto.verifyTrust(certs, enableRevocation);
        }
    }
    return crypto;

}
 
Example 19
@Override
public void handleMessage(SoapMessage msg) throws Fault {
    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);
}
 
Example 20
Source Project: steady   Source File: CryptoCoverageCheckerTest.java    License: Apache License 2.0 6 votes vote down vote up
private void runInterceptorAndValidate(
        String document,
        Map<String, String> prefixes, 
        List<XPathExpression> xpaths,
        boolean pass) throws Exception {
    
    final Document doc = this.readDocument(document);
    final SoapMessage msg = this.getSoapMessageForDom(doc);
    final CryptoCoverageChecker checker = new CryptoCoverageChecker(prefixes, xpaths);
    final PhaseInterceptor<SoapMessage> wss4jInInterceptor = this.getWss4jInInterceptor();
    
    wss4jInInterceptor.handleMessage(msg);
    
    try {
        checker.handleMessage(msg);
        if (!pass) {
            fail("Passed interceptor erroneously.");
        }
    } catch (Fault e) {
        if (pass) {
            fail("Failed interceptor erroneously.");
        }
        
        assertTrue(e.getMessage().contains("element found matching XPath"));
    }
}
 
Example 21
Source Project: cxf   Source File: WSS4JInInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
public void handleMessage(SoapMessage msg) throws Fault {
    if (msg.containsKey(SECURITY_PROCESSED) || isGET(msg) || msg.getExchange() == null) {
        return;
    }

    Object provider = msg.getExchange().get(Provider.class);
    final boolean useCustomProvider = provider != null && ThreadLocalSecurityProvider.isInstalled();
    try {
        if (useCustomProvider) {
            ThreadLocalSecurityProvider.setProvider((Provider)provider);
        }
        handleMessageInternal(msg);
    } finally {
        if (useCustomProvider) {
            ThreadLocalSecurityProvider.unsetProvider();
        }
    }
}
 
Example 22
Source Project: cxf   Source File: StaxDataBinding.java    License: Apache License 2.0 6 votes vote down vote up
public void write(Object obj, XMLStreamWriter writer) {
    try {
        if (obj instanceof XMLStreamReader) {
            XMLStreamReader xmlStreamReader = (XMLStreamReader) obj;
            StaxUtils.copy(xmlStreamReader, writer);
            xmlStreamReader.close();
        } else if (obj instanceof XMLStreamWriterCallback) {
            ((XMLStreamWriterCallback) obj).write(writer);
        } else {
            throw new UnsupportedOperationException("Data types of "
                                                    + obj.getClass() + " are not supported.");
        }
    } catch (XMLStreamException e) {
        throw new Fault("COULD_NOT_READ_XML_STREAM", LOG, e);
    }
}
 
Example 23
@Override
public void handleMessage(SoapMessage msg) throws Fault {
    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);
}
 
Example 24
Source Project: steady   Source File: HttpsTokenInterceptorProvider.java    License: Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    AssertionInfoMap aim = message.get(AssertionInfoMap.class);
    // extract Assertion information
    if (aim != null) {
        Collection<AssertionInfo> ais = aim.get(SP12Constants.HTTPS_TOKEN);
        if (ais == null) {
            return;
        }
        if (isRequestor(message)) {
            assertHttps(ais, message);
        } else {
            //server side should be checked on the way in
            for (AssertionInfo ai : ais) {
                ai.setAsserted(true);
            }                    
        }
    }
}
 
Example 25
Source Project: cxf   Source File: JAXRSSoapBookTest.java    License: Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    InputStream is = message.getContent(InputStream.class);
    if (is == null) {
        return;
    }
    byte[] payload;
    try {
        // input stream will be closed by readBytesFromStream()
        payload = IOUtils.readBytesFromStream(is);
        assertNotNull("payload was null", payload);
        assertTrue("payload was EMPTY", payload.length > 0);
        message.setContent(InputStream.class, new ByteArrayInputStream(payload));
    } catch (Exception e) {
        String error = "Failed to read the stream properly due to " + e.getMessage();
        assertNotNull(error, e);
    }
}
 
Example 26
Source Project: steady   Source File: SpnegoContextTokenInInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
public void handleMessage(SoapMessage message) throws Fault {
    boolean foundSCT = NegotiationUtils.parseSCTResult(message);
    
    AssertionInfoMap aim = message.get(AssertionInfoMap.class);
    // extract Assertion information
    if (aim != null) {
        Collection<AssertionInfo> ais = aim.get(SP12Constants.SPNEGO_CONTEXT_TOKEN);
        if (ais == null || ais.isEmpty()) {
            return;
        }
        for (AssertionInfo inf : ais) {
            if (foundSCT) {
                inf.setAsserted(true);
            } else {
                inf.setNotAsserted("No SecurityContextToken token found in message.");
            }
        }
    }
}
 
Example 27
Source Project: cxf   Source File: SSLNettyServerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handleMessage(Message message) throws Fault {
    if (!MessageUtils.isRequestor(message)) {
        // just check the request message
        TLSSessionInfo info = message.get(TLSSessionInfo.class);
        assertNotNull(info);
    }
}
 
Example 28
Source Project: servicemix   Source File: EnableCORSInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handleMessage(Message message) throws Fault {
    Map<String, List<String>> headers = Headers.getSetProtocolHeaders(message);
    try {
        //Access-Control-Allow-Origin:* Access-Control-Allow-Methods:POST,GET
        headers.put("Access-Control-Allow-Origin", Arrays.asList("*"));
        headers.put("Access-Control-Allow-Methods", Arrays.asList("POST", "GET"));
    } catch (Exception ce) {
        throw new Fault(ce);
    }
}
 
Example 29
Source Project: steady   Source File: WSS4JOutInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
public void handleMessage(SoapMessage mc) throws Fault {
    //must turn off mtom when using WS-Sec so binary is inlined so it can
    //be properly signed/encrypted/etc...
    if (!mtomEnabled) {
        mc.put(org.apache.cxf.message.Message.MTOM_ENABLED, false);
    }
    
    if (mc.getContent(SOAPMessage.class) == null) {
        saajOut.handleMessage(mc);
    }
    
    mc.getInterceptorChain().add(ending);
}
 
Example 30
@Override
public void handleMessage(Message message) throws Fault
{

    LOGGER.info("In handleMessage");
    LOGGER.info("Message --> " + message);

    String name = null;
    String password = null;

    AuthUser user = null;

    AuthorizationPolicy policy = (AuthorizationPolicy) message.get(AuthorizationPolicy.class);
    if (policy != null)
    {
        name = policy.getUserName();
        password = policy.getPassword();

        LOGGER.info("Requesting user: " + name);
        // TODO: read user from DB
        // if user and pw do not match, throw new AuthenticationException("Unauthorized");

        user = new AuthUser();
        user.setName(name);

    }
    else
    {
        LOGGER.info("No requesting user -- GUEST access");
    }

    GeofenceSecurityContext securityContext = new GeofenceSecurityContext();
    GeofencePrincipal principal = (user != null) ? new GeofencePrincipal(user) : GeofencePrincipal.createGuest();
    securityContext.setPrincipal(principal);

    message.put(SecurityContext.class, securityContext);
}