javax.ws.rs.ext.WriterInterceptor Java Examples

The following examples show how to use javax.ws.rs.ext.WriterInterceptor. 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: 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 #2
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 #3
Source File: JAXRSOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private boolean checkBufferingMode(Message m, List<WriterInterceptor> writers, boolean firstTry) {
    if (!firstTry) {
        return false;
    }
    WriterInterceptor last = writers.get(writers.size() - 1);
    MessageBodyWriter<Object> w = ((WriterInterceptorMBW)last).getMBW();
    Object outBuf = m.getContextualProperty(OUT_BUFFERING);
    boolean enabled = PropertyUtils.isTrue(outBuf);
    boolean configurableProvider = w instanceof AbstractConfigurableProvider;
    if (!enabled && outBuf == null && configurableProvider) {
        enabled = ((AbstractConfigurableProvider)w).getEnableBuffering();
    }
    if (enabled) {
        boolean streamingOn = configurableProvider
            && ((AbstractConfigurableProvider)w).getEnableStreaming();
        if (streamingOn) {
            m.setContent(XMLStreamWriter.class, new CachingXmlEventWriter());
        } else {
            m.setContent(OutputStream.class, new CachedOutputStream());
        }
    }
    return enabled;
}
 
Example #4
Source File: JAXRSOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private MediaType checkFinalContentType(MediaType mt, List<WriterInterceptor> writers, boolean checkWriters) {
    if (checkWriters) {
        int mbwIndex = writers.size() == 1 ? 0 : writers.size() - 1;
        MessageBodyWriter<Object> writer = ((WriterInterceptorMBW)writers.get(mbwIndex)).getMBW();
        Produces pm = writer.getClass().getAnnotation(Produces.class);
        if (pm != null) {
            List<MediaType> sorted =
                JAXRSUtils.sortMediaTypes(JAXRSUtils.getMediaTypes(pm.value()), JAXRSUtils.MEDIA_TYPE_QS_PARAM);
            mt = JAXRSUtils.intersectMimeTypes(sorted, mt).get(0);
        }
    }
    if (mt.isWildcardType() || mt.isWildcardSubtype()) {
        if ("application".equals(mt.getType()) || mt.isWildcardType()) {
            mt = MediaType.APPLICATION_OCTET_STREAM_TYPE;
        } else {
            throw ExceptionUtils.toNotAcceptableException(null,  null);
        }
    }
    return mt;
}
 
Example #5
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 #6
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 #7
Source File: ProviderFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
public <T> List<WriterInterceptor> createMessageBodyWriterInterceptor(Class<T> bodyType,
                                                                      Type parameterType,
                                                                      Annotation[] parameterAnnotations,
                                                                      MediaType mediaType,
                                                                      Message m,
                                                                      Set<String> names) {
    MessageBodyWriter<T> mw = createMessageBodyWriter(bodyType,
                                                  parameterType,
                                                  parameterAnnotations,
                                                  mediaType,
                                                  m);
    int size = writerInterceptors.size();
    if (mw != null || size > 0) {

        @SuppressWarnings({
            "unchecked", "rawtypes"
        })
        WriterInterceptor mbwWriter = new WriterInterceptorMBW((MessageBodyWriter)mw, m);

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

        return interceptors;
    }
    return null;
}
 
Example #8
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 #9
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomProviderSortingWIOnly() {
    ProviderFactory pf = ServerProviderFactory.getInstance();

    pf.setUserProviders(
        Arrays.asList(
            new DWriterInterceptor(), new CWriterInterceptor(),
            new AWriterInterceptor(), new BWriterInterceptor()));

    Comparator<ProviderInfo<WriterInterceptor>> comp =
        new Comparator<ProviderInfo<WriterInterceptor>>() {

            @Override
            public int compare(
                ProviderInfo<WriterInterceptor> o1,
                ProviderInfo<WriterInterceptor> o2) {

                WriterInterceptor provider1 = o1.getProvider();
                WriterInterceptor provider2 = o2.getProvider();

                return provider1.getClass().getName().compareTo(
                    provider2.getClass().getName());
            }

        };

    pf.setProviderComparator(comp);

    Collection<ProviderInfo<WriterInterceptor>> values =
        pf.writerInterceptors.values();

    assertEquals(4, values.size());

    Iterator<ProviderInfo<WriterInterceptor>> iterator = values.iterator();

    assertEquals(AWriterInterceptor.class, iterator.next().getProvider().getClass());
    assertEquals(BWriterInterceptor.class, iterator.next().getProvider().getClass());
    assertEquals(CWriterInterceptor.class, iterator.next().getProvider().getClass());
    assertEquals(DWriterInterceptor.class, iterator.next().getProvider().getClass());
}
 
Example #10
Source File: WriterInterceptorContextImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void proceed() throws IOException {
    if (writers == null || writers.isEmpty()) {
        return;
    }
    WriterInterceptor next = writers.remove(0);
    try {
        next.aroundWriteTo(this);
    } catch (IOException ex) {
        throw ex;
    }
}
 
Example #11
Source File: WriterInterceptorContextImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public WriterInterceptorContextImpl(Object entity,
                                    Class<?> cls,
                                    Type type,
                                    Annotation[] anns,
                                    OutputStream os,
                                    Message message,
                                    List<WriterInterceptor> writers) {
//CHECKSTYLE:ON
    super(cls, type, anns, message);
    this.entity = entity;
    this.os = os;
    this.writers = writers;
}
 
Example #12
Source File: MvcBinder.java    From ameba with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void configure() {
    bind(TemplateMethodInterceptor.class).to(WriterInterceptor.class).in(Singleton.class);
    //noinspection unchecked
    bind(ViewableMessageBodyWriter.class).to(MessageBodyWriter.class).in(Singleton.class);

    bind(TemplateModelProcessor.class).to(ModelProcessor.class).in(Singleton.class);
    bindAsContract(ResolvingViewableContext.class).in(Singleton.class);
    bind(ResolvingViewableContext.class).to(ViewableContext.class).in(Singleton.class).ranked(1);
}
 
Example #13
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 #14
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 #15
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 #16
Source File: WebConfigImpl.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public WebConfig bindWriterInterceptor(WriterInterceptor interceptor) {
    app.register(interceptor);
    return this;
}
 
Example #17
Source File: AbstractClient.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected <T> void writeBody(T o, Message outMessage, Class<?> cls, Type type, Annotation[] anns,
                             OutputStream os) {

    if (o == null) {
        return;
    }
    @SuppressWarnings("unchecked")
    MultivaluedMap<String, Object> headers =
        (MultivaluedMap<String, Object>)outMessage.get(Message.PROTOCOL_HEADERS);

    @SuppressWarnings("unchecked")
    Class<T> theClass = (Class<T>)cls;

    Object contentTypeHeader = headers.getFirst(HttpHeaders.CONTENT_TYPE);
    if (contentTypeHeader == null) {
        contentTypeHeader = MediaType.WILDCARD;
    }
    MediaType contentType = JAXRSUtils.toMediaType(contentTypeHeader.toString());

    List<WriterInterceptor> writers = ClientProviderFactory.getInstance(outMessage)
        .createMessageBodyWriterInterceptor(theClass, type, anns, contentType, outMessage, null);
    if (writers != null) {
        try {
            JAXRSUtils.writeMessageBody(writers,
                                        o,
                                        theClass,
                                        type,
                                        anns,
                                        contentType,
                                        headers,
                                        outMessage);

            OutputStream realOs = outMessage.get(OutputStream.class);
            if (realOs != null) {
                realOs.flush();
            }
        } catch (Exception ex) {
            reportMessageHandlerProblem("MSG_WRITER_PROBLEM", cls, contentType, ex);
        }
    } else {
        reportMessageHandlerProblem("NO_MSG_WRITER", cls, contentType, null);
    }

}
 
Example #18
Source File: WebConfig.java    From jweb-cms with GNU Affero General Public License v3.0 votes vote down vote up
WebConfig bindWriterInterceptor(WriterInterceptor interceptor);