Search in sources :

Example 11 with MessageBodyWriter

use of javax.ws.rs.ext.MessageBodyWriter in project jersey by jersey.

the class ApplicationHandler method logApplicationInitConfiguration.

private static void logApplicationInitConfiguration(final InjectionManager injectionManager, final ResourceBag resourceBag, final ProcessingProviders processingProviders) {
    if (!LOGGER.isLoggable(Level.CONFIG)) {
        return;
    }
    final StringBuilder sb = new StringBuilder(LocalizationMessages.LOGGING_APPLICATION_INITIALIZED()).append('\n');
    final List<Resource> rootResourceClasses = resourceBag.getRootResources();
    if (!rootResourceClasses.isEmpty()) {
        sb.append(LocalizationMessages.LOGGING_ROOT_RESOURCE_CLASSES()).append(":");
        for (final Resource r : rootResourceClasses) {
            for (final Class clazz : r.getHandlerClasses()) {
                sb.append('\n').append("  ").append(clazz.getName());
            }
        }
    }
    sb.append('\n');
    final Set<MessageBodyReader> messageBodyReaders;
    final Set<MessageBodyWriter> messageBodyWriters;
    if (LOGGER.isLoggable(Level.FINE)) {
        Spliterator<MessageBodyReader> mbrSpliterator = Providers.getAllProviders(injectionManager, MessageBodyReader.class).spliterator();
        messageBodyReaders = StreamSupport.stream(mbrSpliterator, false).collect(Collectors.toSet());
        Spliterator<MessageBodyWriter> mbwSpliterator = Providers.getAllProviders(injectionManager, MessageBodyWriter.class).spliterator();
        messageBodyWriters = StreamSupport.stream(mbwSpliterator, false).collect(Collectors.toSet());
    } else {
        messageBodyReaders = Providers.getCustomProviders(injectionManager, MessageBodyReader.class);
        messageBodyWriters = Providers.getCustomProviders(injectionManager, MessageBodyWriter.class);
    }
    printProviders(LocalizationMessages.LOGGING_PRE_MATCH_FILTERS(), processingProviders.getPreMatchFilters(), sb);
    printProviders(LocalizationMessages.LOGGING_GLOBAL_REQUEST_FILTERS(), processingProviders.getGlobalRequestFilters(), sb);
    printProviders(LocalizationMessages.LOGGING_GLOBAL_RESPONSE_FILTERS(), processingProviders.getGlobalResponseFilters(), sb);
    printProviders(LocalizationMessages.LOGGING_GLOBAL_READER_INTERCEPTORS(), processingProviders.getGlobalReaderInterceptors(), sb);
    printProviders(LocalizationMessages.LOGGING_GLOBAL_WRITER_INTERCEPTORS(), processingProviders.getGlobalWriterInterceptors(), sb);
    printNameBoundProviders(LocalizationMessages.LOGGING_NAME_BOUND_REQUEST_FILTERS(), processingProviders.getNameBoundRequestFilters(), sb);
    printNameBoundProviders(LocalizationMessages.LOGGING_NAME_BOUND_RESPONSE_FILTERS(), processingProviders.getNameBoundResponseFilters(), sb);
    printNameBoundProviders(LocalizationMessages.LOGGING_NAME_BOUND_READER_INTERCEPTORS(), processingProviders.getNameBoundReaderInterceptors(), sb);
    printNameBoundProviders(LocalizationMessages.LOGGING_NAME_BOUND_WRITER_INTERCEPTORS(), processingProviders.getNameBoundWriterInterceptors(), sb);
    printProviders(LocalizationMessages.LOGGING_DYNAMIC_FEATURES(), processingProviders.getDynamicFeatures(), sb);
    printProviders(LocalizationMessages.LOGGING_MESSAGE_BODY_READERS(), messageBodyReaders.stream().map(new WorkersToStringTransform<>()).collect(Collectors.toList()), sb);
    printProviders(LocalizationMessages.LOGGING_MESSAGE_BODY_WRITERS(), messageBodyWriters.stream().map(new WorkersToStringTransform<>()).collect(Collectors.toList()), sb);
    LOGGER.log(Level.CONFIG, sb.toString());
}
Also used : MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) Resource(org.glassfish.jersey.server.model.Resource) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter)

Example 12 with MessageBodyWriter

use of javax.ws.rs.ext.MessageBodyWriter in project jersey by jersey.

the class RequestUtil method getEntityParameters.

/**
     * Returns the form parameters from a request entity as a multi-valued map.
     * If the request does not have a POST method, or the media type is not
     * x-www-form-urlencoded, then null is returned.
     *
     * @param request the client request containing the entity to extract parameters from.
     * @return a {@link javax.ws.rs.core.MultivaluedMap} containing the entity form parameters.
     */
@SuppressWarnings("unchecked")
public static MultivaluedMap<String, String> getEntityParameters(ClientRequestContext request, MessageBodyWorkers messageBodyWorkers) {
    Object entity = request.getEntity();
    String method = request.getMethod();
    MediaType mediaType = request.getMediaType();
    // no entity, not a post or not x-www-form-urlencoded: return empty map
    if (entity == null || method == null || !HttpMethod.POST.equalsIgnoreCase(method) || mediaType == null || !mediaType.equals(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) {
        return new MultivaluedHashMap<String, String>();
    }
    // it's ready to go if already expressed as a multi-valued map
    if (entity instanceof MultivaluedMap) {
        return (MultivaluedMap<String, String>) entity;
    }
    Type entityType = entity.getClass();
    // if the entity is generic, get specific type and class
    if (entity instanceof GenericEntity) {
        final GenericEntity generic = (GenericEntity) entity;
        // overwrite
        entityType = generic.getType();
        entity = generic.getEntity();
    }
    final Class entityClass = entity.getClass();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    MessageBodyWriter writer = messageBodyWorkers.getMessageBodyWriter(entityClass, entityType, EMPTY_ANNOTATIONS, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
    try {
        writer.writeTo(entity, entityClass, entityType, EMPTY_ANNOTATIONS, MediaType.APPLICATION_FORM_URLENCODED_TYPE, null, out);
    } catch (WebApplicationException wae) {
        throw new IllegalStateException(wae);
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe);
    }
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    MessageBodyReader reader = messageBodyWorkers.getMessageBodyReader(MultivaluedMap.class, MultivaluedMap.class, EMPTY_ANNOTATIONS, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
    try {
        return (MultivaluedMap<String, String>) reader.readFrom(MultivaluedMap.class, MultivaluedMap.class, EMPTY_ANNOTATIONS, MediaType.APPLICATION_FORM_URLENCODED_TYPE, null, in);
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) MediaType(javax.ws.rs.core.MediaType) Type(java.lang.reflect.Type) ByteArrayInputStream(java.io.ByteArrayInputStream) GenericEntity(javax.ws.rs.core.GenericEntity) MediaType(javax.ws.rs.core.MediaType) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter)

Example 13 with MessageBodyWriter

use of javax.ws.rs.ext.MessageBodyWriter in project cxf by apache.

the class ProviderFactoryTest method testRegisterMbrMbwProviderAsMbrOnly.

@Test
public void testRegisterMbrMbwProviderAsMbrOnly() {
    ServerProviderFactory pf = ServerProviderFactory.getInstance();
    JAXBElementProvider<Book> customProvider = new JAXBElementProvider<Book>();
    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);
}
Also used : Arrays(java.util.Arrays) Produces(javax.ws.rs.Produces) Priorities(javax.ws.rs.Priorities) ExceptionMapper(javax.ws.rs.ext.ExceptionMapper) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) ParamConverter(javax.ws.rs.ext.ParamConverter) ContextResolver(javax.ws.rs.ext.ContextResolver) JAXBContextProvider2(org.apache.cxf.jaxrs.JAXBContextProvider2) MediaType(javax.ws.rs.core.MediaType) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) ParamConverterProvider(javax.ws.rs.ext.ParamConverterProvider) JAXBContextProvider(org.apache.cxf.jaxrs.JAXBContextProvider) SuperBook(org.apache.cxf.jaxrs.resources.SuperBook) Collection(java.util.Collection) ExchangeImpl(org.apache.cxf.message.ExchangeImpl) Customer(org.apache.cxf.jaxrs.Customer) Priority(javax.annotation.Priority) List(java.util.List) WriterInterceptorContext(javax.ws.rs.ext.WriterInterceptorContext) Response(javax.ws.rs.core.Response) Type(java.lang.reflect.Type) Annotation(java.lang.annotation.Annotation) WebApplicationException(javax.ws.rs.WebApplicationException) Bus(org.apache.cxf.Bus) MessageImpl(org.apache.cxf.message.MessageImpl) Feature(javax.ws.rs.core.Feature) DataHandler(javax.activation.DataHandler) Schema(javax.xml.validation.Schema) ArrayList(java.util.ArrayList) ProviderInfo(org.apache.cxf.jaxrs.model.ProviderInfo) WriterInterceptor(javax.ws.rs.ext.WriterInterceptor) Status(javax.ws.rs.core.Response.Status) JAXBContext(javax.xml.bind.JAXBContext) WebApplicationExceptionMapper(org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper) Before(org.junit.Before) OutputStream(java.io.OutputStream) Iterator(java.util.Iterator) CustomerParameterHandler(org.apache.cxf.jaxrs.CustomerParameterHandler) Message(org.apache.cxf.message.Message) IOUtils(org.apache.cxf.helpers.IOUtils) IOException(java.io.IOException) Test(org.junit.Test) EasyMock(org.easymock.EasyMock) XmlRootElement(javax.xml.bind.annotation.XmlRootElement) Book(org.apache.cxf.jaxrs.resources.Book) Exchange(org.apache.cxf.message.Exchange) File(java.io.File) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) AbstractResourceInfo(org.apache.cxf.jaxrs.model.AbstractResourceInfo) Endpoint(org.apache.cxf.endpoint.Endpoint) BusFactory(org.apache.cxf.BusFactory) DataSource(javax.activation.DataSource) Comparator(java.util.Comparator) Assert(org.junit.Assert) Collections(java.util.Collections) InputStream(java.io.InputStream) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) SuperBook(org.apache.cxf.jaxrs.resources.SuperBook) Book(org.apache.cxf.jaxrs.resources.Book) MessageImpl(org.apache.cxf.message.MessageImpl) Test(org.junit.Test)

