All Downloads are FREE. Search and download functionalities are using the official Maven repository.

edu.byu.hbll.box.internal.web.DocumentsResponseWriter Maven / Gradle / Ivy

There is a newer version: 1.3.5
Show newest version
/** */
package edu.byu.hbll.box.internal.web;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import edu.byu.hbll.box.BoxDocument;
import edu.byu.hbll.json.ObjectMapperFactory;

/**
 * Allows for serialization of {@link BoxDocument}s in JAX-RS.
 *
 * @author Charles Draper
 */
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class DocumentsResponseWriter implements MessageBodyWriter {

  WebDocumentWriter fullDocumentWriter = new WebDocumentWriter();

  ObjectMapper mapper = ObjectMapperFactory.newUnchecked();

  @Override
  public long getSize(
      DocumentsResponse t,
      Class type,
      Type genericType,
      Annotation[] annotations,
      MediaType mediaType) {
    return 0;
  }

  @Override
  public boolean isWriteable(
      Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    return DocumentsResponse.class.isAssignableFrom(type);
  }

  @Override
  public void writeTo(
      DocumentsResponse t,
      Class type,
      Type genericType,
      Annotation[] annotations,
      MediaType mediaType,
      MultivaluedMap httpHeaders,
      OutputStream entityStream)
      throws IOException, WebApplicationException {

    List documents = new ArrayList<>(t.getDocuments());

    t.getDocuments().clear();
    ObjectNode webResponse = mapper.valueToTree(t);
    webResponse.remove("documents");
    webResponse.putArray("documents");
    t.getDocuments().addAll(documents);

    for (WebDocument webDocument : documents) {
      webResponse.withArray("documents").add(fullDocumentWriter.convert(webDocument));
    }

    mapper.writeValue(entityStream, webResponse);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy