Java Code Examples for org.apache.cxf.jaxrs.utils.InjectionUtils

The following examples show how to use org.apache.cxf.jaxrs.utils.InjectionUtils. 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: JAXRSCdiResourceExtension.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> void collect(@Observes final ProcessBean< T > event) {
    if (event.getAnnotated().isAnnotationPresent(ApplicationPath.class)) {
        applicationBeans.add(event.getBean());
    } else if (event.getAnnotated().isAnnotationPresent(Path.class)) {
        serviceBeans.add(event.getBean());
    } else if (event.getAnnotated().isAnnotationPresent(Provider.class)) {
        providerBeans.add(event.getBean());
    } else if (event.getBean().getTypes().contains(javax.ws.rs.core.Feature.class)) {
        providerBeans.add(event.getBean());
    } else if (event.getBean().getTypes().contains(Feature.class)) {
        featureBeans.add((Bean< ? extends Feature >)event.getBean());
    } else if (CdiBusBean.CXF.equals(event.getBean().getName())
            && Bus.class.isAssignableFrom(event.getBean().getBeanClass())) {
        hasBus = true;
    } else if (event.getBean().getQualifiers().contains(DEFAULT)) {
        event.getBean().getTypes().stream()
            .filter(e -> Object.class != e && InjectionUtils.STANDARD_CONTEXT_CLASSES.contains(e.getTypeName()))
            .findFirst()
            .ifPresent(type -> existingStandardClasses.add(type.getTypeName()));
    }
}
 
Example 2
Source Project: cxf   Source File: SingletonResourceProvider.java    License: Apache License 2.0 6 votes vote down vote up
public void init(Endpoint ep) {
    if (resourceInstance instanceof Constructor) {
        Constructor<?> c = (Constructor<?>)resourceInstance;
        Message m = new MessageImpl();
        ExchangeImpl exchange = new ExchangeImpl();
        exchange.put(Endpoint.class, ep);
        m.setExchange(exchange);
        Object[] values = 
            ResourceUtils.createConstructorArguments(c, m, false, Collections.emptyMap());
        try {
            resourceInstance = values.length > 0 ? c.newInstance(values) : c.newInstance(new Object[]{});
        } catch (Exception ex) {
            throw new ServiceConstructionException(ex);
        }
    }
    if (callPostConstruct) {
        InjectionUtils.invokeLifeCycleMethod(resourceInstance,
            ResourceUtils.findPostConstructMethod(ClassHelper.getRealClass(resourceInstance)));
    }    
}
 
Example 3
Source Project: cxf   Source File: ClassResourceInfo.java    License: Apache License 2.0 6 votes vote down vote up
public ClassResourceInfo(ClassResourceInfo cri) {
    super(cri.getBus());
    if (cri.isCreatedFromModel() && !InjectionUtils.isConcreteClass(cri.getServiceClass())) {
        this.root = cri.root;
        this.serviceClass = cri.serviceClass;
        this.uriTemplate = cri.uriTemplate;
        this.methodDispatcher = new MethodDispatcher(cri.methodDispatcher, this);
        this.subResources = cri.subResources;
        //CHECKSTYLE:OFF
        this.paramFields = cri.paramFields;
        this.paramMethods = cri.paramMethods;
        //CHECKSTYLE:ON
        this.enableStatic = true;
        this.nameBindings = cri.nameBindings;
        this.parent = cri.parent;
    } else {
        throw new IllegalArgumentException();
    }

}
 
Example 4
Source Project: cxf   Source File: AbstractResourceInfo.java    License: Apache License 2.0 6 votes vote down vote up
private void findContextFields(Class<?> cls, Object provider) {
    if (cls == Object.class || cls == null) {
        return;
    }
    for (Field f : ReflectionUtil.getDeclaredFields(cls)) {
        for (Annotation a : f.getAnnotations()) {
            if (a.annotationType() == Context.class
                && (f.getType().isInterface() || f.getType() == Application.class)) {
                contextFields = addContextField(contextFields, f);
                checkContextClass(f.getType());
                if (!InjectionUtils.VALUE_CONTEXTS.contains(f.getType().getName())) {
                    addToMap(getFieldProxyMap(true), f, getFieldThreadLocalProxy(f, provider));
                }
            }
        }
    }
    findContextFields(cls.getSuperclass(), provider);
}
 
