View Javadoc

1   /*
2    * Copyright 2015 Data Archiving and Networked Services (an institute of
3    * Koninklijke Nederlandse Akademie van Wetenschappen), King's College London,
4    * Georg-August-Universitaet Goettingen Stiftung Oeffentlichen Rechts
5    *
6    * Licensed under the EUPL, Version 1.1 or – as soon they will be approved by
7    * the European Commission - subsequent versions of the EUPL (the "Licence");
8    * You may not use this work except in compliance with the Licence.
9    * You may obtain a copy of the Licence at:
10   *
11   * https://joinup.ec.europa.eu/software/page/eupl
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the Licence is distributed on an "AS IS" basis,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the Licence for the specific language governing
17   * permissions and limitations under the Licence.
18   */
19  
20  package eu.ehri.extension.providers;
21  
22  import com.fasterxml.jackson.databind.ObjectWriter;
23  import com.google.common.collect.ImmutableMap;
24  import eu.ehri.project.persistence.Bundle;
25  import graphql.ExecutionResult;
26  
27  import javax.ws.rs.Produces;
28  import javax.ws.rs.WebApplicationException;
29  import javax.ws.rs.core.MediaType;
30  import javax.ws.rs.core.MultivaluedMap;
31  import javax.ws.rs.ext.MessageBodyWriter;
32  import javax.ws.rs.ext.Provider;
33  import java.io.IOException;
34  import java.io.OutputStream;
35  import java.lang.annotation.Annotation;
36  import java.lang.reflect.Type;
37  
38  @Provider
39  @Produces(MediaType.APPLICATION_JSON)
40  public class ExecutionResultProvider implements MessageBodyWriter<ExecutionResult>, JsonMessageBodyHandler {
41  
42      private static final ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
43  
44      @Override
45      public boolean isWriteable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
46          return ExecutionResult.class.isAssignableFrom(aClass);
47      }
48  
49      @Override
50      public long getSize(ExecutionResult executionResult, Class<?> aClass, Type type, Annotation[] annotations,
51              MediaType mediaType) {
52          return -1L;
53      }
54  
55      @Override
56      public void writeTo(ExecutionResult executionResult,
57              Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType,
58              MultivaluedMap<String, Object> headers, OutputStream outputStream)
59              throws IOException, WebApplicationException {
60          if (executionResult.getData() != null) {
61              writer.writeValue(outputStream, ImmutableMap.of(
62                      Bundle.DATA_KEY, executionResult.getData()));
63          }
64      }
65  }