Search in sources :

Example 86 with ObjectWriter

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter in project atlasdb by palantir.

the class AtlasConsoleServiceTest method toJson.

private <T> Expectations toJson(final T output, final Class<T> clazz) throws JsonProcessingException {
    final ObjectWriter writer = context.mock(ObjectWriter.class);
    return new Expectations() {

        {
            oneOf(mapper).writerWithType(clazz);
            will(returnValue(writer));
            oneOf(writer).writeValueAsString(output);
            will(returnValue(RESULT));
        }
    };
}
Also used : Expectations(org.jmock.Expectations) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter)

Example 87 with ObjectWriter

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter in project gate-core by GateNLP.

the class DocumentJsonUtils method writeDocument.

/**
 * Write a substring of a GATE document to the specified
 * JsonGenerator. The specified window of document text will be
 * written as a property named "text" and the specified annotations
 * will be written as "entities", with their offsets adjusted to be
 * relative to the specified window.
 *
 * @param doc the document to write
 * @param start the start offset of the segment to write
 * @param end the end offset of the segment to write
 * @param extraFeatures additional properties to add to the generated
 *          JSON. If the map includes a "text" key this will be
 *          ignored, and if it contains a key "entities" whose value
 *          is a map then these entities will be merged with the
 *          generated ones derived from the annotationsMap. This would
 *          typically be used for documents that were originally
 *          derived from Twitter data, to re-create the original JSON.
 * @param annotationTypeProperty if non-null, the annotation type will
 *          be written as a property under this name, as if it were an
 *          additional feature of each annotation.
 * @param annotationIDProperty if non-null, the annotation ID will
 *          be written as a property under this name, as if it were an
 *          additional feature of each annotation.
 * @param json the {@link JsonGenerator} to write to.
 * @throws JsonGenerationException if a problem occurs while
 *           generating the JSON
 * @throws IOException if an I/O error occurs.
 */
public static void writeDocument(Document doc, Long start, Long end, Map<String, Collection<Annotation>> annotationsMap, Map<?, ?> extraFeatures, String annotationTypeProperty, String annotationIDProperty, JsonGenerator json) throws JsonGenerationException, IOException, InvalidOffsetException {
    ObjectWriter writer = MAPPER.writer();
    json.writeStartObject();
    RepositioningInfo repos = new RepositioningInfo();
    String text = escape(doc.getContent().getContent(start, end).toString(), repos);
    json.writeStringField("text", text);
    json.writeFieldName("entities");
    json.writeStartObject();
    // if the extraFeatures already includes entities, merge them with
    // the new ones we create
    Object entitiesExtraFeature = (extraFeatures == null) ? null : extraFeatures.get("entities");
    Map<?, ?> entitiesMap = null;
    if (entitiesExtraFeature instanceof Map) {
        entitiesMap = (Map<?, ?>) entitiesExtraFeature;
    }
    for (Map.Entry<String, Collection<Annotation>> annsByType : annotationsMap.entrySet()) {
        String annotationType = annsByType.getKey();
        Collection<Annotation> annotations = annsByType.getValue();
        json.writeFieldName(annotationType);
        json.writeStartArray();
        for (Annotation a : annotations) {
            json.writeStartObject();
            // indices:[start, end], corrected to match the sub-range of
            // text we're writing
            json.writeArrayFieldStart("indices");
            json.writeNumber(repos.getOriginalPos(a.getStartNode().getOffset() - start, true));
            json.writeNumber(repos.getOriginalPos(a.getEndNode().getOffset() - start, false));
            // end of indices
            json.writeEndArray();
            if (annotationTypeProperty != null) {
                json.writeStringField(annotationTypeProperty, a.getType());
            }
            if (annotationIDProperty != null) {
                json.writeNumberField(annotationIDProperty, a.getId());
            }
            // other features
            for (Map.Entry<?, ?> feature : a.getFeatures().entrySet()) {
                if (annotationTypeProperty != null && annotationTypeProperty.equals(feature.getKey())) {
                    // annotationTypeProperty
                    continue;
                }
                json.writeFieldName(String.valueOf(feature.getKey()));
                writer.writeValue(json, feature.getValue());
            }
            // end of annotation
            json.writeEndObject();
        }
        // add any entities from the extraFeatures map
        if (entitiesMap != null && entitiesMap.get(annotationType) instanceof Collection) {
            for (Object ent : (Collection<?>) entitiesMap.get(annotationType)) {
                writer.writeValue(json, ent);
            }
        }
        json.writeEndArray();
    }
    if (entitiesMap != null) {
        for (Map.Entry<?, ?> entitiesEntry : entitiesMap.entrySet()) {
            if (!annotationsMap.containsKey(entitiesEntry.getKey())) {
                // not an entity type we've already seen
                json.writeFieldName(String.valueOf(entitiesEntry.getKey()));
                writer.writeValue(json, entitiesEntry.getValue());
            }
        }
    }
    // end of entities
    json.writeEndObject();
    if (extraFeatures != null) {
        for (Map.Entry<?, ?> feature : extraFeatures.entrySet()) {
            if ("text".equals(feature.getKey()) || "entities".equals(feature.getKey())) {
                // already dealt with text and entities
                continue;
            }
            json.writeFieldName(String.valueOf(feature.getKey()));
            writer.writeValue(json, feature.getValue());
        }
    }
    // end of document
    json.writeEndObject();
    // Make sure that everything we have generated is flushed to the
    // underlying OutputStream. It seems that not doing this can easily
    // lead to corrupt files that just end in the middle of a JSON
    // object. This occurs even if you flush the OutputStream instance
    // as the data never leaves the JsonGenerator
    json.flush();
}
Also used : ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) Collection(java.util.Collection) Map(java.util.Map) Annotation(gate.Annotation)