Example 14 with MessageBodyWriter

use of javax.ws.rs.ext.MessageBodyWriter in project cxf by apache.

the class BinaryDataProviderTest method testWriteTo.

@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);
    assertTrue(Arrays.equals(new String("hi").getBytes(), os.toByteArray()));
    ByteArrayInputStream is = new ByteArrayInputStream("hi".getBytes());
    os = new ByteArrayOutputStream();
    p.writeTo(is, null, null, null, null, null, os);
    assertTrue(Arrays.equals(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);
    assertTrue(Arrays.equals(os.toByteArray(), new String("hi").getBytes()));
    os = new ByteArrayOutputStream();
    p.writeTo(new StreamingOutputImpl(), null, null, null, MediaType.valueOf("text/xml"), null, os);
    assertTrue(Arrays.equals(os.toByteArray(), new String("hi").getBytes()));
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) StringReader(java.io.StringReader) Reader(java.io.Reader) StringReader(java.io.StringReader) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) Test(org.junit.Test)

Example 15 with MessageBodyWriter

use of javax.ws.rs.ext.MessageBodyWriter in project cxf by apache.

the class PrimitiveTextProviderTest method testWriteBoolean.

@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testWriteBoolean() throws Exception {
    MessageBodyWriter p = new PrimitiveTextProvider();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    p.writeTo(Boolean.TRUE, null, null, null, MediaType.TEXT_PLAIN_TYPE, null, os);
    assertTrue(Arrays.equals(new String("true").getBytes(), os.toByteArray()));
    os = new ByteArrayOutputStream();
    final boolean value = true;
    p.writeTo(value, null, null, null, MediaType.TEXT_PLAIN_TYPE, null, os);
    assertTrue(Arrays.equals(new String("true").getBytes(), os.toByteArray()));
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) Test(org.junit.Test)

Aggregations

MessageBodyWriter (javax.ws.rs.ext.MessageBodyWriter)25 MediaType (javax.ws.rs.core.MediaType)10 Test (org.junit.Test)10 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 OutputStreamWriter (java.io.OutputStreamWriter)6 Writer (java.io.Writer)6 Type (java.lang.reflect.Type)6 IOException (java.io.IOException)5 MessageBodyReader (javax.ws.rs.ext.MessageBodyReader)5 List (java.util.List)4 Map (java.util.Map)4 WebApplicationException (javax.ws.rs.WebApplicationException)4 MultivaluedMap (javax.ws.rs.core.MultivaluedMap)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 OutputStream (java.io.OutputStream)3 Annotation (java.lang.annotation.Annotation)3 ArrayList (java.util.ArrayList)3 Produces (javax.ws.rs.Produces)3 InjectionManager (org.glassfish.jersey.internal.inject.InjectionManager)3 File (java.io.File)2