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

The following examples show how to use org.apache.cxf.jaxrs.utils.InjectionUtils. 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: SimpleTypeJsonProvider.java    From cxf with 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 #2
Source File: MicroProfileClientProxyImpl.java    From cxf with 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 #3
Source File: ProviderFactory.java    From cxf with 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 #4
Source File: JAXRSServerFactoryBean.java    From cxf with 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 #5
Source File: JAXRSServiceImpl.java    From cxf with 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 #6
Source File: XMLSource.java    From cxf with 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 #7
Source File: AbstractResourceInfo.java    From cxf with 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 #8
Source File: AbstractResourceInfo.java    From cxf with 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 #9
Source File: AbstractResourceInfo.java    From cxf with 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 #10
Source File: ClientRequestContextImpl.java    From cxf with 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 #11
Source File: ClassResourceInfo.java    From cxf with 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 #12
Source File: ClientProxyImpl.java    From cxf with 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 #13
Source File: ProviderFactory.java    From cxf with 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 #14
Source File: SimpleTypeJsonProvider.java    From cxf with 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 #15
Source File: SingletonResourceProvider.java    From cxf with 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 #16
Source File: AtomPojoProvider.java    From cxf with 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 #17
Source File: XSLTJaxbProvider.java    From cxf with 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 #18
Source File: XSLTJaxbProvider.java    From cxf with 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 #19
Source File: ProviderFactory.java    From cxf with 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 #20
Source File: PrimitiveSearchCondition.java    From cxf with 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 #21
Source File: PrimitiveTextProvider.java    From cxf with 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 #22
Source File: CdiResourceProvider.java    From tomee with 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 #23
Source File: JAXRSCdiResourceExtension.java    From cxf with 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 #24
Source File: SearchContextImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public <T> SearchCondition<T> getCondition(String expression,
                                           Class<T> cls,
                                           Map<String, String> beanProperties,
                                           Map<String, String> parserProperties) {
    if (InjectionUtils.isPrimitive(cls)) {
        String errorMessage = "Primitive condition types are not supported";
        LOG.warning(errorMessage);
        throw new IllegalArgumentException(errorMessage);
    }

    SearchConditionParser<T> parser = getParser(cls, beanProperties, parserProperties);

    String theExpression = expression == null
        ? getSearchExpression() : expression;
    if (theExpression != null) {
        try {
            return parser.parse(theExpression);
        } catch (SearchParseException ex) {
            if (PropertyUtils.isTrue(message.getContextualProperty(BLOCK_SEARCH_EXCEPTION))) {
                return null;
            }
            throw ex;
        }
    }
    return null;

}
 
Example #25
Source File: ClientResponseFilterInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void handleMessage(Message inMessage) throws Fault {
    ClientProviderFactory pf = ClientProviderFactory.getInstance(inMessage);
    if (pf == null) {
        return;
    }

    List<ProviderInfo<ClientResponseFilter>> filters = pf.getClientResponseFilters();
    if (!filters.isEmpty()) {
        final ClientRequestContext reqContext = new ClientRequestContextImpl(
            inMessage.getExchange().getOutMessage(), true);
        final ResponseImpl response = (ResponseImpl)getResponse(inMessage);
        final ClientResponseContext respContext = new ClientResponseContextImpl(response, inMessage);
        for (ProviderInfo<ClientResponseFilter> filter : filters) {
            InjectionUtils.injectContexts(filter.getProvider(), filter, inMessage);
            try {
                filter.getProvider().filter(reqContext, respContext);
            } catch (RuntimeException | IOException ex) {
                // Complete the IN chain, if we won't set it, the AbstractClient::preProcessResult
                // would be stuck waiting for the IN chain completion.
                if (!inMessage.getExchange().isOneWay()) {
                    synchronized (inMessage.getExchange()) {
                        inMessage.getExchange().put("IN_CHAIN_COMPLETE", Boolean.TRUE);
                    }
                }
                
                // When a provider method throws an exception, the JAX-RS client runtime will map 
                // it to an instance of ResponseProcessingException if thrown while processing 
                // a response (4.5.2 Client Runtime).
                throw new ResponseProcessingException(response, ex);
            }
        }
    }
}
 
Example #26
Source File: BlueprintResourceFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Object getInstance(Message m) {
    //TODO -- This is not the BP way.
    ProviderInfo<?> application = m == null ? null
        : (ProviderInfo<?>)m.getExchange().getEndpoint().get(Application.class.getName());
    Map<Class<?>, Object> mapValues = CastUtils.cast(application == null ? null
        : Collections.singletonMap(Application.class, application.getProvider()));
    Object[] values = ResourceUtils.createConstructorArguments(c, m, !isSingleton(), mapValues);
    //TODO Very springish...
    Object instance = values.length > 0 ? blueprintContainer.getComponentInstance(beanId)
        : blueprintContainer.getComponentInstance(beanId);
    if (!isSingleton() || m == null) {
        InjectionUtils.invokeLifeCycleMethod(instance, postConstructMethod);
    }
    return instance;
}
 
Example #27
Source File: ContainerResponseContextImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public Type getEntityType() {
    return InjectionUtils.getGenericResponseType(invoked,
                                          serviceCls,
                                          super.r.getActualEntity(),
                                          getEntityClass(),
                                          super.m.getExchange());
}
 
Example #28
Source File: StreamingResponseProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(StreamingResponse<T> p, Class<?> cls, Type t, Annotation[] anns,
                    MediaType mt, MultivaluedMap<String, Object> headers, OutputStream os)
    throws IOException, WebApplicationException {
    Class<?> actualCls = InjectionUtils.getActualType(t);
    if (cls == actualCls) {
        actualCls = Object.class;
    }
    //TODO: review the possibility of caching the providers
    StreamingResponseWriter thewriter = new StreamingResponseWriter(actualCls, anns, mt, headers, os);
    p.writeTo(thewriter);
}
 
Example #29
Source File: ServerProviderFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void injectContextValues(ProviderInfo<?> pi, Message m) {
    if (m != null) {
        InjectionUtils.injectContexts(pi.getProvider(), pi, m);
        if (application != null && application.contextsAvailable()) {
            InjectionUtils.injectContexts(application.getProvider(), application, m);
        }
    }
}
 
Example #30
Source File: JAXRSFieldInjectionInterceptor.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
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);
            }
        }
    }
}