Example 88 with ObjectWriter

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter in project jackson-jaxrs-propertyfiltering by HubSpot.

the class PropertyFilteringMessageBodyWriter method writeTo.

@Override
public void writeTo(Object o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream os) throws IOException {
    PropertyFiltering annotation = findPropertyFiltering(annotations);
    Collection<String> properties = new ArrayList<>();
    if (annotation != null) {
        properties.addAll(getProperties(annotation.using()));
        properties.addAll(Arrays.asList(annotation.always()));
    }
    PropertyFilter propertyFilter = createPropertyFilter(properties, o, type, genericType, annotations, httpHeaders);
    if (!propertyFilter.hasFilters()) {
        write(o, type, genericType, annotations, mediaType, httpHeaders, os);
        return;
    }
    Timer timer = getTimer();
    Timer.Context context = timer.time();
    try {
        ObjectMapper mapper = getJsonProvider().locateMapper(type, mediaType);
        ObjectWriter writer = JsonEndpointConfig.forWriting(mapper.writer(), annotations, null).getWriter();
        JsonNode tree = valueToTree(mapper, writer, o);
        propertyFilter.filter(tree);
        write(tree, tree.getClass(), tree.getClass(), annotations, mediaType, httpHeaders, os);
    } finally {
        context.stop();
    }
}
Also used : Timer(com.codahale.metrics.Timer) ArrayList(java.util.ArrayList) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) JsonNode(com.fasterxml.jackson.databind.JsonNode) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 89 with ObjectWriter

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter in project OpenTripPlanner by opentripplanner.

the class EmbedConfig method serializedConfiguration.

private String serializedConfiguration(JsonNode config) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
    return config.isMissingNode() ? null : writer.writeValueAsString(config);
}
Also used : ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 90 with ObjectWriter

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter in project uPortal by Jasig.

the class JacksonColumnMapper method toNonNullValue.

@Override
public final String toNonNullValue(Object value) {
    try {
        final Class<? extends Object> type = value.getClass();
        final ObjectWriter typeWriter = typedObjectWriters.getUnchecked(type);
        final String valueAsString = typeWriter.writeValueAsString(value);
        return objectWriter.writeValueAsString(new JsonWrapper(type, valueAsString));
    } catch (JsonGenerationException e) {
        throw new IllegalArgumentException("Could not write to JSON: " + value, e);
    } catch (JsonMappingException e) {
        throw new IllegalArgumentException("Could not write to JSON: " + value, e);
    } catch (IOException e) {
        throw new IllegalArgumentException("Could not write to JSON: " + value, e);
    }
}
Also used : JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) IOException(java.io.IOException) JsonGenerationException(com.fasterxml.jackson.core.JsonGenerationException)

Aggregations

ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)140 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)61 IOException (java.io.IOException)31 Test (org.junit.Test)30 File (java.io.File)17 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)15 ArrayList (java.util.ArrayList)12 ObjectReader (com.fasterxml.jackson.databind.ObjectReader)11 JavaType (com.fasterxml.jackson.databind.JavaType)10 JsonNode (com.fasterxml.jackson.databind.JsonNode)10 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)7 FileOutputStream (java.io.FileOutputStream)7 OutputStream (java.io.OutputStream)7 StringWriter (java.io.StringWriter)7 Map (java.util.Map)7 JCommander (com.beust.jcommander.JCommander)6 ParameterException (com.beust.jcommander.ParameterException)6 SimpleFilterProvider (com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider)6 RateLimiter (com.google.common.util.concurrent.RateLimiter)6 FileInputStream (java.io.FileInputStream)6