java类javax.ws.rs.ext.MessageBodyWriter的实例源码

JerseyApplication.java 文件源码 项目:gitplex-mit 阅读 27 收藏 0 点赞 0 评论 0
@Inject
public JerseyApplication(ServiceLocator serviceLocator) {
    GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
    GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
    guiceBridge.bridgeGuiceInjector(AppLoader.injector);

    String disableMoxy = PropertiesHelper.getPropertyNameForRuntime(
            CommonProperties.MOXY_JSON_FEATURE_DISABLE,
               getConfiguration().getRuntimeType());
       property(disableMoxy, true);
       property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);

       // add the default Jackson exception mappers
       register(JsonParseExceptionMapper.class);
       register(JsonMappingExceptionMapper.class);
       register(JacksonJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);

       packages(JerseyApplication.class.getPackage().getName());

    for (JerseyConfigurator configurator: AppLoader.getExtensions(JerseyConfigurator.class)) {
        configurator.configure(this);
    }
}
Issue1341.java 文件源码 项目:GitHub 阅读 23 收藏 0 点赞 0 评论 0
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)) {
        //DisableCircularReferenceDetect
        FastJsonProvider fastJsonProvider = new FastJsonProvider();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.BrowserSecure);

        fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect);

        fastJsonProvider.setFastJsonConfig(fastJsonConfig);

        context.register(fastJsonProvider, MessageBodyReader.class, MessageBodyWriter.class);
    }
    return true;
}
ValueMessageBodyWriter.java 文件源码 项目:dropwizard-vavr 阅读 26 收藏 0 点赞 0 评论 0
/**
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked")
@Override
public void writeTo(Value<?> entity,
                    Class<?> type,
                    Type genericType,
                    Annotation[] annotations,
                    MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream)
        throws IOException {
    final Object entityValue = entity.getOrElseThrow(() -> EmptyValueException.INSTANCE);
    final Class<?> entityClass = entityValue.getClass();

    final Type actualGenericTypeArgument;
    if (genericType instanceof ParameterizedType) {
        actualGenericTypeArgument = ((ParameterizedType) genericType).getActualTypeArguments()[0];
    } else {
        actualGenericTypeArgument = entityClass;
    }

    final MessageBodyWriter writer = mbw.get().getMessageBodyWriter(entityClass, actualGenericTypeArgument, annotations, mediaType);
    writer.writeTo(entityValue, entityClass, actualGenericTypeArgument, annotations, mediaType, httpHeaders, entityStream);
}
MinijaxApplication.java 文件源码 项目:minijax 阅读 32 收藏 0 点赞 0 评论 0
@SuppressWarnings("rawtypes")
private MediaType findResponseType(
        final Object obj,
        final List<MediaType> produces) {

    final Class<?> objType = obj == null ? null : obj.getClass();

    for (final MediaType mediaType : produces) {
        final MessageBodyWriter writer = providers.getMessageBodyWriter(objType, null, null, mediaType);
        if (writer != null) {
            return mediaType;
        }
    }

    return MediaType.TEXT_PLAIN_TYPE;
}
MinijaxProviders.java 文件源码 项目:minijax 阅读 25 收藏 0 点赞 0 评论 0
@SuppressWarnings("unchecked")
public void register(final Class<?> c) {
    if (MessageBodyReader.class.isAssignableFrom(c)) {
        readers.add((Class<MessageBodyReader<?>>) c, MediaTypeUtils.parseMediaTypes(c.getAnnotation(Consumes.class)));
    }

    if (MessageBodyWriter.class.isAssignableFrom(c)) {
        writers.add((Class<MessageBodyWriter<?>>) c, MediaTypeUtils.parseMediaTypes(c.getAnnotation(Produces.class)));
    }

    if (ExceptionMapper.class.isAssignableFrom(c)) {
        exceptionMappers.add((Class<ExceptionMapper<?>>) c, MediaTypeUtils.parseMediaTypes(c.getAnnotation(Produces.class)));
    }

    if (ParamConverterProvider.class.isAssignableFrom(c)) {
        paramConverterProviders.add((ParamConverterProvider) application.get(c));
    }
}
AdditionalRegistrationTest.java 文件源码 项目:microprofile-rest-client 阅读 26 收藏 0 点赞 0 评论 0
@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());
    }
}
AdditionalRegistrationTest.java 文件源码 项目:microprofile-rest-client 阅读 23 收藏 0 点赞 0 评论 0
@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());
    }
}
FastJsonFeature.java 文件源码 项目:JerseyRestful 阅读 22 收藏 0 点赞 0 评论 0
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;
}
JacksonFeature.java 文件源码 项目:micro-server 阅读 26 收藏 0 点赞 0 评论 0
@Override
  public boolean configure(final FeatureContext context) {

    PluginLoader.INSTANCE.plugins.get().stream()
.filter(module -> module.jacksonFeatureProperties()!=null)
.map(Plugin::jacksonFeatureProperties)
.map(fn->fn.apply(context))
.forEach(map -> {
    addAll(map,context);
});


      JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
        provider.setMapper(JacksonUtil.getMapper());
          context.register(provider, new Class[]{MessageBodyReader.class, MessageBodyWriter.class});

      return true;
  }
BlobStoreResource.java 文件源码 项目:swiftproxy 阅读 107 收藏 0 点赞 0 评论 0
private void debugWrite(Object root, MediaType format) {

        MessageBodyWriter messageBodyWriter =
                workers.getMessageBodyWriter(root.getClass(), root.getClass(),
                        new Annotation[]{}, format);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            // use the MBW to serialize myBean into baos
            messageBodyWriter.writeTo(root,
                    root.getClass(), root.getClass(), new Annotation[]{},
                    format, new MultivaluedHashMap<String, Object>(),
                    baos);
        } catch (Throwable e) {
            logger.error(String.format("could not serialize %s to format %s", root, format), e);
            throw propagate(e);
        }

        logger.info("{}", baos);
    }
MultipartUploadRepresentationMessageBodyWriter.java 文件源码 项目:blaze-storage 阅读 21 收藏 0 点赞 0 评论 0
@Override
public void writeTo(MultipartUploadRepresentation o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    Class<BucketObjectUpdateRepresentation> writerType = BucketObjectUpdateRepresentation.class;
    Type writerGenericType = writerType;
    Annotation[] writerAnnotations = new Annotation[0];

    MessageBodyWriter<BucketObjectUpdateRepresentation> writer = providers.getMessageBodyWriter(writerType, writerGenericType, writerAnnotations, MediaType.WILDCARD_TYPE);

    String boundary = UUID.randomUUID().toString();
    httpHeaders.putSingle(BlazeStorageHeaders.QUIET, Boolean.toString(o.isQuiet()));
    httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString() + "; boundary=" + boundary);
    byte[] boundaryBytes = ("--" + boundary).getBytes();

    for (Map.Entry<String, BucketObjectUpdateRepresentation> entry : o.getUploads().entrySet()) {
        BucketObjectUpdateRepresentation value = entry.getValue();
        MediaType writerMediaType = MediaType.valueOf(value.getContentType());
        MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>();
        headers.add(BlazeStorageHeaders.MULTIPART_KEY, entry.getKey());

        entityStream.write(boundaryBytes);
        entityStream.write("\r\n".getBytes());
        writer.writeTo(entry.getValue(), writerType, writerGenericType, writerAnnotations, writerMediaType, headers, new HeaderFlushedOutputStream(headers, entityStream));
        entityStream.write("\r\n".getBytes());
    }

    entityStream.write(boundaryBytes);
    entityStream.write("--".getBytes());
}
RESTAppBase.java 文件源码 项目:r01fb 阅读 31 收藏 0 点赞 0 评论 0
@Override
public Set<Class<?>> getClasses() {
    Set<Class<?>> s = new HashSet<Class<?>>();

    // rest Resources
    Set<Class<? extends RESTResource>> restResourceTypes = this.getRESTResourceTypes();
    if (CollectionUtils.hasData(restResourceTypes)) s.addAll(restResourceTypes);

    // Request received objects mappers: transforms Java->XML for REST methods param types
    Set<Class<? extends MessageBodyReader<?>>> reqReceivedTypesMappers = this.getRequestReceivedTypesMappers();
    if (CollectionUtils.hasData(reqReceivedTypesMappers)) s.addAll(reqReceivedTypesMappers);

    // Response sent objects mappers: transforms Java->XML for REST methods return types
    Set<Class<? extends MessageBodyWriter<?>>> respSentTypesMappers = this.getResponseSentTypesMappers();
    if (CollectionUtils.hasData(respSentTypesMappers)) s.addAll(respSentTypesMappers);

    // Exception Mappers
    Set<Class<? extends ExceptionMapper<?>>> expsMappers = this.getExceptionsMappers();
    if (CollectionUtils.hasData(expsMappers)) s.addAll(expsMappers);        

    return s;
}
JsonWebKeySetProvider.java 文件源码 项目:openid-connect 阅读 23 收藏 0 点赞 0 评论 0
@Override
public void writeTo(final JsonWebKeySet jwks,
        final Class<?> type,
        final Type genericType,
        final Annotation[] annotations,
        final MediaType mediaType,
        final MultivaluedMap<String, Object> httpHeaders,
        final OutputStream os) throws IOException,
        WebApplicationException {

    final MessageBodyWriter<JsonWebKey> writer = providers.getMessageBodyWriter(JsonWebKey.class, JsonWebKey.class, annotations, mediaType);
    final JsonArrayBuilder keysArray = Json.createArrayBuilder();
    for (final JsonWebKey key : jwks.getKeys()) {
        final ByteArrayOutputStream keyStream = new ByteArrayOutputStream();
        writer.writeTo(key, JsonWebKey.class, null, annotations, mediaType, null, keyStream);
        keyStream.close();
        keysArray.add(Json.createReader(new ByteArrayInputStream(keyStream.toByteArray()))
                .readObject());
    }
    final JsonObject jwksObject = Json.createObjectBuilder()
            .add("keys", keysArray)
            .build();
    final JsonWriter w = Json.createWriter(os);
    w.write(jwksObject);
    w.close();
}
ErrorPageGenerator.java 文件源码 项目:ameba 阅读 24 收藏 0 点赞 0 评论 0
/**
 * <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);
    }
}
OptionalMessageBodyWriter.java 文件源码 项目:dropwizard-java8 阅读 28 收藏 0 点赞 0 评论 0
@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);
}
FastJsonFeature.java 文件源码 项目:fastjson-jaxrs-json-provider 阅读 27 收藏 0 点赞 0 评论 0
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;
}
UriTemplateApplication.java 文件源码 项目:Handy-URI-Templates-WebApp 阅读 28 收藏 0 点赞 0 评论 0
/**
 * Create a new UriTemplateApplication.
 * 
 */
