Java Code Examples for org.apache.cxf.endpoint.Endpoint#get()

The following examples show how to use org.apache.cxf.endpoint.Endpoint#get() . 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 File: AbstractMetricsInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void addEndpointMetrics(ExchangeMetrics ctx, Message m) {
    Endpoint ep = m.getExchange().getEndpoint();
    Object o = ep.get(MetricsContext.class.getName());
    if (o == null) {
        synchronized (ep) {
            o = createEndpointMetrics(m);
        }
    }
    if (o instanceof List) {
        List<MetricsContext> list = CastUtils.cast((List<?>)o);
        for (MetricsContext c : list) {
            ctx.addContext(c);
        }
    } else if (o instanceof MetricsContext) {
        ctx.addContext((MetricsContext)o);
    }
}
 
Example 2
Source File: ProtobufMessageInInterceptor.java    From fuchsia with Apache License 2.0 6 votes vote down vote up
/**
 */
public void handleMessage(Message message) throws Fault {
    Endpoint endpoint = message.getExchange().get(Endpoint.class);
    @SuppressWarnings(value = "unchecked")
    Class<? extends com.google.protobuf.Message> messageClass = (Class) message.getExchange().get(IN_MESSAGE_CLASS);

    if (messageClass == null) {
        messageClass = (Class) endpoint
                .get(IN_MESSAGE_CLASS);
    }

    InputStream in = message.getContent(InputStream.class);

    try {
        com.google.protobuf.Message m = (com.google.protobuf.Message) messageClass.getMethod("parseFrom",
                InputStream.class).invoke(null, in);
        message.setContent(com.google.protobuf.Message.class, m);
    } catch (Exception e) {
        log.error("Failed to invoke message method from protobuffer.",e);
        throw new RuntimeException(e);
    }
}
 
Example 3
Source File: DOM4JProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private Message createMessage(ProviderFactory factory) {
    Message m = new MessageImpl();
    m.put("org.apache.cxf.http.case_insensitive_queries", false);
    Exchange e = new ExchangeImpl();
    m.setExchange(e);
    e.setInMessage(m);
    Endpoint endpoint = EasyMock.createMock(Endpoint.class);
    endpoint.getEndpointInfo();
    EasyMock.expectLastCall().andReturn(null).anyTimes();
    endpoint.get(Application.class.getName());
    EasyMock.expectLastCall().andReturn(null);
    endpoint.size();
    EasyMock.expectLastCall().andReturn(0).anyTimes();
    endpoint.isEmpty();
    EasyMock.expectLastCall().andReturn(true).anyTimes();
    endpoint.get(ServerProviderFactory.class.getName());
    EasyMock.expectLastCall().andReturn(factory).anyTimes();
    EasyMock.replay(endpoint);
    e.put(Endpoint.class, endpoint);
    return m;
}
 
Example 4
Source File: DOM4JProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private Message createMessage(boolean suppress) {
    ProviderFactory factory = ServerProviderFactory.getInstance();
    Message m = new MessageImpl();
    m.put("org.apache.cxf.http.case_insensitive_queries", false);
    Exchange e = new ExchangeImpl();
    e.put(DOM4JProvider.SUPPRESS_XML_DECLARATION, suppress);
    m.setExchange(e);
    e.setInMessage(m);
    Endpoint endpoint = EasyMock.createMock(Endpoint.class);
    endpoint.getEndpointInfo();
    EasyMock.expectLastCall().andReturn(null).anyTimes();
    endpoint.get(Application.class.getName());
    EasyMock.expectLastCall().andReturn(null);
    endpoint.size();
    EasyMock.expectLastCall().andReturn(0).anyTimes();
    endpoint.isEmpty();
    EasyMock.expectLastCall().andReturn(true).anyTimes();
    endpoint.get(ServerProviderFactory.class.getName());
    EasyMock.expectLastCall().andReturn(factory).anyTimes();
    EasyMock.replay(endpoint);
    e.put(Endpoint.class, endpoint);
    return m;
}
 
Example 5
Source File: AbstractMetricsInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private Object createEndpointMetrics(Message m) {
    final Endpoint ep = m.getExchange().getEndpoint();
    Object o = ep.get(MetricsContext.class.getName());
    if (o == null) {
        List<MetricsContext> contexts = new ArrayList<>();
        for (MetricsProvider p : getMetricProviders(m.getExchange().getBus())) {
            MetricsContext c = p.createEndpointContext(ep, MessageUtils.isRequestor(m),
                                                       (String)m.getContextualProperty(MetricsProvider.CLIENT_ID));
            if (c != null) {
                contexts.add(c);
            }
            if (c instanceof Closeable) {
                ep.addCleanupHook((Closeable)c);
            }
        }
        if (contexts.size() == 1) {
            o = contexts.get(0);
        } else {
            o = contexts;
        }
        ep.put(MetricsContext.class.getName(), o);
    }
    return o;
}
 
Example 6
Source File: CodahaleMetricsProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
StringBuilder getBaseServiceName(Endpoint endpoint, boolean isClient, String clientId) {
    StringBuilder buffer = new StringBuilder();
    if (endpoint.get("org.apache.cxf.management.service.counter.name") != null) {
        buffer.append((String)endpoint.get("org.apache.cxf.management.service.counter.name"));
    } else {
        Service service = endpoint.getService();

        String serviceName = "\"" + escapePatternChars(service.getName().toString()) + "\"";
        String portName = "\"" + endpoint.getEndpointInfo().getName().getLocalPart() + "\"";

        buffer.append(ManagementConstants.DEFAULT_DOMAIN_NAME).append(':');
        buffer.append(ManagementConstants.BUS_ID_PROP + "=" + bus.getId() + ",");
        buffer.append(ManagementConstants.TYPE_PROP).append("=Metrics");
        if (isClient) {
            buffer.append(".Client,");
        } else {
            buffer.append(".Server,");
        }
        buffer.append(ManagementConstants.SERVICE_NAME_PROP + "=" + serviceName + ",");
        buffer.append(ManagementConstants.PORT_NAME_PROP + "=" + portName + ",");
        if (clientId != null) {
            buffer.append("Client=" + clientId + ",");
        }
    }
    return buffer;
}
 
Example 7
Source File: MAPAggregatorImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
* Determine if the use of addressing is indicated by the presence of a
* the usingAddressing attribute.
*
* @param message the current message
* @pre message is outbound
* @pre requestor role
*/
private boolean hasUsingAddressing(Message message) {
    boolean ret = false;
    Endpoint endpoint = message.getExchange().getEndpoint();
    if (null != endpoint) {
        Boolean b = (Boolean)endpoint.get(USING_ADDRESSING);
        if (null == b) {
            EndpointInfo endpointInfo = endpoint.getEndpointInfo();
            List<ExtensibilityElement> endpointExts = endpointInfo != null ? endpointInfo
                .getExtensors(ExtensibilityElement.class) : null;
            List<ExtensibilityElement> bindingExts = endpointInfo != null
                && endpointInfo.getBinding() != null ? endpointInfo
                .getBinding().getExtensors(ExtensibilityElement.class) : null;
            List<ExtensibilityElement> serviceExts = endpointInfo != null
                && endpointInfo.getService() != null ? endpointInfo
                .getService().getExtensors(ExtensibilityElement.class) : null;
            ret = hasUsingAddressing(endpointExts) || hasUsingAddressing(bindingExts)
                         || hasUsingAddressing(serviceExts);
            b = ret ? Boolean.TRUE : Boolean.FALSE;
            endpoint.put(USING_ADDRESSING, b);
        } else {
            ret = b.booleanValue();
        }
    }
    return ret;
}
 
Example 8
Source File: RMManager.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 9
Source File: RMManager.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 10
Source File: AbstractMetricsInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> getRestMetricsMap(Endpoint e) {
    synchronized (e) {
        Object mmo = e.get(REST_METRICS_MAP);
        if (mmo == null) {
            e.put(REST_METRICS_MAP, new ConcurrentHashMap<String, Object>());
            mmo = e.get(REST_METRICS_MAP);
        }
        return CastUtils.cast((Map<?, ?>)mmo);
    }
}
 
Example 11
Source File: ProviderFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static ProviderFactory getInstance(Message m) {
    Endpoint e = m.getExchange().getEndpoint();

    Message outM = m.getExchange().getOutMessage();
    boolean isClient = outM != null && MessageUtils.isRequestor(outM);
    String name = isClient ? CLIENT_FACTORY_NAME : SERVER_FACTORY_NAME;

    return (ProviderFactory)e.get(name);
}
 
Example 12
Source File: TokenTestUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void verifyToken(DoubleItPortType port) throws Exception {
    Client client = ClientProxy.getClient(port);
    Endpoint ep = client.getEndpoint();
    String id = (String)ep.get(SecurityConstants.TOKEN_ID);
    TokenStore store = (TokenStore)ep.getEndpointInfo().getProperty(TokenStore.class.getName());
    org.apache.cxf.ws.security.tokenstore.SecurityToken tok = store.getToken(id);
    assertNotNull(tok);
    STSClient sts = (STSClient)ep.get(SecurityConstants.STS_CLIENT);

    List<SecurityToken> validTokens = sts.validateSecurityToken(tok);
    assertTrue(validTokens != null && !validTokens.isEmpty());

    //mess with the token a bit to force it to fail to validate
    Element e = tok.getToken();
    Element e2 = DOMUtils.getFirstChildWithName(e, e.getNamespaceURI(), "Conditions");
    String nb = e2.getAttributeNS(null, "NotBefore");
    String noa = e2.getAttributeNS(null, "NotOnOrAfter");
    nb = "2010" + nb.substring(4);
    noa = "2010" + noa.substring(4);
    e2.setAttributeNS(null, "NotBefore", nb);
    e2.setAttributeNS(null, "NotOnOrAfter", noa);
    try {
        sts.validateSecurityToken(tok);
        fail("Failure expected on an invalid token");
    } catch (org.apache.cxf.ws.security.trust.TrustException ex) {
        // expected
    }
}
 
Example 13
Source File: CachingTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testImminentExpiry() throws Exception {

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = CachingTest.class.getResource("cxf-client.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    URL wsdl = CachingTest.class.getResource("DoubleIt.wsdl");
    Service service = Service.create(wsdl, SERVICE_QNAME);
    QName portQName = new QName(NAMESPACE, "DoubleItTransportSAML1Port");
    DoubleItPortType port =
        service.getPort(portQName, DoubleItPortType.class);
    ((BindingProvider)port).getRequestContext().put("thread.local.request.context", "true");
    updateAddressPort(port, PORT);

    // Make a successful invocation
    doubleIt(port, 25);

    Client client = ClientProxy.getClient(port);
    Endpoint ep = client.getEndpoint();
    String id = (String)ep.get(SecurityConstants.TOKEN_ID);
    TokenStore store = (TokenStore)ep.getEndpointInfo().getProperty(TokenStore.class.getName());
    SecurityToken tok = store.getToken(id);
    assertNotNull(tok);

    // Make the token "about to expire"
    tok.setExpires(Instant.now().plusSeconds(5L));
    assertTrue(tok.isAboutToExpire(10L));

    doubleIt(port, 25);

    ((java.io.Closeable)port).close();
    bus.shutdown(true);
}
 
Example 14
Source File: ServerCachingTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testServerSideSAMLTokenCaching() throws Exception {

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = ServerCachingTest.class.getResource("cxf-client.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    URL wsdl = ServerCachingTest.class.getResource("DoubleIt.wsdl");
    Service service = Service.create(wsdl, SERVICE_QNAME);
    QName portQName = new QName(NAMESPACE, "DoubleItTransportSAML1AlternativePort");
    DoubleItPortType port =
        service.getPort(portQName, DoubleItPortType.class);
    ((BindingProvider)port).getRequestContext().put("thread.local.request.context", "true");
    updateAddressPort(port, PORT);

    // Make an initial successful invocation
    doubleIt(port, 25);

    // Store the SAML Assertion that was obtained from the STS
    Client client = ClientProxy.getClient(port);
    Endpoint ep = client.getEndpoint();
    String id = (String)ep.get(SecurityConstants.TOKEN_ID);
    TokenStore store = (TokenStore)ep.getEndpointInfo().getProperty(TokenStore.class.getName());
    SecurityToken tok = store.getToken(id);
    assertNotNull(tok);
    Element storedToken = tok.getToken();

    // Get another security token by invoking on the STS directly and save it on the client port
    SecurityToken token =
        requestSecurityToken(SAML1_TOKEN_TYPE, PUBLIC_KEY_KEYTYPE, bus, DEFAULT_ADDRESS);
    assertNotNull(token);
    tok.setToken(token.getToken());

    // Try another invocation - this will fail as the STSClient on the server side is disabled
    // after the first invocation
    try {
        doubleIt(port, 30);
        fail("Failure expected as the STSClient on the server side is null");
    } catch (Exception ex) {
        // expected
    }
    // Try again using the original SAML token - this should work as it should be cached by the service
    tok.setToken(storedToken);
    doubleIt(port, 35);

    ((java.io.Closeable)port).close();
    bus.shutdown(true);
}
 
Example 15
Source File: ServerProviderFactory.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static ServerProviderFactory getInstance(Message m) {
    Endpoint e = m.getExchange().getEndpoint();
    return (ServerProviderFactory)e.get(SERVER_FACTORY_NAME);
}
 
Example 16
Source File: MicroProfileClientProviderFactory.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static MicroProfileClientProviderFactory getInstance(Endpoint e) {
    return (MicroProfileClientProviderFactory)e.get(CLIENT_FACTORY_NAME);
}
 
Example 17
Source File: ClientProviderFactory.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static ClientProviderFactory getInstance(Endpoint e) {
    return (ClientProviderFactory)e.get(CLIENT_FACTORY_NAME);
}
 
Example 18
Source File: WadlGenerator.java    From cxf with Apache License 2.0 4 votes vote down vote up
public Response getExistingWadl(Message m, UriInfo ui, MediaType mt) {
    Endpoint ep = m.getExchange().getEndpoint();
    if (ep != null) {
        String loc = (String)ep.get(JAXRSUtils.DOC_LOCATION);
        if (loc != null) {
            try {
                InputStream is = ResourceUtils.getResourceStream(loc, (Bus)ep.get(Bus.class.getName()));
                if (is != null) {
                    Object contextProp = m.getContextualProperty(CONVERT_WADL_RESOURCES_TO_DOM);
                    boolean doConvertResourcesToDOM = contextProp == null
                        ? convertResourcesToDOM : PropertyUtils.isTrue(contextProp);
                    if (!doConvertResourcesToDOM || isJson(mt)) {
                        return Response.ok(is, mt).build();
                    }
                    Document wadlDoc = StaxUtils.read(is);
                    Element appEl = wadlDoc.getDocumentElement();

                    List<Element> grammarEls = DOMUtils.getChildrenWithName(appEl, WadlGenerator.WADL_NS,
                                                                            "grammars");
                    if (grammarEls.size() == 1) {
                        handleExistingDocRefs(DOMUtils.getChildrenWithName(grammarEls.get(0),
                                                                           WadlGenerator.WADL_NS,
                                                                           "include"), "href", loc, "",
                                              m, ui);
                    }

                    List<Element> resourcesEls = DOMUtils.getChildrenWithName(appEl,
                                                                              WadlGenerator.WADL_NS,
                                                                              "resources");
                    if (resourcesEls.size() == 1) {
                        DOMUtils.setAttribute(resourcesEls.get(0), "base", getBaseURI(m, ui));

                        List<Element> resourceEls = DOMUtils.getChildrenWithName(resourcesEls.get(0),
                                                                                 WadlGenerator.WADL_NS,
                                                                                 "resource");
                        handleExistingDocRefs(resourceEls, "type", loc, "", m, ui);
                        return finalizeExistingWadlResponse(wadlDoc, m, ui, mt);
                    }

                }
            } catch (Exception ex) {
                throw ExceptionUtils.toInternalServerErrorException(ex, null);
            }
        }
    }
    return null;
}
 
Example 19
Source File: Stax2ValidationUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Create woodstox validator for a schema set.
 *
 * @throws XMLStreamException
 */
private XMLValidationSchema getValidator(Endpoint endpoint, ServiceInfo serviceInfo)
        throws XMLStreamException {
    synchronized (endpoint) {
        XMLValidationSchema ret = (XMLValidationSchema) endpoint.get(KEY);
        if (ret == null) {
            if (endpoint.containsKey(KEY)) {
                return null;
            }
            Map<String, Source> sources = new TreeMap<>();

            for (SchemaInfo schemaInfo : serviceInfo.getSchemas()) {
                XmlSchema sch = schemaInfo.getSchema();
                String uri = sch.getTargetNamespace();
                if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(uri)) {
                    continue;
                }

                if (sch.getTargetNamespace() == null && !sch.getExternals().isEmpty()) {
                    for (XmlSchemaExternal xmlSchemaExternal : sch.getExternals()) {
                        addSchema(sources, xmlSchemaExternal.getSchema(),
                                getElement(xmlSchemaExternal.getSchema().getSourceURI()));
                    }
                    continue;
                } else if (sch.getTargetNamespace() == null) {
                    throw new IllegalStateException("An Schema without imports must have a targetNamespace");
                }

                addSchema(sources, sch, schemaInfo.getElement());
            }

            try {
                // I don't think that we need the baseURI.
                Method method = multiSchemaFactory.getMethod("createSchema", String.class, Map.class);
                ret = (XMLValidationSchema) method.invoke(multiSchemaFactory.newInstance(), null, sources);
                endpoint.put(KEY, ret);
            } catch (Throwable t) {
                LOG.log(Level.INFO, "Problem loading schemas. Falling back to slower method.", ret);
                endpoint.put(KEY, null);
            }
        }
        return ret;
    }
}