javax.ws.rs.ext.MessageBodyWriter Java Examples

The following examples show how to use javax.ws.rs.ext.MessageBodyWriter. 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: BookServer.java    From cxf with Apache License 2.0 7 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType,
                                          Annotation[] annotations) {
    if (rawType == Book.class) {

        MessageBodyReader<Book> mbr = providers.getMessageBodyReader(Book.class,
                                                                     Book.class,
                                                                     annotations,
                                                                     MediaType.APPLICATION_XML_TYPE);
        MessageBodyWriter<Book> mbw = providers.getMessageBodyWriter(Book.class,
                                                                     Book.class,
                                                                     annotations,
                                                                     MediaType.APPLICATION_XML_TYPE);
        return (ParamConverter<T>)new XmlParamConverter(mbr, mbw);
    } else if (rawType == byte.class) {
        return (ParamConverter<T>)new ByteConverter();
    } else {
        return null;
    }

}
 
Example #2
Source File: AWSRequest.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream getContent() {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  final Object entity = clientRequestContext.getEntity();
  if (entity == null) {
    return null;
  } else {
    MessageBodyWriter messageBodyWriter = workers.getMessageBodyWriter(entity.getClass(), entity.getClass(),
      new Annotation[]{}, clientRequestContext.getMediaType());
    try {
      // use the MBW to serialize entity into baos
      messageBodyWriter.writeTo(entity,
        entity.getClass(), entity.getClass(), new Annotation[] {},
        clientRequestContext.getMediaType(), new MultivaluedHashMap<String, Object>(),
        baos);
    } catch (IOException e) {
      throw new RuntimeException(
        "Error while serializing entity.", e);
    }
    return new ByteArrayInputStream(baos.toByteArray());
  }
}
 
Example #3
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testRegisterMbrMbwProviderAsMbrOnly() {
    ServerProviderFactory pf = ServerProviderFactory.getInstance();
    JAXBElementProvider<Book> customProvider = new JAXBElementProvider<>();
    pf.registerUserProvider((Feature) context -> {
        context.register(customProvider, MessageBodyReader.class);
        return true;
    });
    MessageBodyReader<Book> reader = pf.createMessageBodyReader(Book.class, null, null,
                                                                MediaType.TEXT_XML_TYPE, new MessageImpl());
    assertSame(reader, customProvider);

    MessageBodyWriter<Book> writer = pf.createMessageBodyWriter(Book.class, null, null,
                                                                MediaType.TEXT_XML_TYPE, new MessageImpl());
    assertTrue(writer instanceof JAXBElementProvider);
    assertNotSame(writer, customProvider);
}
 
Example #4
Source File: BinaryDataProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testWriteTo() throws Exception {
    MessageBodyWriter p = new BinaryDataProvider();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    p.writeTo(new byte[]{'h', 'i'}, null, null, null, null, null, os);
    assertArrayEquals(new String("hi").getBytes(), os.toByteArray());
    ByteArrayInputStream is = new ByteArrayInputStream("hi".getBytes());
    os = new ByteArrayOutputStream();
    p.writeTo(is, null, null, null, null, null, os);
    assertArrayEquals(os.toByteArray(), new String("hi").getBytes());

    Reader r = new StringReader("hi");
    os = new ByteArrayOutputStream();
    p.writeTo(r, null, null, null, MediaType.valueOf("text/xml"), null, os);
    assertArrayEquals(os.toByteArray(), new String("hi").getBytes());

    os = new ByteArrayOutputStream();
    p.writeTo(new StreamingOutputImpl(), null, null, null,
              MediaType.valueOf("text/xml"), null, os);
    assertArrayEquals(os.toByteArray(), new String("hi").getBytes());
}
 
Example #5
Source File: ProviderBinderTest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void retrievesAcceptableWriterMediaTypes() throws Exception {
    ObjectFactory<ProviderDescriptor> writerFactory = mock(ObjectFactory.class);
    ProviderDescriptor providerDescriptor = mock(ProviderDescriptor.class);
    when(providerDescriptor.produces()).thenReturn(newArrayList(new MediaType("text", "*"), new MediaType("text", "plain")));
    when(providerDescriptor.getObjectClass()).thenReturn((Class)StringEntityProvider.class);
    when(writerFactory.getObjectModel()).thenReturn(providerDescriptor);
    MessageBodyWriter<String> writer = mock(MessageBodyWriter.class);
    when(writer.isWriteable(eq(String.class), isNull(), any(), eq(WILDCARD_TYPE))).thenReturn(true);
    when(writerFactory.getInstance(context)).thenReturn(writer);

    providers.addMessageBodyWriter(writerFactory);

    assertEquals(newArrayList(new MediaType("text", "plain"), new MediaType("text", "*")),
                 providers.getAcceptableWriterMediaTypes(String.class, null, null));
}
 
