Java 代码实例

・12 分钟阅读

以下是展示如何使用的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1

@SuppressWarnings({"rawtypes", "unchecked"})
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);

实例 2

public void writeTo(EntryModel<?> t, Class<?> type, Type genericType,
        Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> httpHeaders,
        OutputStream entityStream) throws IOException {
    Entry entry = t.getEntry();
    MessageBodyWriter<Entry> writer = workers.getMessageBodyWriter(
            Entry.class, Entry.class, annotations, mediaType);
    writer.writeTo(entry, Entry.class, genericType, annotations, mediaType,
            httpHeaders, entityStream);

实例 3

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
                    root.getClass(), root.getClass(), new Annotation[]{},
                    format, new MultivaluedHashMap<String, Object>(),
        } catch (Throwable e) {
            logger.error(String.format("could not serialize %s to format %s", root, format), e);
            throw propagate(e);
        }"{}", baos);

实例 4

 * @see MessageBodyWriter#writeTo(Object, Class, Type, Annotation[],
 *      MediaType, MultivaluedMap, OutputStream)
public void writeTo(Person t, Class<?> type, Type genericType,
        Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> httpHeaders,
        OutputStream entityStream) throws IOException {
    MessageBodyWriter<Person> mbw;
    mbw = this.providers.getMessageBodyWriter(Person.class, Person.class,
            annotations, MediaType.APPLICATION_XML_TYPE);
    mbw.writeTo(t, Person.class, Person.class, annotations,
            MediaType.APPLICATION_XML_TYPE, httpHeaders, entityStream);
    final MediaType mediaType2 = new MediaType("text", "crazy-person");
    mbw = this.providers.getMessageBodyWriter(Person.class, Person.class,
            annotations, mediaType2);
    mbw.writeTo(t, Person.class, Person.class, annotations, mediaType2,
            httpHeaders, entityStream);

实例 5

   public void writeTo(ConstraintViolationException cve, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> headerMap, OutputStream entityStream) throws IOException, WebApplicationException
if (log.isTraceEnabled()) log.trace("Writing Model with HTTP headers: {} MediaType: {}", headerMap, mediaType);
       MessageBodyWriter<Model> reader = getProviders().getMessageBodyWriter(Model.class, Model.class, annotations, mediaType);
       if (reader == null) throw new WebApplicationException(Response.Status.NOT_ACCEPTABLE);
       reader.writeTo(cve.getModel(), type, genericType, annotations, mediaType, headerMap, entityStream);

实例 6

 * Generates a payload based on request context. On empty content use url as content.
 * @param requestContext
 * @return payload based on content
private Payload obtainObjectPay(ClientRequestContext requestContext){
    Payload objectPay = null;
    Object object = requestContext.getEntity();
    if (object != null)
        // buffer into which myBean will be serialized
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Class<Object> type = (Class<Object>) requestContext.getEntityClass();
        GenericType<Object> genericType = new GenericType<Object>(type) {
        // get most appropriate MBW
        final MessageBodyWriter<Object> messageBodyWriter =
                workers.getMessageBodyWriter(type, type,
                        new Annotation[] {}, MediaType.APPLICATION_JSON_TYPE);
        try {
            // use the MBW to serialize myBean into baos
                    object.getClass(), genericType.getType(), new Annotation[] {},
                    new MultivaluedHashMap<String, Object>(),
        } catch (IOException e) {
            throw new RuntimeException(
                    "Error while serializing MyBean.", e);
        String stringJsonOutput = baos.toString();
        if (logger.isDebugEnabled())
            logger.debug("Entity.toString():: " + stringJsonOutput);
        //There is a short limitation for http headers. It depends on server.
        //As message payload grows, payload in header is growing too, so we must set a limit.
        //It means that we are only signing, validating and checking message integrity of first 1024 characters
        //Same logic is applied in server side
        if (stringJsonOutput != null
                && stringJsonOutput.length() > PAYLOAD_HEADER_MAX_SIZE)
            stringJsonOutput = stringJsonOutput.substring(0, PAYLOAD_HEADER_MAX_SIZE);
        objectPay = new Payload(stringJsonOutput);
    //If request entity is null (usually GET methods) use URI as payload
    else {
        String reqUri = getUri(requestContext);
        objectPay = new Payload(reqUri);
    return objectPay;

实例 7

public void writeBody(GenericContainerResponse response, MessageBodyWriter entityWriter) throws IOException
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   Object entity = response.getEntity();
   if (entity != null)
      entityWriter.writeTo(entity, entity.getClass(), response.getEntityType(), null, response.getContentType(),
         response.getHttpHeaders(), out);
      body = out.toByteArray();

实例 8

 * Set the request entity.
 * @param type        the class of object that is to be written.
 * @param genericType the type of object to be written, obtained either
 *                    by reflection of a resource method return type or by inspection
 *                    of the returned instance. {@link}
 *                    provides a way to specify this information at runtime.
 * @param annotations an array of the annotations on the resource
 *                    method that returns the object.
 * @param mediaType   the media type of the HTTP entity.
 * @param httpHeaders a mutable map of the HTTP response headers.
 * @param entity      the entity instance to write.
 * @throws MappableContainerException encapsulates exceptions thrown while
 *                    serializing the entity.
public <T> void setEntity(final Class<T> type, final Type genericType,
                          final Annotation annotations[], final MediaType mediaType,
                          final MultivaluedMap<String, Object> httpHeaders, final T entity) {
    final MessageBodyWriter<T> writer = getMessageBodyWorkers().getMessageBodyWriter(type, genericType, annotations, mediaType);
    if (writer == null) {
        String message = "A message body writer for Java class " + type.getName() +
                ", and Java type " + genericType +
                ", and MIME media type " + mediaType + " was not found.n";
        Map<MediaType, List<MessageBodyReader>> m = getMessageBodyWorkers().
        message += "The registered message body readers compatible with the MIME media type are:n" +
        throw new WebApplicationException(
                new MessageException(message),
    if (isTracingEnabled()) {
        trace(String.format("matched message body writer: %s, "%s" -> %s",
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {
        writer.writeTo(entity, type, genericType, annotations, mediaType, httpHeaders, byteArrayOutputStream);
    } catch (IOException e) {
        throw new MappableContainerException(e);
    this.entity = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
淘淘あ西西 profile image