當前位置: 首頁>>代碼示例>>Java>>正文


Java MessageBodyWriter類代碼示例

本文整理匯總了Java中javax.ws.rs.ext.MessageBodyWriter的典型用法代碼示例。如果您正苦於以下問題:Java MessageBodyWriter類的具體用法?Java MessageBodyWriter怎麽用?Java MessageBodyWriter使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


MessageBodyWriter類屬於javax.ws.rs.ext包,在下文中一共展示了MessageBodyWriter類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: JerseyApplication

import javax.ws.rs.ext.MessageBodyWriter; //導入依賴的package包/類
@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);
    }
}
 
開發者ID:jmfgdev,項目名稱:gitplex-mit,代碼行數:24,代碼來源:JerseyApplication.java

示例2: shouldRegisterAMultiTypedProviderInstanceWithPriorities

import javax.ws.rs.ext.MessageBodyWriter; //導入依賴的package包/類
@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());
    }
}
 
開發者ID:eclipse,項目名稱:microprofile-rest-client,代碼行數:25,代碼來源:AdditionalRegistrationTest.java

示例3: configure

import javax.ws.rs.ext.MessageBodyWriter; //導入依賴的package包/類
@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;
  }
 
開發者ID:aol,項目名稱:micro-server,代碼行數:19,代碼來源:JacksonFeature.java

示例4: configure

import javax.ws.rs.ext.MessageBodyWriter; //導入依賴的package包/類
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;
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:26,代碼來源:Issue1341.java

示例5: writeTo

import javax.ws.rs.ext.MessageBodyWriter; //導入依賴的package包/類
/**
 * {@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);
}
 
開發者ID:dropwizard,項目名稱:dropwizard-vavr,代碼行數:27,代碼來源:ValueMessageBodyWriter.java

示例6: findResponseType

import javax.ws.rs.ext.MessageBodyWriter; //導入依賴的package包/類
@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;
}
 
開發者ID:minijax,項目名稱:minijax,代碼行數:17,代碼來源:MinijaxApplication.java

示例7: register

import javax.ws.rs.ext.MessageBodyWriter; //導入依賴的package包/類
@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));
    }
}
 
開發者ID:minijax,項目名稱:minijax,代碼行數:19,代碼來源:MinijaxProviders.java

示例8: shouldRegisterAMultiTypedProviderClassWithPriorities

import javax.ws.rs.ext.MessageBodyWriter; //導入依賴的package包/類
@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());
    }
}
 
開發者ID:eclipse,項目名稱:microprofile-rest-client,代碼行數:23,代碼來源:AdditionalRegistrationTest.java

示例9: configure

import javax.ws.rs.ext.MessageBodyWriter; //導入依賴的package包/類
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;
}
 
開發者ID:ChineseLincoln,項目名稱:JerseyRestful,代碼行數:17,代碼來源:FastJsonFeature.java

示例10: debugWrite

import javax.ws.rs.ext.MessageBodyWriter; //導入依賴的package包/類
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);
    }
 
開發者ID:bouncestorage,項目名稱:swiftproxy,代碼行數:20,代碼來源:BlobStoreResource.java

示例11: writeTo

import javax.ws.rs.ext.MessageBodyWriter; //導入依賴的package包/類
@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());
}
 
開發者ID:Blazebit,項目名稱:blaze-storage,代碼行數:29,代碼來源:MultipartUploadRepresentationMessageBodyWriter.java

示例12: getClasses

import javax.ws.rs.ext.MessageBodyWriter; //導入依賴的package包/類
@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;
}
 
開發者ID:opendata-euskadi,項目名稱:r01fb,代碼行數:23,代碼來源:RESTAppBase.java

示例13: writeTo

import javax.ws.rs.ext.MessageBodyWriter; //導入依賴的package包/類
@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();
}
 
開發者ID:trajano,項目名稱:openid-connect,代碼行數:27,代碼來源:JsonWebKeySetProvider.java

示例14: writeViewable

import javax.ws.rs.ext.MessageBodyWriter; //導入依賴的package包/類
/**
 * <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);
    }
}
 
開發者ID:icode,項目名稱:ameba,代碼行數:26,代碼來源:ErrorPageGenerator.java

示例15: writeTo

import javax.ws.rs.ext.MessageBodyWriter; //導入依賴的package包/類
@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);
}
 
開發者ID:dropwizard,項目名稱:dropwizard-java8,代碼行數:23,代碼來源:OptionalMessageBodyWriter.java


注:本文中的javax.ws.rs.ext.MessageBodyWriter類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。