javax.ws.rs.ext.ReaderInterceptor Java Examples

The following examples show how to use javax.ws.rs.ext.ReaderInterceptor. 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: ProviderFactoryTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateMessageBodyReaderInterceptorWithReaderInterceptor() throws Exception {
    ReaderInterceptor ri = readerInterceptorContext -> readerInterceptorContext.proceed();
    ProviderInfo<ReaderInterceptor> pi = new ProviderInfo<>(ri, null, true);

    ServerProviderFactory spf = ServerProviderFactory.getInstance();
    spf.readerInterceptors.put(new ProviderFactory.NameKey("org.apache.cxf.filter.binding", 1, ri.getClass()), pi);

    final Message message = prepareMessage(MediaType.APPLICATION_XML, MediaType.APPLICATION_XML);

    List<ReaderInterceptor> interceptors =
        spf.createMessageBodyReaderInterceptor(Book.class, Book.class,
                                               new Annotation[0], MediaType.APPLICATION_XML_TYPE,
                                               message, true, null);
    assertSame(2, interceptors.size());
}
 
Example #2
Source File: AdditionalRegistrationTest.java    From microprofile-rest-client with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRegisterAMultiTypedProviderInstanceWithPriorities() {
    MultiTypedProvider provider = new MultiTypedProvider();
    Map<Class<?>, Integer> priorities = new HashMap<>();
    priorities.put(ClientRequestFilter.class, 500);
    priorities.put(ClientResponseFilter.class, 501);
    priorities.put(MessageBodyReader.class, 502);
    priorities.put(MessageBodyWriter.class, 503);
    priorities.put(ReaderInterceptor.class, 504);
    priorities.put(WriterInterceptor.class, 505);
    priorities.put(ResponseExceptionMapper.class, 506);
    priorities.put(ParamConverterProvider.class, 507);
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(provider, priorities);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered");
    assertTrue(configuration.isRegistered(provider), MultiTypedProvider.class + " should be registered");
    Map<Class<?>, Integer> contracts = configuration.getContracts(MultiTypedProvider.class);
    assertEquals(contracts.size(), priorities.size(),
        "There should be "+priorities.size()+" provider types registered");
    for(Map.Entry<Class<?>, Integer> priority : priorities.entrySet()) {
        Integer contractPriority = contracts.get(priority.getKey());
        assertEquals(contractPriority, priority.getValue(), "The priority for "+priority.getKey()+" should be "+priority.getValue());
    }
}
 
Example #3
Source File: AdditionalRegistrationTest.java    From microprofile-rest-client with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRegisterAMultiTypedProviderClassWithPriorities() {
    Map<Class<?>, Integer> priorities = new HashMap<>();
    priorities.put(ClientRequestFilter.class, 500);
    priorities.put(ClientResponseFilter.class, 501);
    priorities.put(MessageBodyReader.class, 502);
    priorities.put(MessageBodyWriter.class, 503);
    priorities.put(ReaderInterceptor.class, 504);
    priorities.put(WriterInterceptor.class, 505);
    priorities.put(ResponseExceptionMapper.class, 506);
    priorities.put(ParamConverterProvider.class, 507);
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(MultiTypedProvider.class, priorities);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered");
    Map<Class<?>, Integer> contracts = configuration.getContracts(MultiTypedProvider.class);
    assertEquals(contracts.size(), priorities.size(),
        "There should be "+priorities.size()+" provider types registered");
    for(Map.Entry<Class<?>, Integer> priority : priorities.entrySet()) {
        Integer contractPriority = contracts.get(priority.getKey());
        assertEquals(contractPriority, priority.getValue(), "The priority for "+priority.getKey()+" should be "+priority.getValue());
    }
}
 
Example #4
Source File: ServerProviderFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public Map<Class<?>, Integer> getContracts(Class<?> cls) {
    Map<Class<?>, Integer> map = new HashMap<>();
    if (isRegistered(cls)) {
        if (ContainerRequestFilter.class.isAssignableFrom(cls)) {
            boolean isPreMatch = cls.getAnnotation(PreMatching.class) != null;
            map.put(ContainerRequestFilter.class,
                    getPriority(isPreMatch ? preMatchContainerRequestFilters
                        : postMatchContainerRequestFilters.values(), cls, ContainerRequestFilter.class));
        }
        if (ContainerResponseFilter.class.isAssignableFrom(cls)) {
            map.put(ContainerResponseFilter.class,
                    getPriority(containerResponseFilters.values(), cls, ContainerResponseFilter.class));
        }
        if (WriterInterceptor.class.isAssignableFrom(cls)) {
            map.put(WriterInterceptor.class,
                    getPriority(writerInterceptors.values(), cls, WriterInterceptor.class));
        }
        if (ReaderInterceptor.class.isAssignableFrom(cls)) {
            map.put(ReaderInterceptor.class,
                    getPriority(readerInterceptors.values(), cls, ReaderInterceptor.class));
        }
    }
    return map;
}
 