Example #6
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 #7
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testSortEntityProviders() throws Exception {
    ProviderFactory pf = ServerProviderFactory.getInstance();
    pf.registerUserProvider(new TestStringProvider());
    pf.registerUserProvider(new PrimitiveTextProvider<Object>());

    List<ProviderInfo<MessageBodyReader<?>>> readers = pf.getMessageReaders();

    assertTrue(indexOf(readers, TestStringProvider.class)
               < indexOf(readers, PrimitiveTextProvider.class));

    List<ProviderInfo<MessageBodyWriter<?>>> writers = pf.getMessageWriters();

    assertTrue(indexOf(writers, TestStringProvider.class)
               < indexOf(writers, PrimitiveTextProvider.class));

}
 
Example #8
Source File: ContainerResponseTest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
private Answer<Void> writeEntity() {
    return invocation -> {
        MessageBodyWriter messageBodyWriter = (MessageBodyWriter)invocation.getArguments()[1];
        Object entity = containerResponse.getEntity();
        if (entity != null) {
            messageBodyWriter.writeTo(entity,
                                      entity.getClass(),
                                      containerResponse.getEntityType(),
                                      null,
                                      containerResponse.getContentType(),
                                      containerResponse.getHttpHeaders(),
                                      entityStream);
        }
        return null;
    };
}
 
Example #9
Source File: ProviderFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
public int compare(ProviderInfo<MessageBodyWriter<?>> p1,
                   ProviderInfo<MessageBodyWriter<?>> p2) {
    MessageBodyWriter<?> e1 = p1.getProvider();
    MessageBodyWriter<?> e2 = p2.getProvider();

    int result = compareClasses(e1, e2);
    if (result != 0) {
        return result;
    }
    List<MediaType> types1 =
        JAXRSUtils.sortMediaTypes(JAXRSUtils.getProviderProduceTypes(e1), JAXRSUtils.MEDIA_TYPE_QS_PARAM);
    List<MediaType> types2 =
        JAXRSUtils.sortMediaTypes(JAXRSUtils.getProviderProduceTypes(e2), JAXRSUtils.MEDIA_TYPE_QS_PARAM);

    result = JAXRSUtils.compareSortedMediaTypes(types1, types2, JAXRSUtils.MEDIA_TYPE_QS_PARAM);
    if (result != 0) {
        return result;
    }
    result = compareCustomStatus(p1, p2);
    if (result != 0) {
        return result;
    }

    return comparePriorityStatus(p1.getProvider().getClass(), p2.getProvider().getClass());
}
 
Example #10
Source File: ProviderBinderTest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Test
@UseDataProvider("messageBodyWriterByTypeAndMediaType")
public void retrievesMessageBodyWriterByTypeAndMediaType(boolean singletonOrPerRequest,
                                                         Class<?> writeObjectType,
                                                         Type writeObjectGenericType,
                                                         MediaType mediaType,
                                                         Object expectedMessageBodyWriterClassOrInstance) throws Exception {
    if (singletonOrPerRequest == SINGLETON) {
        registerSingletonMessageBodyWriters();
    } else {
        registerPerRequestMessageBodyWriters();
    }

    MessageBodyWriter messageBodyWriter = providers.getMessageBodyWriter(writeObjectType, writeObjectGenericType, null, mediaType);
    if (singletonOrPerRequest == SINGLETON) {
        assertSame(expectedMessageBodyWriterClassOrInstance, messageBodyWriter);
    } else {
        if (expectedMessageBodyWriterClassOrInstance == null) {
            assertNull(messageBodyWriter);
        } else {
            assertNotNull(messageBodyWriter);
            assertEquals(expectedMessageBodyWriterClassOrInstance, messageBodyWriter.getClass());
        }
    }
}
 
