Search in sources :

Example 76 with ObjectWriter

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter in project logging-log4j2 by apache.

the class JacksonFactory method newWriter.

ObjectWriter newWriter(final boolean locationInfo, final boolean properties, final boolean compact) {
    final SimpleFilterProvider filters = new SimpleFilterProvider();
    final Set<String> except = new HashSet<>(2);
    if (!locationInfo) {
        except.add(this.getPropertNameForSource());
    }
    if (!properties) {
        except.add(this.getPropertNameForContextMap());
    }
    except.add(this.getPropertNameForNanoTime());
    filters.addFilter(Log4jLogEvent.class.getName(), SimpleBeanPropertyFilter.serializeAllExcept(except));
    final ObjectWriter writer = this.newObjectMapper().writer(compact ? this.newCompactPrinter() : this.newPrettyPrinter());
    return writer.with(filters);
}
Also used : SimpleFilterProvider(com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider) Log4jLogEvent(org.apache.logging.log4j.core.impl.Log4jLogEvent) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) HashSet(java.util.HashSet)

Example 77 with ObjectWriter

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

the class JsonMapper method writeTo.

@Override
public void writeTo(Object value, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream outputStream) throws IOException {
    // Prevent broken browser from attempting to render the json as html
    httpHeaders.add(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff");
    JsonFactory jsonFactory = objectMapper.getFactory();
    jsonFactory.setCharacterEscapes(HTMLCharacterEscapes.INSTANCE);
    JsonGenerator jsonGenerator = jsonFactory.createGenerator(outputStream, JsonEncoding.UTF8);
    // Important: we are NOT to close the underlying stream after
    // mapping, so we need to instruct generator:
    jsonGenerator.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
    // Pretty print?
    if (isPrettyPrintRequested()) {
        jsonGenerator.useDefaultPrettyPrinter();
    }
    // 04-Mar-2010, tatu: How about type we were given? (if any)
    JavaType rootType = null;
    if (genericType != null && value != null) {
        // generic.
        if (genericType.getClass() != Class.class) {
            // generic types are other implementations of 'java.lang.reflect.Type'
            // This is still not exactly right; should root type be further
            // specialized with 'value.getClass()'? Let's see how well this works before
            // trying to come up with more complete solution.
            rootType = objectMapper.getTypeFactory().constructType(genericType);
            // 
            if (rootType.getRawClass() == Object.class) {
                rootType = null;
            }
        }
    }
    String jsonpFunctionName = getJsonpFunctionName();
    if (jsonpFunctionName != null) {
        value = new JSONPObject(jsonpFunctionName, value, rootType);
        rootType = null;
    }
    ObjectWriter writer;
    if (rootType != null) {
        writer = objectMapper.writerFor(rootType);
    } else {
        writer = objectMapper.writer();
    }
    try {
        writer.writeValue(jsonGenerator, value);
        // add a newline so when you use curl it looks nice
        outputStream.write('\n');
    } catch (EOFException e) {
    // ignore EOFException
    // This happens when the client terminates the connection when data
    // is being written.  If the exception is allowed to propagate to
    // Jersey, the exception will be logged, but this error is not
    // important.  This is safe since the output stream is already
    // closed.
    }
}
Also used : JavaType(com.fasterxml.jackson.databind.JavaType) JsonFactory(com.fasterxml.jackson.core.JsonFactory) EOFException(java.io.EOFException) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) JSONPObject(com.fasterxml.jackson.databind.util.JSONPObject) SerializableString(com.fasterxml.jackson.core.SerializableString)

Example 78 with ObjectWriter

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter in project syndesis-qe by syndesisio.

the class AbstractEndpoint method list.

public List<T> list(String id) {
    final ObjectMapper mapper = new ObjectMapper().registerModules(new Jdk8Module());
    mapper.configure(Feature.AUTO_CLOSE_SOURCE, true);
    final ObjectWriter ow = mapper.writer();
    final Class<ListResult<T>> listtype = (Class) ListResult.class;
    log.debug("GET : {}", getEndpointUrl(Optional.ofNullable(id)));
    final Invocation.Builder invocation = this.createInvocation(id);
    final JsonNode response = invocation.get(JsonNode.class);
    ListResult<T> result = null;
    try {
        result = Json.reader().forType(listtype).readValue(response.toString());
    } catch (IOException ex) {
        log.error("" + ex);
    }
    final List<T> ts = new ArrayList<>();
    for (int i = 0; i < result.getTotalCount(); i++) {
        T con = null;
        try {
            final String json = ow.writeValueAsString(result.getItems().get(i));
            con = Json.reader().forType(type).readValue(json);
        } catch (IOException ex) {
            log.error(ex.toString());
        }
        ts.add(con);
    }
    return ts;
}
Also used : Invocation(javax.ws.rs.client.Invocation) ArrayList(java.util.ArrayList) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) ListResult(io.syndesis.common.model.ListResult) Jdk8Module(com.fasterxml.jackson.datatype.jdk8.Jdk8Module) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 79 with ObjectWriter

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

the class SystemController method getMetrics.

@GET
@Path("/metrics")
private String getMetrics(Request request, Response response) throws IOException {
    response.header(CACHE_CONTROL, "must-revalidate,no-cache,no-store");
    response.status(HttpServletResponse.SC_OK);
    Optional<String> format = Optional.ofNullable(request.queryParams(FORMAT));
    String dFormat = format.orElse(JSON);
    switch(dFormat) {
        case PROMETHEUS:
            // Prometheus format for the metrics
            response.type(PROMETHEUS_CONTENT_TYPE);
            final Writer writer1 = new StringWriter();
            TextFormat.write004(writer1, this.prometheusRegistry.metricFamilySamples());
            return writer1.toString();
        case JSON:
            // Json/Dropwizard format
            response.type(APPLICATION_JSON);
            final ObjectWriter writer = mapper.writer();
            try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
                writer.writeValue(output, this.metricRegistry);
                return new String(output.toByteArray(), "UTF-8");
            }
        default:
            throw GraknServerException.requestInvalidParameter(FORMAT, dFormat);
    }
}
Also used : StringWriter(java.io.StringWriter) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) StringWriter(java.io.StringWriter) Writer(java.io.Writer) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 80 with ObjectWriter

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

the class GHBaseServlet method writeJson.

protected void writeJson(HttpServletRequest req, HttpServletResponse res, JsonNode json) throws IOException {
    String type = getParam(req, "type", "json");
    res.setCharacterEncoding("UTF-8");
    final boolean indent = getBooleanParam(req, "debug", false) || getBooleanParam(req, "pretty", false);
    ObjectWriter objectWriter = indent ? objectMapper.writer().with(SerializationFeature.INDENT_OUTPUT) : objectMapper.writer();
    if ("jsonp".equals(type)) {
        res.setContentType("application/javascript");
        if (!jsonpAllowed) {
            writeError(res, SC_BAD_REQUEST, "Server is not configured to allow jsonp!");
            return;
        }
        String callbackName = getParam(req, "callback", null);
        if (callbackName == null) {
            writeError(res, SC_BAD_REQUEST, "No callback provided, necessary if type=jsonp");
            return;
        }
        writeResponse(res, callbackName + "(" + objectWriter.writeValueAsString(json) + ")");
    } else {
        res.setContentType("application/json");
        writeResponse(res, objectWriter.writeValueAsString(json));
    }
}
Also used : ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter)

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