Example #5
Source File: ProviderFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void setProviderComparator(Comparator<?> providerComparator) {
    this.providerComparator = providerComparator;

    sortReaders();
    sortWriters();

    NameKeyMap<ProviderInfo<ReaderInterceptor>> sortedReaderInterceptors =
        new NameKeyMap<>(
            (Comparator<ProviderInfo<?>>) providerComparator, true);
    sortedReaderInterceptors.putAll(readerInterceptors);
    NameKeyMap<ProviderInfo<WriterInterceptor>> sortedWriterInterceptors =
        new NameKeyMap<>(
            (Comparator<ProviderInfo<?>>) providerComparator, true);
    sortedWriterInterceptors.putAll(writerInterceptors);

    readerInterceptors = sortedReaderInterceptors;
    writerInterceptors = sortedWriterInterceptors;
}
 
Example #6
Source File: RESTService.java    From tomee with Apache License 2.0 5 votes vote down vote up
private static <T> boolean isProvider(final Class<T> clazz) {
    return MessageBodyReader.class.isAssignableFrom(clazz) ||
            MessageBodyWriter.class.isAssignableFrom(clazz) ||
            ParamConverter.class.isAssignableFrom(clazz) ||
            ContainerRequestFilter.class.isAssignableFrom(clazz) ||
            ContainerResponseFilter.class.isAssignableFrom(clazz) ||
            ReaderInterceptor.class.isAssignableFrom(clazz) ||
            WriterInterceptor.class.isAssignableFrom(clazz) ||
            ParamConverterProvider.class.isAssignableFrom(clazz) ||
            ContextResolver.class.isAssignableFrom(clazz) ||
            Feature.class.isAssignableFrom(clazz) ||
            new MetaAnnotatedClass<>(clazz).isAnnotationPresent(Provider.class);
}
 
Example #7
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateMessageBodyReaderInterceptorWithFaultMessageAndReaderInterceptor() throws Exception {
    ReaderInterceptor ri = readerInterceptorContext -> readerInterceptorContext.proceed();
    ProviderInfo<ReaderInterceptor> pi = new ProviderInfo<>(ri, null, true);

    ServerProviderFactory spf = ServerProviderFactory.getInstance();
    spf.readerInterceptors.put(new ProviderFactory.NameKey("org.apache.cxf.filter.binding", 1, ri.getClass()), pi);

    final Message message = prepareFaultMessage(MediaType.APPLICATION_XML, MediaType.APPLICATION_XML);
    List<ReaderInterceptor> interceptors =
        spf.createMessageBodyReaderInterceptor(Book.class, Book.class,
                                               new Annotation[0], MediaType.APPLICATION_XML_TYPE,
                                               message, true, null);
    assertSame(2, interceptors.size());
}
 
Example #8
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateMessageBodyReaderInterceptorWithFaultMessage() throws Exception {
    ServerProviderFactory spf = ServerProviderFactory.getInstance();
    final Message message = prepareFaultMessage(MediaType.APPLICATION_XML, MediaType.APPLICATION_XML);

    List<ReaderInterceptor> interceptors =
        spf.createMessageBodyReaderInterceptor(Book.class, Book.class,
                                               new Annotation[0], MediaType.APPLICATION_XML_TYPE,
                                               message, true, null);
    assertSame(1, interceptors.size());
}
 
Example #9
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateMessageBodyReaderInterceptor() {
    ServerProviderFactory spf = ServerProviderFactory.getInstance();
    final Message message = prepareMessage(MediaType.APPLICATION_XML, MediaType.APPLICATION_XML);

    List<ReaderInterceptor> interceptors =
        spf.createMessageBodyReaderInterceptor(Book.class, Book.class,
                                               new Annotation[0], MediaType.APPLICATION_XML_TYPE,
                                               message, true, null);
    assertSame(1, interceptors.size());
}
 
Example #10
Source File: ReaderInterceptorContextImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public Object proceed() throws IOException {
    if (readers == null || readers.isEmpty()) {
        return null;
    }
    ReaderInterceptor next = readers.remove(0);
    return next.aroundReadFrom(this);
}
 
Example #11
Source File: ReaderInterceptorContextImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public ReaderInterceptorContextImpl(Class<?> cls,
                                    Type type,
                                    Annotation[] anns,
                                    InputStream is,
                                    Message message,
                                    List<ReaderInterceptor> readers) {
    super(cls, type, anns, message);
    this.is = is;
    this.readers = readers;
}
 