Example 5
Source Project: cxf   Source File: AbstractResourceInfo.java    License: Apache License 2.0 6 votes vote down vote up
private static ThreadLocalProxy<?> getFieldThreadLocalProxy(Field f, Object provider) {
    if (provider != null) {
        Object proxy = null;
        synchronized (provider) {
            try {
                proxy = InjectionUtils.extractFieldValue(f, provider);
            } catch (Throwable t) {
                // continue
            }
            if (!(proxy instanceof ThreadLocalProxy)) {
                proxy = InjectionUtils.createThreadLocalProxy(f.getType());
                InjectionUtils.injectFieldValue(f, provider, proxy);
            }
        }
        return (ThreadLocalProxy<?>)proxy;
    }
    return InjectionUtils.createThreadLocalProxy(f.getType());
}
 
Example 6
Source Project: cxf   Source File: AbstractResourceInfo.java    License: Apache License 2.0 6 votes vote down vote up
private static ThreadLocalProxy<?> getMethodThreadLocalProxy(Method m, Object provider) {
    if (provider != null) {
        Object proxy = null;
        synchronized (provider) {
            try {
                proxy = InjectionUtils.extractFromMethod(provider,
                                                         InjectionUtils.getGetterFromSetter(m),
                                                         false);
            } catch (Throwable t) {
                // continue
            }
            if (!(proxy instanceof ThreadLocalProxy)) {
                proxy = InjectionUtils.createThreadLocalProxy(m.getParameterTypes()[0]);
                InjectionUtils.injectThroughMethod(provider, m, proxy);
            }
        }
        return (ThreadLocalProxy<?>)proxy;
    }
    return InjectionUtils.createThreadLocalProxy(m.getParameterTypes()[0]);
}
 
Example 7
Source Project: cxf   Source File: ProviderFactory.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> ContextProvider<T> createContextProvider(Type contextType,
                                                    Message m) {
    Class<?> contextCls = InjectionUtils.getActualType(contextType);
    if (contextCls == null) {
        return null;
    }
    for (ProviderInfo<ContextProvider<?>> cr : contextProviders) {
        Type[] types = cr.getProvider().getClass().getGenericInterfaces();
        for (Type t : types) {
            if (t instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType)t;
                Type[] args = pt.getActualTypeArguments();
                if (args.length > 0) {
                    Class<?> argCls = InjectionUtils.getActualType(args[0]);

                    if (argCls != null && argCls.isAssignableFrom(contextCls)) {
                        return (ContextProvider<T>)cr.getProvider();
                    }
                }
            }
        }
    }
    return null;
}
 
Example 8
Source Project: cxf   Source File: ProviderFactory.java    License: Apache License 2.0 6 votes vote down vote up
protected static int compareClasses(Class<?> expectedCls, Object o1, Object o2) {
    Class<?> cl1 = ClassHelper.getRealClass(o1);
    Class<?> cl2 = ClassHelper.getRealClass(o2);
    Type[] types1 = getGenericInterfaces(cl1, expectedCls);
    Type[] types2 = getGenericInterfaces(cl2, expectedCls);
    if (types1.length == 0 && types2.length == 0) {
        return 0;
    } else if (types1.length == 0 && types2.length > 0) {
        return 1;
    } else if (types1.length > 0 && types2.length == 0) {
        return -1;
    }

    Class<?> realClass1 = InjectionUtils.getActualType(types1[0]);
    Class<?> realClass2 = InjectionUtils.getActualType(types2[0]);
    if (realClass1 == realClass2) {
        return 0;
    }
    if (realClass1.isAssignableFrom(realClass2)) {
        // subclass should go first
        return 1;
    }
    return -1;
}
 
Example 9
Source Project: cxf   Source File: ProviderFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static Type[] getGenericInterfaces(Class<?> cls, Class<?> expectedClass,
                                           Class<?> commonBaseCls) {
    if (Object.class == cls) {
        return new Type[]{};
    }
    if (expectedClass != null) {
        Type genericSuperType = cls.getGenericSuperclass();
        if (genericSuperType instanceof ParameterizedType) {
            Class<?> actualType = InjectionUtils.getActualType(genericSuperType);
            if (actualType != null && actualType.isAssignableFrom(expectedClass)) {
                return new Type[]{genericSuperType};
            } else if (commonBaseCls != null && commonBaseCls != Object.class
                       && commonBaseCls.isAssignableFrom(expectedClass)
                       && commonBaseCls.isAssignableFrom(actualType)
                       || expectedClass.isAssignableFrom(actualType)) {
                return new Type[]{};
            }
        }
    }
    Type[] types = cls.getGenericInterfaces();
    if (types.length > 0) {
        return types;
    }
    return getGenericInterfaces(cls.getSuperclass(), expectedClass, commonBaseCls);
}
 
Example 10
Source Project: cxf   Source File: XSLTJaxbProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] anns, MediaType mt) {
    if (!super.isReadable(type, genericType, anns, mt)) {
        return false;
    }

    if (InjectionUtils.isSupportedCollectionOrArray(type)) {
        return supportJaxbOnly;
    }

    // if the user has set the list of in classes and a given class
    // is in that list then it can only be handled by the template
    if (inClassCanBeHandled(type.getName()) || inClassesToHandle == null && !supportJaxbOnly) {
        return inTemplatesAvailable(type, anns, mt);
    }
    return supportJaxbOnly;
}
 
Example 11
Source Project: cxf   Source File: XSLTJaxbProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] anns, MediaType mt) {
    // JAXB support is required
    if (!super.isWriteable(type, genericType, anns, mt)) {
        return false;
    }
    if (InjectionUtils.isSupportedCollectionOrArray(type)) {
        return supportJaxbOnly;
    }

    // if the user has set the list of out classes and a given class
    // is in that list then it can only be handled by the template
    if (outClassCanBeHandled(type.getName()) || outClassesToHandle == null && !supportJaxbOnly) {
        return outTemplatesAvailable(type, anns, mt);
    }
    return supportJaxbOnly;
}
 
Example 12
Source Project: cxf   Source File: PrimitiveTextProvider.java    License: Apache License 2.0 6 votes vote down vote up
public T readFrom(Class<T> type, Type genType, Annotation[] anns, MediaType mt,
                  MultivaluedMap<String, String> headers, InputStream is) throws IOException {
    String string = IOUtils.toString(is, HttpUtils.getEncoding(mt, StandardCharsets.UTF_8.name()));
    if (StringUtils.isEmpty(string)) {
        reportEmptyContentLength();
    }
    if (type == Character.class) {
        char character = string.charAt(0);
        return type.cast(Character.valueOf(character));
    }
    return InjectionUtils.handleParameter(
                string,
                false,
                type,
                genType,
                anns,
                ParameterType.REQUEST_BODY, null);

}
 
Example 13
Source Project: cxf   Source File: JAXRSServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void createMessagePartInfo(OperationInfo oi, Class<?> type, QName qname, Method m,
                                   boolean input) {
    if (type == void.class || Source.class.isAssignableFrom(type)) {
        return;
    }
    if (InjectionUtils.isPrimitive(type) || Response.class == type) {
        return;
    }
    QName mName = new QName(qname.getNamespaceURI(),
                            (input ? "in" : "out") + m.getName());
    MessageInfo ms = oi.createMessage(mName,
                                       input ? MessageInfo.Type.INPUT : MessageInfo.Type.OUTPUT);
    if (input) {
        oi.setInput("in", ms);
    } else {
        oi.setOutput("out", ms);
    }
    QName mpQName = JAXRSUtils.getClassQName(type);
    MessagePartInfo mpi = ms.addMessagePart(mpQName);
    mpi.setConcreteName(mpQName);
    mpi.setTypeQName(mpQName);
    mpi.setTypeClass(type);
}
 
Example 14
Source Project: cxf   Source File: JAXRSServerFactoryBean.java    License: Apache License 2.0 6 votes vote down vote up
protected void injectContexts(ServerProviderFactory factory, ApplicationInfo fallback) {
    // Sometimes the application provider (ApplicationInfo) is injected through
    // the endpoint, not JAXRSServerFactoryBean (like for example OpenApiFeature
    // or Swagger2Feature do). As such, without consulting the endpoint, the injection
    // may not work properly.
    final ApplicationInfo appInfoProvider = (appProvider == null) ? fallback : appProvider;
    final Application application = appInfoProvider == null ? null : appInfoProvider.getProvider();

    for (ClassResourceInfo cri : serviceFactory.getClassResourceInfo()) {
        if (cri.isSingleton()) {
            InjectionUtils.injectContextProxiesAndApplication(cri,
                                                cri.getResourceProvider().getInstance(null),
                                                application,
                                                factory);
        }
    }
    if (application != null) {
        InjectionUtils.injectContextProxiesAndApplication(appInfoProvider,
                                                          application, null, null);
    }
}
 
Example 15
Source Project: cxf   Source File: XMLSource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Find the list of matching XML nodes and convert them into
 * an array of instances of the provided class.
 * The default JAXB MessageBodyReader is currently used  in case of non-primitive types.
 *
 * @param expression XPath expression
 * @param namespaces the namespaces map, prefixes which are used in the XPath expression
 *        are the keys, namespace URIs are the values; note, the prefixes do not have to match
 *        the actual ones used in the XML instance.
 * @param cls class of the node
 * @return the array of instances representing the matching nodes
 */
@SuppressWarnings("unchecked")
public <T> T[] getNodes(String expression, Map<String, String> namespaces, Class<T> cls) {

    NodeList nodes = (NodeList)evaluate(expression, namespaces, XPathConstants.NODESET);
    if (nodes == null || nodes.getLength() == 0) {
        return null;
    }
    T[] values = (T[])Array.newInstance(cls, nodes.getLength());
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (InjectionUtils.isPrimitive(cls)) {
            values[i] = (T)readPrimitiveValue(node, cls);
        } else {
            values[i] = readNode(node, cls);
        }
    }
    return values;
}
 
Example 16
Source Project: cxf   Source File: MicroProfileClientProxyImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Type getGenericReturnType(Class<?> serviceCls, Method method, Class<?> returnType) {
    final Type genericReturnType = super.getGenericReturnType(serviceCls, method, returnType);
    
    if (genericReturnType instanceof ParameterizedType) {
        final ParameterizedType pt = (ParameterizedType)genericReturnType;
        if (CompletionStage.class.isAssignableFrom(InjectionUtils.getRawType(pt))) {
            final Type[] actualTypeArguments = pt.getActualTypeArguments();
            if (actualTypeArguments.length > 0 && actualTypeArguments[0] instanceof ParameterizedType) {
                return InjectionUtils.processGenericTypeIfNeeded(serviceCls, returnType, 
                    (ParameterizedType)actualTypeArguments[0]);
            } else {
                return returnType;
            }
        }
    }
    
    return genericReturnType;
}
 
Example 17
Source Project: cxf   Source File: ClientRequestContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void doSetEntity(Object entity) {
    Object actualEntity = InjectionUtils.getEntity(entity);
    m.setContent(List.class, actualEntity == null ? new MessageContentsList()
        : new MessageContentsList(actualEntity));
    Type type = null;
    if (entity != null) {
        if (GenericEntity.class.isAssignableFrom(entity.getClass())) {
            type = ((GenericEntity<?>)entity).getType();
        } else {
            type = entity.getClass();
        }
        m.put(Type.class, type);
        m.remove("org.apache.cxf.empty.request");
    }

}
 
Example 18
Source Project: cxf   Source File: ClientProxyImpl.java    License: Apache License 2.0 6 votes vote down vote up
protected void addFormValue(MultivaluedMap<String, String> form, String name, Object pValue, Annotation[] anns) {
    if (pValue != null) {
        if (InjectionUtils.isSupportedCollectionOrArray(pValue.getClass())) {
            Collection<?> c = pValue.getClass().isArray()
                ? Arrays.asList((Object[]) pValue) : (Collection<?>) pValue;
            for (Iterator<?> it = c.iterator(); it.hasNext();) {
                FormUtils.addPropertyToForm(form, name, convertParamValue(it.next(), anns));
            }
        } else {
            FormUtils.addPropertyToForm(form, name, name.isEmpty()
                                        ? pValue : convertParamValue(pValue, anns));
        }

    }

}
 
Example 19
Source Project: cxf   Source File: SimpleTypeJsonProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                    MultivaluedMap<String, Object> headers, OutputStream os)
    throws IOException, WebApplicationException {
    if (!supportSimpleTypesOnly && !InjectionUtils.isPrimitive(type)) {
        @SuppressWarnings("unchecked")
        MessageBodyWriter<T> next =
            (MessageBodyWriter<T>)providers.getMessageBodyWriter(type, genericType, annotations, mediaType);
        JAXRSUtils.getCurrentMessage().put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, this);
        try {
            next.writeTo(t, type, genericType, annotations, mediaType, headers, os);
        } finally {
            JAXRSUtils.getCurrentMessage().put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, null);
        }
    } else {
        os.write(StringUtils.toBytesASCII("{\"" + type.getSimpleName().toLowerCase() + "\":"));
        writeQuote(os, type);
        primitiveHelper.writeTo(t, type, genericType, annotations, mediaType, headers, os);
        writeQuote(os, type);
        os.write(StringUtils.toBytesASCII("}"));
    }
}
 
Example 20
Source Project: cxf   Source File: SimpleTypeJsonProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                  MultivaluedMap<String, String> headers, InputStream is)
    throws IOException, WebApplicationException {
    if (!supportSimpleTypesOnly && !InjectionUtils.isPrimitive(type)) {
        MessageBodyReader<T> next =
            providers.getMessageBodyReader(type, genericType, annotations, mediaType);
        JAXRSUtils.getCurrentMessage().put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, this);
        try {
            return next.readFrom(type, genericType, annotations, mediaType, headers, is);
        } finally {
            JAXRSUtils.getCurrentMessage().put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, null);
        }
    }
    String data = IOUtils.toString(is).trim();
    int index = data.indexOf(':');
    data = data.substring(index + 1, data.length() - 1).trim();
    if (data.startsWith("\"")) {
        data = data.substring(1, data.length() - 1);
    }
    return primitiveHelper.readFrom(type, genericType, annotations, mediaType, headers,
                                    new ByteArrayInputStream(StringUtils.toBytesUTF8(data)));
}
 
Example 21
Source Project: cxf   Source File: AtomPojoProvider.java    License: Apache License 2.0 6 votes vote down vote up
protected void setFeedFromCollection(Factory factory,
                                     Feed feed,
                                     Object wrapper,
                                     Class<?> wrapperCls,
                                     Object collection,
                                     Class<?> collectionCls,
                                     Type collectionType,
                                     boolean writerUsed) throws Exception {
//CHECKSTYLE:ON
    Object[] arr = collectionCls.isArray() ? (Object[])collection : ((Collection<?>)collection).toArray();
    Class<?> memberClass = InjectionUtils.getActualType(collectionType);

    for (Object o : arr) {
        Entry entry = createEntryFromObject(factory, o, memberClass);
        feed.addEntry(entry);
    }
    if (!writerUsed) {
        setFeedProperties(factory, feed, wrapper, wrapperCls, collection, collectionCls, collectionType);
    }
}
 
Example 22
Source Project: cxf   Source File: PrimitiveSearchCondition.java    License: Apache License 2.0 6 votes vote down vote up
protected static Object getPrimitiveValue(String name, Object value) {

        int index = name.indexOf('.');
        if (index != -1) {
            String[] names = name.split("\\.");
            name = name.substring(index + 1);
            if (value != null && !InjectionUtils.isPrimitive(value.getClass())) {
                try {
                    String nextPart = StringUtils.capitalize(names[1]);
                    Method m = value.getClass().getMethod("get" + nextPart, new Class[]{});
                    value = m.invoke(value, new Object[]{});
                } catch (Throwable ex) {
                    throw new RuntimeException();
                }
            }
            return getPrimitiveValue(name, value);
        }
        return value;

    }
 
Example 23
Source Project: tomee   Source File: CdiResourceProvider.java    License: Apache License 2.0 6 votes vote down vote up
protected void doInit() throws OpenEJBException {
    injector = new InjectionProcessor<>(instance, new ArrayList<>(injections), InjectionProcessor.unwrap(context));
    instance = injector.createInstance();

    final BeanManager bm = webbeansContext == null ? null : webbeansContext.getBeanManagerImpl();
    if (bm != null) {
        creationalContext = bm.createCreationalContext(null);

        try {
            OWBInjector.inject(bm, instance, creationalContext);
        } catch (final Exception e) {
            // ignored
        }
    }

    // injector.postConstruct(); // it doesn't know it
    InjectionUtils.invokeLifeCycleMethod(instance, postConstructMethod);
}
 
Example 24
private void doInject(final InvocationContext ic) throws Exception {
    final Message current = JAXRSUtils.getCurrentMessage();
    if (current != null) {
        final OperationResourceInfoStack stack = OperationResourceInfoStack.class.cast(current.get(OperationResourceInfoStack.class.getName()));
        if (stack != null && !stack.isEmpty()) {
            final Object instance;
            if (ConstructorInterceptorInvocationContext.class.isInstance(ic)) {
                final ConstructorInterceptorInvocationContext constructorInterceptorInvocationContext = ConstructorInterceptorInvocationContext.class.cast(ic);
                constructorInterceptorInvocationContext.directProceed();
                instance = constructorInterceptorInvocationContext.getNewInstance();
            } else {
                instance = ic.getTarget();
            }
            Application application = null;
            final Object appInfo = current.getExchange().getEndpoint().get(Application.class.getName());
            if (ApplicationInfo.class.isInstance(appInfo)) {
                application = ApplicationInfo.class.cast(appInfo).getProvider();
            }
            synchronized (this) {
                if (injected.get()) {
                    return;
                }
                InjectionUtils.injectContextProxiesAndApplication(
                        stack.lastElement().getMethodInfo().getClassResourceInfo(),
                        instance,
                        application,
                        ProviderFactory.getInstance(current));
                injected.compareAndSet(false, true);
            }
        }
    }
}
 
Example 25
Source Project: cxf   Source File: JAXRSCdiResourceExtension.java    License: Apache License 2.0 5 votes vote down vote up
public void injectBus(@Observes final AfterBeanDiscovery event, final BeanManager beanManager) {
    if (!hasBus) {
        final AnnotatedType< ExtensionManagerBus > busAnnotatedType =
            beanManager.createAnnotatedType(ExtensionManagerBus.class);

        final InjectionTarget<ExtensionManagerBus> busInjectionTarget =
            beanManager.createInjectionTarget(busAnnotatedType);
        event.addBean(new CdiBusBean(busInjectionTarget));
    }

    if (applicationBeans.isEmpty() && !serviceBeans.isEmpty()) {
        final DefaultApplicationBean applicationBean = new DefaultApplicationBean();
        applicationBeans.add(applicationBean);
        event.addBean(applicationBean);
    } else {
        // otherwise will be ambiguous since we scanned it with default qualifier already
        existingStandardClasses.add(Application.class.getName());
    }

    // always add the standard context classes
    InjectionUtils.STANDARD_CONTEXT_CLASSES.stream()
            .map(this::toClass)
            .filter(Objects::nonNull)
            .forEach(contextTypes::add);
    // add custom contexts
    contextTypes.addAll(getCustomContextClasses());
    // register all of the context types
    contextTypes.forEach(
        t -> event.addBean(new ContextProducerBean(t, !existingStandardClasses.contains(t.getTypeName()))));
}
 
Example 26
Source Project: cxf   Source File: BookServer20.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext,
                   ContainerResponseContext responseContext) throws IOException {
    if (responseContext.getMediaType() != null) {
        String ct = responseContext.getMediaType().toString();
        if (requestContext.getProperty("filterexception") != null) {
            if (!"text/plain".equals(ct)) {
                throw new RuntimeException();
            }
            responseContext.getHeaders().putSingle("FilterException",
                                                   requestContext.getProperty("filterexception"));
        }
    
        Object entity = responseContext.getEntity();
        Type entityType = responseContext.getEntityType();
        if (entity instanceof GenericHandler && InjectionUtils.getActualType(entityType) == Book.class) {
            ct += ";charset=ISO-8859-1";
            if ("getGenericBook2".equals(rInfo.getResourceMethod().getName())) {
                Annotation[] anns = responseContext.getEntityAnnotations();
                if (anns.length == 4 && anns[3].annotationType() == Context.class) {
                    responseContext.getHeaders().addFirst("Annotations", "OK");
                }
            } else {
                responseContext.setEntity(new Book("book", 124L));
            }
        } else {
            ct += ";charset=";
        }
        responseContext.getHeaders().putSingle("Content-Type", ct);
        responseContext.getHeaders().add("Response", "OK");
    }
}
 
Example 27
Source Project: cxf   Source File: JAXRSInvoker.java    License: Apache License 2.0 5 votes vote down vote up
protected Method getMethodToInvoke(ClassResourceInfo cri, OperationResourceInfo ori, Object resourceObject) {
    Method resourceMethod = cri.getMethodDispatcher().getMethod(ori);

    Method methodToInvoke = null;
    if (Proxy.class.isInstance(resourceObject)) {
        methodToInvoke = cri.getMethodDispatcher().getProxyMethod(resourceMethod);
        if (methodToInvoke == null) {
            methodToInvoke = InjectionUtils.checkProxy(resourceMethod, resourceObject);
            cri.getMethodDispatcher().addProxyMethod(resourceMethod, methodToInvoke);
        }
    } else {
        methodToInvoke = resourceMethod;
    }
    return methodToInvoke;
}
 
Example 28
Source Project: cxf   Source File: ClassResourceInfo.java    License: Apache License 2.0 5 votes vote down vote up
public void injectContexts(Object resourceObject, OperationResourceInfo ori, Message inMessage) {
    final boolean contextsAvailable = contextsAvailable();
    final boolean paramsAvailable = paramsAvailable();
    if (contextsAvailable || paramsAvailable) {
        Object realResourceObject = ClassHelper.getRealObject(resourceObject);
        if (paramsAvailable) {
            JAXRSUtils.injectParameters(ori, this, realResourceObject, inMessage);
        }
        if (contextsAvailable) {
            InjectionUtils.injectContexts(realResourceObject, this, inMessage);
        }
    }
}
 
Example 29
Source Project: cxf   Source File: AbstractResourceInfo.java    License: Apache License 2.0 5 votes vote down vote up
private void addContextMethod(Class<?> contextClass, Method m, Object provider) {
    if (contextMethods == null) {
        contextMethods = new HashMap<>();
    }
    addToMap(contextMethods, contextClass, m);
    if (!InjectionUtils.VALUE_CONTEXTS.contains(m.getParameterTypes()[0].getName())) {
        addToMap(getSetterProxyMap(true), m, getMethodThreadLocalProxy(m, provider));
    }
}
 
Example 30
Source Project: cxf   Source File: ProviderFactory.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> ContextResolver<T> createContextResolver(Type contextType,
                                                    Message m,
                                                    MediaType type) {
    Class<?> contextCls = InjectionUtils.getActualType(contextType);
    if (contextCls == null) {
        return null;
    }
    List<ContextResolver<T>> candidates = new LinkedList<>();
    for (ProviderInfo<ContextResolver<?>> cr : contextResolvers) {
        Type[] types = cr.getProvider().getClass().getGenericInterfaces();
        for (Type t : types) {
            if (t instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType)t;
                Type[] args = pt.getActualTypeArguments();
                if (args.length > 0) {
                    Class<?> argCls = InjectionUtils.getActualType(args[0]);

                    if (argCls != null && argCls.isAssignableFrom(contextCls)) {
                        List<MediaType> mTypes = JAXRSUtils.getProduceTypes(
                             cr.getProvider().getClass().getAnnotation(Produces.class));
                        if (JAXRSUtils.doMimeTypesIntersect(mTypes, type)) {
                            injectContextValues(cr, m);
                            candidates.add((ContextResolver<T>)cr.getProvider());
                        }
                    }
                }
            }
        }
    }
    if (candidates.isEmpty()) {
        return null;
    } else if (candidates.size() == 1) {
        return candidates.get(0);
    } else {
        Collections.sort(candidates, new PriorityBasedClassComparator());
        return new ContextResolverProxy<T>(candidates);
    }

}