public UriTemplateApplication()
{
   registerClasses(UriTemplateResource.class);
   registerClasses(SchemaResource.class);
   register(new Feature()
   {

      @Override
      public boolean configure(final FeatureContext context)
      {
         final String disableMoxy = CommonProperties.MOXY_JSON_FEATURE_DISABLE + '.'
               + context.getConfiguration().getRuntimeType().name().toLowerCase();
         context.property(disableMoxy, true);

         context.register(JacksonJaxbJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
         return true;
      }

   });
}
EnvelopedWriter.java 文件源码 项目:jersey-smime 阅读 23 收藏 0 点赞 0 评论 0
@SuppressWarnings("unchecked")
public static MimeBodyPart createBodyPart(Providers providers, SMIMEOutput out) throws IOException, MessagingException {
    ByteArrayOutputStream bodyOs = new ByteArrayOutputStream();
    MessageBodyWriter writer = providers.getMessageBodyWriter(out.getType(), out.getGenericType(), null, out.getMediaType());

    if (writer == null) {
        throw new RuntimeException("Failed to find writer for type: " + out.getType().getName());
    }

    MultivaluedMap<String, String> bodyHeaders = new MultivaluedHashMap<String, String>();
    bodyHeaders.add("Content-Type", out.getMediaType().toString());
    writer.writeTo(out.getEntity(), out.getType(), out.getGenericType(), null, out.getMediaType(), bodyHeaders, bodyOs);


    InternetHeaders ih = new InternetHeaders();

    for (Map.Entry<String, List<String>> entry : bodyHeaders.entrySet()) {
        for (String value : entry.getValue()) {
            ih.addHeader(entry.getKey(), value);
        }
    }
    return new MimeBodyPart(ih, bodyOs.toByteArray());
}
OccurrenceDwcXMLBodyWriterTest.java 文件源码 项目:occurrence 阅读 19 收藏 0 点赞 0 评论 0
@Test
public void testOccurrenceXML() throws IOException {
  MessageBodyWriter<Occurrence> occurrenceDwcXMLBodyWriter = new OccurrenceDwcXMLBodyWriter();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  Occurrence occ = new Occurrence();

  occ.setCountry(Country.MADAGASCAR);
  occ.setVerbatimField(DwcTerm.verbatimLocality, "mad");
  occ.setReferences(URI.create("http://www.gbif.org"));

  Term customTerm = TermFactory.instance().findTerm("MyTerm");
  occ.setVerbatimField(customTerm, "MyTerm value");

  occurrenceDwcXMLBodyWriter.writeTo(occ, null, null, null, null, null, baos);

  String expectedContent = IOUtils.toString(new FileInputStream(FileUtils.getClasspathFile("dwc_xml/occurrence.xml")));
  assertEquals(CharMatcher.WHITESPACE.removeFrom(expectedContent), CharMatcher.WHITESPACE.removeFrom(baos.toString()));
}
ComponentTestCase.java 文件源码 项目:Mastering-Java-EE-Development-with-WildFly 阅读 24 收藏 0 点赞 0 评论 0
@Test
public void testConfiguration() throws Exception {
    logger.info("start REST Configuration test");
    Client client = newClient();
    Configuration configuration = client.getConfiguration();
    Set<Class<?>> classes = configuration.getClasses();
    for (Class<?> clazz : classes) {
        assertTrue("verify if the class is a rest component or provider",
                MessageBodyReader.class.isAssignableFrom(clazz) || MessageBodyWriter.class.isAssignableFrom(clazz)
                        || clazz.isAnnotationPresent(Provider.class)
                        || DynamicFeature.class.isAssignableFrom(clazz));
        Map<Class<?>, Integer> contracts = configuration.getContracts(clazz);
        assertFalse("each class has different contracts", contracts.isEmpty());
        for (Class<?> contract : contracts.keySet()) {
            int value = contracts.get(contract);
            assertTrue("verify if the contract is a rest component or provider",
                    value == 5000 || value == 4000 || value == 3000 || value == 0);
        }
    }
    Set<Object> instances = configuration.getInstances();
    assertTrue("by default there are not instances", instances.isEmpty());
    Map<String, Object> properties = configuration.getProperties();
    assertTrue("by default there are not properties", properties.isEmpty());
    MyComponent myComponent = new MyComponent();
    client.register(myComponent);
    instances = configuration.getInstances();
    assertFalse("Added instance", instances.isEmpty());
    for (Object instance : instances) {
        if (instance instanceof MyComponent)
            assertTrue("MyComponent is registered and active", configuration.isEnabled((Feature) instance));
    }
    assertEquals("Added property through MyComponent", 1, properties.size());
    boolean property = (Boolean) properties.get("configured_myComponent");
    assertEquals("configured_myComponent ok!", true, property);
    assertEquals("type CLIENT by default", CLIENT, configuration.getRuntimeType());
}
EitherMessageBodyWriter.java 文件源码 项目:dropwizard-vavr 阅读 24 收藏 0 点赞 0 评论 0
/**
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked")
@Override
public void writeTo(Either<?, ?> entity,
                    Class<?> type,
                    Type genericType,
                    Annotation[] annotations,
                    MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream)
        throws IOException {
    final Object entityValue;
    final int typeArgumentIndex;
    if (entity.isLeft()) {
        entityValue = entity.getLeft();
        typeArgumentIndex = 0;
    } else {
        entityValue = entity.get();
        typeArgumentIndex = 1;
    }
    final Class<?> entityClass = entityValue.getClass();

    final Type actualGenericTypeArgument;
    if (genericType instanceof ParameterizedType) {
        actualGenericTypeArgument = ((ParameterizedType) genericType).getActualTypeArguments()[typeArgumentIndex];
    } else {
        actualGenericTypeArgument = entityClass;
    }

    final MessageBodyWriter writer = mbw.get().getMessageBodyWriter(entityClass,
            actualGenericTypeArgument, annotations, mediaType);
    writer.writeTo(entityValue, entityClass,
            actualGenericTypeArgument,
            annotations, mediaType, httpHeaders, entityStream);
}
SupportedMediaTypesScanner.java 文件源码 项目:dotwebstack-framework 阅读 20 收藏 0 点赞 0 评论 0
@Autowired
public SupportedMediaTypesScanner(
    @NonNull List<MessageBodyWriter<GraphEntity>> graphEntityWriters,
    @NonNull List<MessageBodyWriter<TupleEntity>> tupleEntityWriters) {
  loadSupportedMediaTypes(graphEntityWriters, graphMediaTypes, this.graphEntityWriters);
  loadSupportedMediaTypes(tupleEntityWriters, tupleMediaTypes, this.tupleEntityWriters);
}
SupportedMediaTypesScanner.java 文件源码 项目:dotwebstack-framework 阅读 22 收藏 0 点赞 0 评论 0
private <T> void loadSupportedMediaTypes(List<MessageBodyWriter<T>> entityWriters,
    List<MediaType> list, List<MessageBodyWriter<T>> resultingList) {

  entityWriters.forEach(writer -> {
    Class<?> entityWriterClass = writer.getClass();
    EntityWriter providerAnnotation = entityWriterClass.getAnnotation(EntityWriter.class);
    Produces produceAnnotation = entityWriterClass.getAnnotation(Produces.class);

    if (providerAnnotation == null) {
      LOG.warn(
          String.format("Found writer that did not specify the EntityWriter annotation correctly."
              + " Skipping %s", writer.getClass()));
      return;
    }

    if (produceAnnotation == null) {
      LOG.warn(String.format(
          "Found writer that did not specify the Produce annotation correctly. Skipping %s",
          writer.getClass()));
      return;
    }

    addMediaTypes(list, produceAnnotation);
    resultingList.add(writer);
    LOG.info(String.format("Registered %s writer for results.", writer.getClass()));
  });
}
JacksonFeature.java 文件源码 项目:payara-micro-docker-starter-kit 阅读 30 收藏 0 点赞 0 评论 0
public boolean configure(FeatureContext context) {
    context.property("jersey.config.server.disableMoxyJson", Boolean.valueOf(true));
    Configuration config = context.getConfiguration();
    context.property(getPropertyNameForRuntime("jersey.config.jsonFeature", config.getRuntimeType()), JSON_FEATURE);
    if (!config.isRegistered(JacksonJaxbJsonProvider.class)) {
        context.register(JsonParseExceptionMapper.class);
        context.register(JsonMappingExceptionMapper.class);
        context.register(JacksonJaxbJsonProvider.class, new Class[]{MessageBodyReader.class, MessageBodyWriter.class});
    }

    return true;
}
WriterTest.java 文件源码 项目:minijax 阅读 26 收藏 0 点赞 0 评论 0
@Test
@SuppressWarnings("unchecked")
public void testWriteMap() throws IOException {
    final Map<String, String> map = new HashMap<>();
    map.put("key", "value");

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final MessageBodyWriter<Map<String, String>> mapWriter = (MessageBodyWriter<Map<String, String>>) writer;
    mapWriter.writeTo(map, Map.class, null, null, MediaType.APPLICATION_JSON_TYPE, null, outputStream);
    assertEquals("{\"key\":\"value\"}", outputStream.toString());
}
WriterTest.java 文件源码 项目:minijax 阅读 22 收藏 0 点赞 0 评论 0
@Test
@SuppressWarnings("unchecked")
public void testWriteWidget() throws IOException {
    final Widget widget = new Widget();
    widget.id = "456";
    widget.value = "foobar";

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final MessageBodyWriter<Widget> widgetWriter = (MessageBodyWriter<Widget>) writer;
    widgetWriter.writeTo(widget, Widget.class, null, null, MediaType.APPLICATION_JSON_TYPE, null, outputStream);
    assertEquals("{\"id\":\"456\",\"value\":\"foobar\"}", outputStream.toString());
}
MinijaxApplication.java 文件源码 项目:minijax 阅读 25 收藏 0 点赞 0 评论 0
@SuppressWarnings({ "rawtypes", "unchecked" })
public void write(
        final MinijaxRequestContext context,
        final Response response,
        final HttpServletResponse servletResponse)
                throws IOException {

    servletResponse.setStatus(response.getStatus());

    for (final Entry<String, List<Object>> entry : response.getHeaders().entrySet()) {
        final String name = entry.getKey();
        for (final Object value : entry.getValue()) {
            servletResponse.addHeader(name, value.toString());
        }
    }

    if (context.getMethod().equals("OPTIONS")) {
        return;
    }

    final MediaType mediaType = response.getMediaType();
    if (mediaType != null) {
        servletResponse.setContentType(mediaType.toString());
    }

    final Object obj = response.getEntity();
    if (obj == null) {
        return;
    }

    final MessageBodyWriter writer = providers.getMessageBodyWriter(obj.getClass(), null, null, mediaType);
    if (writer != null) {
        writer.writeTo(obj, obj.getClass(), null, null, mediaType, null, servletResponse.getOutputStream());
        return;
    }

    // What to do
    servletResponse.getWriter().println(obj.toString());
}
MinijaxProviders.java 文件源码 项目:minijax 阅读 28 收藏 0 点赞 0 评论 0
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public <T> MessageBodyWriter<T> getMessageBodyWriter(
        final Class<T> type,
        final Type genericType,
        final Annotation[] annotations,
        final MediaType mediaType) {

    if (STRING_WRITER.isWriteable(type, genericType, annotations, mediaType)) {
        return (MessageBodyWriter<T>) STRING_WRITER;
    }

    if (INPUT_STREAM_WRITER.isWriteable(type, genericType, annotations, mediaType)) {
        return (MessageBodyWriter<T>) INPUT_STREAM_WRITER;
    }

    if (FILE_WRITER.isWriteable(type, genericType, annotations, mediaType)) {
        return (MessageBodyWriter<T>) FILE_WRITER;
    }

    for (final Class<? extends MessageBodyWriter<?>> writerClass : writers.get(mediaType)) {
        final MessageBodyWriter writer = application.get(writerClass);
        if (writer.isWriteable(type, genericType, annotations, mediaType)) {
            return writer;
        }
    }
    return null;
}
JsonJacksonFeature.java 文件源码 项目:webserver 阅读 30 收藏 0 点赞 0 评论 0
@Override
public boolean configure(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 Jackson.
  if (!config.isRegistered(JacksonJaxbJsonProvider.class)) {
    // add the Jackson exception mappers with application/json output
    context.register(JsonMappingExceptionMapper.class);
    context.register(JsonParseExceptionMapper.class);

    if (EntityFilteringFeature.enabled(config)) {
      context.register(JacksonFilteringFeature.class);
      context.register(FilteringJacksonJaxbJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
    } else {
      context.register(JacksonJaxbJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
    }
  }

  return true;
}
AdditionalRegistrationTest.java 文件源码 项目:microprofile-rest-client 阅读 23 收藏 0 点赞 0 评论 0
@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");
}


问题


面经


文章

微信
公众号

扫码关注公众号