Exemple #1
0
 public MessageBodyWriter findWriter(
     Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
   for (MessageBodyWriter writer : messageBodyWriters) {
     if (writer.isWriteable(type, genericType, annotations, mediaType)) {
       return writer;
     }
   }
   return null;
 }
Exemple #2
0
  private static void checkJaxbType(
      Class<?> serviceClass,
      Class<?> type,
      Type genericType,
      ResourceTypes types,
      Annotation[] anns,
      MessageBodyWriter<?> jaxbWriter) {
    boolean isCollection = false;
    if (InjectionUtils.isSupportedCollectionOrArray(type)) {
      type = InjectionUtils.getActualType(genericType);
      isCollection = true;
    }
    if (type == Object.class && !(genericType instanceof Class)) {
      Type theType =
          InjectionUtils.processGenericTypeIfNeeded(serviceClass, Object.class, genericType);
      type = InjectionUtils.getActualType(theType);
    }
    if (type == null
        || InjectionUtils.isPrimitive(type)
        || JAXBElement.class.isAssignableFrom(type)
        || Response.class.isAssignableFrom(type)
        || type.isInterface()) {
      return;
    }

    MessageBodyWriter<?> writer = jaxbWriter;
    if (writer == null) {
      JAXBElementProvider<Object> defaultWriter = new JAXBElementProvider<Object>();
      defaultWriter.setMarshallAsJaxbElement(true);
      defaultWriter.setXmlTypeAsJaxbElementOnly(true);
      writer = defaultWriter;
    }
    if (writer.isWriteable(type, type, anns, MediaType.APPLICATION_XML_TYPE)) {
      types.getAllTypes().put(type, type);
      Class<?> genCls = InjectionUtils.getActualType(genericType);
      if (genCls != type
          && genCls != null
          && genCls != Object.class
          && !InjectionUtils.isSupportedCollectionOrArray(genCls)) {
        types.getAllTypes().put(genCls, genCls);
      }

      XMLName name = AnnotationUtils.getAnnotation(anns, XMLName.class);
      QName qname = name != null ? JAXRSUtils.convertStringToQName(name.value()) : null;
      if (isCollection) {
        types.getCollectionMap().put(type, qname);
      } else {
        types.getXmlNameMap().put(type, qname);
      }
    }
  }
Exemple #3
0
  public <T> byte[] toBytes(MediaType mediaType, T o) throws IOException {
    if (o == null) {
      return null;
    }

    Class<T> clazz = (Class<T>) o.getClass();
    MessageBodyWriter<T> writer = findWriter(clazz, null, EMPTY_ANNOTATIONS, mediaType);
    if (writer == null) {
      throw new IllegalArgumentException(
          "cannot convert " + clazz.getName() + " into byte[] (" + mediaType + ")");
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
    writer.writeTo(o, clazz, clazz, EMPTY_ANNOTATIONS, mediaType, EMPTY_OBJECT_HEADERS, baos);
    return baos.toByteArray();
  }
 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;
 }
Exemple #5
0
 @SuppressWarnings("unchecked")
 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();
   }
 }
  /**
   * Write the response.
   *
   * <p>The status and headers will be written by calling the method {@link
   * ContainerResponseWriter#writeStatusAndHeaders} on the provided {@link ContainerResponseWriter}
   * instance. The {@link OutputStream} returned from that method call is used to write the entity
   * (if any) to that {@link OutputStream}. An appropriate {@link MessageBodyWriter} will be found
   * to write the entity.
   *
   * @throws WebApplicationException if {@link MessageBodyWriter} cannot be found for the entity
   *     with a 500 (Internal Server error) response.
   * @throws java.io.IOException if there is an error writing the entity
   */
  public void write() throws IOException {
    if (isCommitted) return;

    if (request.isTracingEnabled()) {
      configureTrace(responseWriter);
    }

    if (entity == null) {
      isCommitted = true;
      responseWriter.writeStatusAndHeaders(-1, this);
      responseWriter.finish();
      return;
    }

    if (!getHttpHeaders().containsKey(HttpHeaders.VARY)) {
      final String varyHeader = (String) request.getProperties().get(ContainerRequest.VARY_HEADER);
      if (varyHeader != null) {
        getHttpHeaders().add(HttpHeaders.VARY, varyHeader);
      }
    }

    MediaType contentType = getMediaType();
    if (contentType == null) {
      contentType =
          getMessageBodyWorkers()
              .getMessageBodyWriterMediaType(
                  entity.getClass(), entityType, annotations, request.getAcceptableMediaTypes());
      if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype())
        contentType = MediaType.APPLICATION_OCTET_STREAM_TYPE;

      getHttpHeaders().putSingle(HttpHeaders.CONTENT_TYPE, contentType);
    }

    final MessageBodyWriter p =
        getMessageBodyWorkers()
            .getMessageBodyWriter(entity.getClass(), entityType, annotations, contentType);
    if (p == null) {
      String message =
          "A message body writer for Java class "
              + entity.getClass().getName()
              + ", and Java type "
              + entityType
              + ", and MIME media type "
              + contentType
              + " was not found";
      LOGGER.severe(message);
      Map<MediaType, List<MessageBodyWriter>> m = getMessageBodyWorkers().getWriters(contentType);
      LOGGER.severe(
          "The registered message body writers compatible with the MIME media type are:\n"
              + getMessageBodyWorkers().writersToString(m));

      if (request.getMethod().equals("HEAD")) {
        isCommitted = true;
        responseWriter.writeStatusAndHeaders(-1, this);
        responseWriter.finish();
        return;
      } else {
        throw new WebApplicationException(new MessageException(message), 500);
      }
    }

    final long size = p.getSize(entity, entity.getClass(), entityType, annotations, contentType);
    if (request.getMethod().equals("HEAD")) {
      if (size != -1) getHttpHeaders().putSingle(HttpHeaders.CONTENT_LENGTH, Long.toString(size));
      isCommitted = true;
      responseWriter.writeStatusAndHeaders(0, this);
    } else {
      if (request.isTracingEnabled()) {
        request.trace(
            String.format(
                "matched message body writer: %s, \"%s\" -> %s",
                ReflectionHelper.objectToString(entity),
                contentType,
                ReflectionHelper.objectToString(p)));
      }

      if (out == null) out = new CommittingOutputStream(size);
      p.writeTo(
          entity, entity.getClass(), entityType, annotations, contentType, getHttpHeaders(), out);
      if (!isCommitted) {
        isCommitted = true;
        responseWriter.writeStatusAndHeaders(-1, this);
      }
    }
    responseWriter.finish();
  }