Example #11
Source File: OutboundSseEventBodyWriter.java    From cxf with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private<T> void writePayloadTo(Class<T> cls, Type type, Annotation[] anns, MediaType mt,
        MultivaluedMap<String, Object> headers, Object data, OutputStream os)
            throws IOException, WebApplicationException {

    MessageBodyWriter<T> writer = null;
    if (message != null && factory != null) {
        writer = factory.createMessageBodyWriter(cls, type, anns, mt, message);
    }

    if (writer == null) {
        throw new InternalServerErrorException("No suitable message body writer for class: " + cls.getName());
    }

    writer.writeTo((T)data, cls, type, anns, mt, headers, os);
}
 
Example #12
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 #13
Source File: PrimitiveTextProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteStringISO() throws Exception {
    MessageBodyWriter<String> p = new PrimitiveTextProvider<>();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    MultivaluedMap<String, Object> headers = new MetadataMap<>();

    String eWithAcute = "\u00E9";
    String helloStringUTF16 = "Hello, my name is F" + eWithAcute + "lix Agn" + eWithAcute + "s";

    p.writeTo(helloStringUTF16,
              String.class, String.class, null, MediaType.valueOf("text/plain;charset=ISO-8859-1"),
              headers, os);

    byte[] iso88591bytes = helloStringUTF16.getBytes("ISO-8859-1");
    String helloStringISO88591 = new String(iso88591bytes, "ISO-8859-1");

    assertEquals(helloStringISO88591, os.toString("ISO-8859-1"));
}
 
Example #14
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 #15
Source File: ErrorPageGenerator.java    From ameba with MIT License 6 votes vote down vote up
/**
 * <p>writeViewable.</p>
 *
 * @param viewable     a {@link org.glassfish.jersey.server.mvc.Viewable} object.
 * @param mediaType    a {@link javax.ws.rs.core.MediaType} object.
 * @param httpHeaders  a {@link javax.ws.rs.core.MultivaluedMap} object.
 * @param entityStream a {@link java.io.OutputStream} object.
 * @throws java.io.IOException if any.
 */
protected void writeViewable(Viewable viewable,
                             MediaType mediaType,
                             MultivaluedMap<String, Object> httpHeaders,
                             OutputStream entityStream) throws IOException {
    MessageBodyWriter<Viewable> writer = workers.get().getMessageBodyWriter(Viewable.class, null,
            new Annotation[]{}, null);
    if (writer != null) {
        writer.writeTo(viewable,
                Viewable.class,
                Viewable.class,
                new Annotation[0],
                mediaType,
                httpHeaders,
                entityStream);
    }
}
 
Example #16
Source File: OptionalMessageBodyWriter.java    From dropwizard-java8 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public void writeTo(Optional<?> entity,
                    Class<?> type,
                    Type genericType,
                    Annotation[] annotations,
                    MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream)
        throws IOException {
    if (!entity.isPresent()) {
        throw new NotFoundException();
    }

    final Type innerGenericType = (genericType instanceof ParameterizedType) ?
        ((ParameterizedType) genericType).getActualTypeArguments()[0] : entity.get().getClass();

    MessageBodyWriter writer = mbw.get().getMessageBodyWriter(entity.get().getClass(),
        innerGenericType, annotations, mediaType);
    writer.writeTo(entity.get(), entity.get().getClass(),
        innerGenericType, annotations, mediaType, httpHeaders, entityStream);
}
 