Example #12
Source File: ProviderFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
public <T> List<ReaderInterceptor> createMessageBodyReaderInterceptor(Class<T> bodyType,
                                                        Type parameterType,
                                                        Annotation[] parameterAnnotations,
                                                        MediaType mediaType,
                                                        Message m,
                                                        boolean checkMbrNow,
                                                        Set<String> names) {
    MessageBodyReader<T> mr = !checkMbrNow ? null : createMessageBodyReader(bodyType,
                                                  parameterType,
                                                  parameterAnnotations,
                                                  mediaType,
                                                  m);
    int size = readerInterceptors.size();
    if (mr != null || size > 0) {
        ReaderInterceptor mbrReader = new ReaderInterceptorMBR(mr, getResponseMessage(m));

        List<ReaderInterceptor> interceptors = null;
        if (size > 0) {
            interceptors = new ArrayList<>(size + 1);
            List<ProviderInfo<ReaderInterceptor>> readers =
                getBoundFilters(readerInterceptors, names);
            for (ProviderInfo<ReaderInterceptor> p : readers) {
                injectContextValues(p, m);
                interceptors.add(p.getProvider());
            }
            interceptors.add(mbrReader);
        } else {
            interceptors = Collections.singletonList(mbrReader);
        }

        return interceptors;
    }
    return null;
}
 
Example #13
Source File: JAXRSUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static Object readFromMessageBodyReader(List<ReaderInterceptor> readers,
                                               Class<?> targetTypeClass,
                                               Type parameterType,
                                               Annotation[] parameterAnnotations,
                                               InputStream is,
                                               MediaType mediaType,
                                               Message m) throws IOException, WebApplicationException {

    // Verbose but avoids an extra context instantiation for the typical path
    if (readers.size() > 1) {
        ReaderInterceptor first = readers.remove(0);
        ReaderInterceptorContext context = new ReaderInterceptorContextImpl(targetTypeClass,
                                                                        parameterType,
                                                                        parameterAnnotations,
                                                                        is,
                                                                        m,
                                                                        readers);

        return first.aroundReadFrom(context);
    }
    MessageBodyReader<?> provider = ((ReaderInterceptorMBR)readers.get(0)).getMBR();
    @SuppressWarnings("rawtypes")
    Class cls = targetTypeClass;
    return provider.readFrom(
              cls, parameterType, parameterAnnotations, mediaType,
              new HttpHeadersImpl(m).getRequestHeaders(), is);
}
 
Example #14
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private ReaderInterceptor getReaderInterceptor() {
    return readerInterceptorContext -> {
        InputStream is = new BufferedInputStream(readerInterceptorContext.getInputStream());
        readerInterceptorContext.setInputStream(is);
        return readerInterceptorContext.proceed();
    };
}
 
Example #15
Source File: AdditionalRegistrationTest.java    From microprofile-rest-client with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRegisterAMultiTypedProviderClass() {
    Class<?>[] providerTypes = {ClientRequestFilter.class, ClientResponseFilter.class,
        MessageBodyReader.class, MessageBodyWriter.class, ReaderInterceptor.class, WriterInterceptor.class,
        ResponseExceptionMapper.class, ParamConverterProvider.class};
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(MultiTypedProvider.class, providerTypes);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered");
    assertEquals(configuration.getContracts(MultiTypedProvider.class).size(), providerTypes.length,
        "There should be "+providerTypes.length+" provider types registered");
}
 
Example #16
Source File: AdditionalRegistrationTest.java    From microprofile-rest-client with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRegisterAMultiTypedProviderInstance() {
    MultiTypedProvider provider = new MultiTypedProvider();
    Class<?>[] providerTypes = {ClientRequestFilter.class, ClientResponseFilter.class,
        MessageBodyReader.class, MessageBodyWriter.class, ReaderInterceptor.class, WriterInterceptor.class,
        ResponseExceptionMapper.class, ParamConverterProvider.class};
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(provider, providerTypes);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered");
    assertTrue(configuration.isRegistered(provider), MultiTypedProvider.class + " should be registered");
    assertEquals(configuration.getContracts(MultiTypedProvider.class).size(), providerTypes.length,
        "There should be "+providerTypes.length+" provider types registered");
}
 
Example #17
Source File: ProviderFactory.java    From cxf with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
protected void setCommonProviders(List<ProviderInfo<? extends Object>> theProviders) {
    List<ProviderInfo<ReaderInterceptor>> readInts =
        new LinkedList<>();
    List<ProviderInfo<WriterInterceptor>> writeInts =
        new LinkedList<>();
    for (ProviderInfo<? extends Object> provider : theProviders) {
        Class<?> providerCls = ClassHelper.getRealClass(bus, provider.getProvider());

        if (filterContractSupported(provider, providerCls, MessageBodyReader.class)) {
            addProviderToList(messageReaders, provider);
        }

        if (filterContractSupported(provider, providerCls, MessageBodyWriter.class)) {
            addProviderToList(messageWriters, provider);
        }

        if (filterContractSupported(provider, providerCls, ContextResolver.class)) {
            addProviderToList(contextResolvers, provider);
        }

        if (ContextProvider.class.isAssignableFrom(providerCls)) {
            addProviderToList(contextProviders, provider);
        }

        if (filterContractSupported(provider, providerCls, ReaderInterceptor.class)) {
            readInts.add((ProviderInfo<ReaderInterceptor>)provider);
        }

        if (filterContractSupported(provider, providerCls, WriterInterceptor.class)) {
            writeInts.add((ProviderInfo<WriterInterceptor>)provider);
        }

        if (filterContractSupported(provider, providerCls, ParamConverterProvider.class)) {
            paramConverters.add((ProviderInfo<ParamConverterProvider>)provider);
        }
    }
    sortReaders();
    sortWriters();
    sortContextResolvers();

    mapInterceptorFilters(readerInterceptors, readInts, ReaderInterceptor.class, true);
    mapInterceptorFilters(writerInterceptors, writeInts, WriterInterceptor.class, true);

    injectContextProxies(messageReaders, messageWriters, contextResolvers, paramConverters,
        readerInterceptors.values(), writerInterceptors.values());
    checkParamConverterContexts();
}
 
Example #18
Source File: ResponseImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
public <T> T doReadEntity(Class<T> cls, Type t, Annotation[] anns) throws ProcessingException,
    IllegalStateException {

    checkEntityIsClosed();

    if (lastEntity != null && cls.isAssignableFrom(lastEntity.getClass())
        && !(lastEntity instanceof InputStream)) {
        return cls.cast(lastEntity);
    }

    MediaType mediaType = getMediaType();
    if (mediaType == null) {
        mediaType = MediaType.WILDCARD_TYPE;
    }

    // the stream is available if entity is IS or
    // message contains XMLStreamReader or Reader
    boolean entityStreamAvailable = entityStreamAvailable();
    InputStream entityStream = null;
    if (!entityStreamAvailable) {
        // try create a stream if the entity is String or Number
        entityStream = convertEntityToStreamIfPossible();
        entityStreamAvailable = entityStream != null;
    } else if (entity instanceof InputStream) {
        entityStream = InputStream.class.cast(entity);
    } else {
        Message inMessage = getResponseMessage();
        Reader reader = inMessage.getContent(Reader.class);
        if (reader != null) {
            entityStream = InputStream.class.cast(new ReaderInputStream(reader));
        }
    }

    // we need to check for readers even if no IS is set - the readers may still do it
    List<ReaderInterceptor> readers = outMessage == null ? null : ProviderFactory.getInstance(outMessage)
        .createMessageBodyReaderInterceptor(cls, t, anns, mediaType, outMessage, entityStreamAvailable, null);

    if (readers != null) {
        try {
            if (entityBufferred) {
                InputStream.class.cast(entity).reset();
            }

            Message responseMessage = getResponseMessage();
            responseMessage.put(Message.PROTOCOL_HEADERS, getHeaders());

            lastEntity = JAXRSUtils.readFromMessageBodyReader(readers, cls, t,
                                                                   anns,
                                                                   entityStream,
                                                                   mediaType,
                                                                   responseMessage);
            autoClose(cls, false);
            return castLastEntity();
        } catch (Exception ex) {
            autoClose(cls, true);
            reportMessageHandlerProblem("MSG_READER_PROBLEM", cls, mediaType, ex);
        } finally {
            ProviderFactory pf = ProviderFactory.getInstance(outMessage);
            if (pf != null) {
                pf.clearThreadLocalProxies();
            }
        }
    } else if (entity != null && cls.isAssignableFrom(entity.getClass())) {
        lastEntity = entity;
        return castLastEntity();
    } else if (entityStreamAvailable) {
        reportMessageHandlerProblem("NO_MSG_READER", cls, mediaType, null);
    }

    throw new IllegalStateException("The entity is not backed by an input stream, entity class is : "
        + (entity != null ? entity.getClass().getName() : cls.getName()));

}
 
Example #19
Source File: WebConfigImpl.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public WebConfig bindReaderInterceptor(ReaderInterceptor interceptor) {
    app.register(interceptor);
    return this;
}
 
Example #20
Source File: WebConfig.java    From jweb-cms with GNU Affero General Public License v3.0 votes vote down vote up
WebConfig bindReaderInterceptor(ReaderInterceptor interceptor);