Example #17
Source File: FastJsonFeature.java    From fastjson-jaxrs-json-provider with Apache License 2.0 6 votes vote down vote up
public boolean configure(final FeatureContext context) {
	final Configuration config = context.getConfiguration();
	final String jsonFeature = CommonProperties.getValue(config.getProperties(), config.getRuntimeType(), InternalProperties.JSON_FEATURE, JSON_FEATURE,
			String.class);
	// Other JSON providers registered.
	if (!JSON_FEATURE.equalsIgnoreCase(jsonFeature)) {
		return false;
	}
	// Disable other JSON providers.
	context.property(PropertiesHelper.getPropertyNameForRuntime(InternalProperties.JSON_FEATURE, config.getRuntimeType()), JSON_FEATURE);
	// Register FastJson.
	if (!config.isRegistered(FastJsonProvider.class)) {
		context.register(FastJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
	}
	return true;
}
 
Example #18
Source File: MultipartProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
MessageBodyWriterDataHandler(MessageBodyWriter<T> writer,
                             T obj,
                             Class<T> cls,
                             Type genericType,
                             Annotation[] anns,
                             MediaType contentType) {
    super(new ByteDataSource("1".getBytes()));
    this.writer = writer;
    this.obj = obj;
    this.cls = cls;
    this.genericType = genericType;
    this.anns = anns;
    this.contentType = contentType;
}
 
Example #19
Source File: ProviderCache.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void putWriters(Class<?> type, MediaType mt, List<ProviderInfo<MessageBodyWriter<?>>> candidates) {
    if (candidates == null || candidates.isEmpty()) {
        return;
    }
    checkCacheSize(writerProviderCache);

    String key = getKey(type, mt);
    writerProviderCache.put(key, candidates);
}
 
Example #20
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomProviderSorting() {
    ProviderFactory pf = ServerProviderFactory.getInstance();
    Comparator<?> comp = new Comparator<ProviderInfo<?>>() {

        @Override
        public int compare(ProviderInfo<?> o1, ProviderInfo<?> o2) {
            Object provider1 = o1.getProvider();
            Object provider2 = o2.getProvider();
            if (provider1 instanceof StringTextProvider) {
                return 1;
            } else if (provider2 instanceof StringTextProvider) {
                return -1;
            } else {
                return 0;
            }
        }

    };
    pf.setProviderComparator(comp);

    // writers
    List<ProviderInfo<MessageBodyWriter<?>>> writers = pf.getMessageWriters();
    assertEquals(10, writers.size());
    Object lastWriter = writers.get(9).getProvider();
    assertTrue(lastWriter instanceof StringTextProvider);
    //readers
    List<ProviderInfo<MessageBodyReader<?>>> readers = pf.getMessageReaders();
    assertEquals(9, readers.size());
    Object lastReader = readers.get(8).getProvider();
    assertTrue(lastReader instanceof StringTextProvider);
}
 
Example #21
Source File: MultipartFormDataWriter.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected void writeItem(OutputItem item, OutputStream output, byte[] boundary) throws IOException {
    output.write(HYPHENS);
    output.write(boundary);
    output.write(NEW_LINE);
    final MediaType mediaType = item.getMediaType();
    final Class<?> type = item.getType();
    final Type genericType = item.getGenericType();
    final MessageBodyWriter writer = providers.getMessageBodyWriter(type, genericType, EMPTY, mediaType);
    if (writer == null) {
        throw new RuntimeException(
                String.format("Unable to find a MessageBodyWriter for media type '%s' and class '%s'", mediaType, type.getName()));
    }
    final MultivaluedMap<String, String> myHeaders = new MultivaluedMapImpl();
    String contentDispositionHeader = "form-data; name=\"" + item.getName() + '"';
    final String filename = item.getFilename();
    if (filename != null) {
        contentDispositionHeader += ("; filename=\"" + item.getFilename() + "\"");
    }
    myHeaders.putSingle("Content-Disposition", contentDispositionHeader);
    if (mediaType != null) {
        myHeaders.putSingle("Content-Type", mediaType.toString());
    }
    myHeaders.putAll(item.getHeaders());
    writeHeaders(myHeaders, output);
    writer.writeTo(item.getEntity(), type, genericType, EMPTY, mediaType, myHeaders, output);
    output.write(NEW_LINE);
}
 
Example #22
Source File: ProviderCache.java    From cxf with Apache License 2.0 5 votes vote down vote up
public List<ProviderInfo<MessageBodyWriter<?>>> getWriters(Class<?> type, MediaType mt) {
    if (writerProviderCache.isEmpty()) {
        return Collections.emptyList();
    }

    String key = getKey(type, mt);

    List<ProviderInfo<MessageBodyWriter<?>>> list = writerProviderCache.get(key);
    return list != null ? list : Collections.emptyList();
}
 
Example #23
Source File: JAXRSUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static List<MediaType> getProviderProduceTypes(MessageBodyWriter<?> provider) {
    String[] values = getUserMediaTypes(provider, false);
    if (values == null) {
        return getProduceTypes(provider.getClass().getAnnotation(Produces.class));
    }
    return JAXRSUtils.getMediaTypes(values);
}
 
Example #24
Source File: EverrestJetty.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
private boolean isRestResource(Class<?> resourceClass) {
    return resourceClass.isAnnotationPresent(Path.class) ||
           resourceClass.isAnnotationPresent(Provider.class) ||
           resourceClass.isAnnotationPresent(Filter.class) ||
           resourceClass.isAssignableFrom(ExceptionMapper.class) ||
           resourceClass.isAssignableFrom(ContextResolver.class) ||
           resourceClass.isAssignableFrom(MessageBodyReader.class) ||
           resourceClass.isAssignableFrom(MessageBodyWriter.class) ||
           resourceClass.isAssignableFrom(MethodInvokerFilter.class) ||
           resourceClass.isAssignableFrom(RequestFilter.class) ||
           resourceClass.isAssignableFrom(ResponseFilter.class);
}
 
Example #25
Source File: ProviderBinder.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Add per-request MessageBodyWriter.
 *
 * @param messageBodyWriter
 *         class of implementation MessageBodyWriter
 */
public void addMessageBodyWriter(Class<? extends MessageBodyWriter> messageBodyWriter) {
    try {
        ProviderDescriptor descriptor = new ProviderDescriptorImpl(messageBodyWriter);
        addMessageBodyWriter(new PerRequestObjectFactory<>(descriptor));
    } catch (Exception e) {
        LOG.error(String.format("Failed add MessageBodyWriter %s. %s", messageBodyWriter.getName(), e.getMessage()), e);
    }
}
 
Example #26
Source File: MultipartFormDataWriterTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
private MessageBodyWriter<String> mockStringMessageBodyWriter(OutputStream out) throws Exception {
    @SuppressWarnings({"unchecked"})
    MessageBodyWriter<String> messageBodyWriter = mock(MessageBodyWriter.class);
    doAnswer(invocation -> {
        Object[] arguments = invocation.getArguments();
        out.write(((String)arguments[0]).getBytes());
        return null;
    }).when(messageBodyWriter).writeTo(anyObject(), eq(String.class), any(), any(Annotation[].class), any(MediaType.class), any(), eq(out));
    return messageBodyWriter;
}
 
Example #27
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomProviderSortingMBWOnly() {
    ProviderFactory pf = ServerProviderFactory.getInstance();
    Comparator<ProviderInfo<MessageBodyWriter<?>>> comp =
        new Comparator<ProviderInfo<MessageBodyWriter<?>>>() {

        @Override
        public int compare(ProviderInfo<MessageBodyWriter<?>> o1, ProviderInfo<MessageBodyWriter<?>> o2) {
            MessageBodyWriter<?> provider1 = o1.getProvider();
            MessageBodyWriter<?> provider2 = o2.getProvider();
            if (provider1 instanceof StringTextProvider) {
                return 1;
            } else if (provider2 instanceof StringTextProvider) {
                return -1;
            } else {
                return 0;
            }
        }

    };
    pf.setProviderComparator(comp);

    // writers
    List<ProviderInfo<MessageBodyWriter<?>>> writers = pf.getMessageWriters();
    assertEquals(10, writers.size());
    Object lastWriter = writers.get(9).getProvider();
    assertTrue(lastWriter instanceof StringTextProvider);
    //readers
    List<ProviderInfo<MessageBodyReader<?>>> readers = pf.getMessageReaders();
    assertEquals(9, readers.size());
    Object lastReader = readers.get(8).getProvider();
    assertFalse(lastReader instanceof StringTextProvider);
}
 
Example #28
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomJaxbProvider() {
    ProviderFactory pf = ServerProviderFactory.getInstance();
    JAXBElementProvider<Book> provider = new JAXBElementProvider<>();
    pf.registerUserProvider(provider);
    MessageBodyReader<Book> customJaxbReader = pf.createMessageBodyReader(Book.class, null, null,
                                                          MediaType.TEXT_XML_TYPE, new MessageImpl());
    assertSame(customJaxbReader, provider);

    MessageBodyWriter<Book> customJaxbWriter = pf.createMessageBodyWriter(Book.class, null, null,
                                                          MediaType.TEXT_XML_TYPE, new MessageImpl());
    assertSame(customJaxbWriter, provider);
}
 
Example #29
Source File: SseEventSinkContextProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected SseEventSink createSseEventSink(final HttpServletRequest request,
        final MessageBodyWriter<OutboundSseEvent> writer,
        final AsyncResponse async, final Integer bufferSize) {
    if (bufferSize != null) {
        return new SseEventSinkImpl(writer, async, request.getAsyncContext(), bufferSize);
    } else {        
        return new SseEventSinkImpl(writer, async, request.getAsyncContext());
    }
}
 
Example #30
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testMessageBodyWriterString() throws Exception {
    ProviderFactory pf = ServerProviderFactory.getInstance();
    MessageBodyWriter<String> mbr = pf.createMessageBodyWriter(String.class, String.class, new Annotation[]{},
                               MediaType.APPLICATION_XML_TYPE, new MessageImpl());
    assertTrue(mbr instanceof StringTextProvider);
}