Search in sources :

Example 51 with ObjectWriter

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

the class ObjectMapperJDK7IT method testWriteValue.

@Test
public void testWriteValue() throws Exception {
    __POJO pojo = new __POJO();
    pojo.setName("Jackson");
    String jsonStr = mapper.writeValueAsString(pojo);
    byte[] jsonByte = mapper.writeValueAsBytes(pojo);
    ObjectWriter writer = mapper.writer();
    writer.writeValueAsString(pojo);
    writer.writeValueAsBytes(pojo);
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    Method mapperWriteValueAsString = ObjectMapper.class.getMethod("writeValueAsString", Object.class);
    Method mapperWriteValueAsBytes = ObjectMapper.class.getMethod("writeValueAsBytes", Object.class);
    Method writerWriteValueAsString = ObjectWriter.class.getMethod("writeValueAsString", Object.class);
    Method writerWriteValueAsBytes = ObjectWriter.class.getMethod("writeValueAsBytes", Object.class);
    verifier.verifyTrace(event(SERVICE_TYPE, mapperWriteValueAsString, annotation(ANNOTATION_KEY, jsonStr.length())));
    verifier.verifyTrace(event(SERVICE_TYPE, mapperWriteValueAsBytes, annotation(ANNOTATION_KEY, jsonByte.length)));
    verifier.verifyTrace(event(SERVICE_TYPE, writerWriteValueAsString, annotation(ANNOTATION_KEY, jsonStr.length())));
    verifier.verifyTrace(event(SERVICE_TYPE, writerWriteValueAsBytes, annotation(ANNOTATION_KEY, jsonByte.length)));
    verifier.verifyTraceCount(0);
}
Also used : ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) Method(java.lang.reflect.Method) PluginTestVerifier(com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier) Test(org.junit.Test)

Example 52 with ObjectWriter

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

the class ObjectMapperIT method testWriteValue.

@Test
public void testWriteValue() throws Exception {
    __POJO pojo = new __POJO();
    pojo.setName("Jackson");
    String jsonStr = mapper.writeValueAsString(pojo);
    byte[] jsonByte = mapper.writeValueAsBytes(pojo);
    ObjectWriter writer = mapper.writer();
    writer.writeValueAsString(pojo);
    writer.writeValueAsBytes(pojo);
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    Method mapperWriteValueAsString = ObjectMapper.class.getMethod("writeValueAsString", Object.class);
    Method mapperWriteValueAsBytes = ObjectMapper.class.getMethod("writeValueAsBytes", Object.class);
    Method writerWriteValueAsString = ObjectWriter.class.getMethod("writeValueAsString", Object.class);
    Method writerWriteValueAsBytes = ObjectWriter.class.getMethod("writeValueAsBytes", Object.class);
    verifier.verifyTrace(event(SERVICE_TYPE, mapperWriteValueAsString, annotation(ANNOTATION_KEY, jsonStr.length())));
    verifier.verifyTrace(event(SERVICE_TYPE, mapperWriteValueAsBytes, annotation(ANNOTATION_KEY, jsonByte.length)));
    verifier.verifyTrace(event(SERVICE_TYPE, writerWriteValueAsString, annotation(ANNOTATION_KEY, jsonStr.length())));
    verifier.verifyTrace(event(SERVICE_TYPE, writerWriteValueAsBytes, annotation(ANNOTATION_KEY, jsonByte.length)));
    verifier.verifyTraceCount(0);
}
Also used : ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) Method(java.lang.reflect.Method) PluginTestVerifier(com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier) Test(org.junit.Test)

Example 53 with ObjectWriter

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

the class ObjectReaderIT method testWriteValue.

@Test
public void testWriteValue() throws Exception {
    __POJO pojo = new __POJO();
    pojo.setName("Jackson");
    ObjectWriter writer = mapper.writer();
    String jsonStr = writer.writeValueAsString(pojo);
    byte[] jsonByte = writer.writeValueAsBytes(pojo);
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    Method writeval1 = ObjectWriter.class.getMethod("writeValueAsString", Object.class);
    Method writeval2 = ObjectWriter.class.getMethod("writeValueAsBytes", Object.class);
    verifier.verifyTrace(event("JACKSON", writeval1, annotation("jackson.json.length", jsonStr.length())));
    verifier.verifyTrace(event("JACKSON", writeval2, annotation("jackson.json.length", jsonByte.length)));
    verifier.verifyTraceCount(0);
}
Also used : ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) Method(java.lang.reflect.Method) PluginTestVerifier(com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier) Test(org.junit.Test)

Example 54 with ObjectWriter

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

the class ObjectReaderJDK7IT method testWriteValue.

@Test
public void testWriteValue() throws Exception {
    __POJO pojo = new __POJO();
    pojo.setName("Jackson");
    ObjectWriter writer = mapper.writer();
    String jsonStr = writer.writeValueAsString(pojo);
    byte[] jsonByte = writer.writeValueAsBytes(pojo);
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    Method writeval1 = ObjectWriter.class.getMethod("writeValueAsString", Object.class);
    Method writeval2 = ObjectWriter.class.getMethod("writeValueAsBytes", Object.class);
    verifier.verifyTrace(event("JACKSON", writeval1, annotation("jackson.json.length", jsonStr.length())));
    verifier.verifyTrace(event("JACKSON", writeval2, annotation("jackson.json.length", jsonByte.length)));
    verifier.verifyTraceCount(0);
}
Also used : ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) Method(java.lang.reflect.Method) PluginTestVerifier(com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier) Test(org.junit.Test)

Example 55 with ObjectWriter

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

the class QueryResource method doPost.

@POST
@Produces({ MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE })
@Consumes({ MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE, APPLICATION_SMILE })
public Response doPost(final InputStream in, @QueryParam("pretty") final String pretty, // used to get request content-type,Accept header, remote address and auth-related headers
@Context final HttpServletRequest req) throws IOException {
    final QueryLifecycle queryLifecycle = queryLifecycleFactory.factorize();
    Query<?> query = null;
    final ResourceIOReaderWriter ioReaderWriter = createResourceIOReaderWriter(req, pretty != null);
    final String currThreadName = Thread.currentThread().getName();
    try {
        queryLifecycle.initialize(readQuery(req, in, ioReaderWriter));
        query = queryLifecycle.getQuery();
        final String queryId = query.getId();
        final String queryThreadName = StringUtils.format("%s[%s_%s_%s]", currThreadName, query.getType(), query.getDataSource().getTableNames(), queryId);
        Thread.currentThread().setName(queryThreadName);
        if (log.isDebugEnabled()) {
            log.debug("Got query [%s]", query);
        }
        final Access authResult = queryLifecycle.authorize(req);
        if (!authResult.isAllowed()) {
            throw new ForbiddenException(authResult.toString());
        }
        final QueryLifecycle.QueryResponse queryResponse = queryLifecycle.execute();
        final Sequence<?> results = queryResponse.getResults();
        final ResponseContext responseContext = queryResponse.getResponseContext();
        final String prevEtag = getPreviousEtag(req);
        if (prevEtag != null && prevEtag.equals(responseContext.getEntityTag())) {
            queryLifecycle.emitLogsAndMetrics(null, req.getRemoteAddr(), -1);
            successfulQueryCount.incrementAndGet();
            return Response.notModified().build();
        }
        final Yielder<?> yielder = Yielders.each(results);
        try {
            boolean shouldFinalize = QueryContexts.isFinalize(query, true);
            boolean serializeDateTimeAsLong = QueryContexts.isSerializeDateTimeAsLong(query, false) || (!shouldFinalize && QueryContexts.isSerializeDateTimeAsLongInner(query, false));
            final ObjectWriter jsonWriter = ioReaderWriter.getResponseWriter().newOutputWriter(queryLifecycle.getToolChest(), queryLifecycle.getQuery(), serializeDateTimeAsLong);
            Response.ResponseBuilder responseBuilder = Response.ok(new StreamingOutput() {

                @Override
                public void write(OutputStream outputStream) throws WebApplicationException {
                    Exception e = null;
                    CountingOutputStream os = new CountingOutputStream(outputStream);
                    try {
                        // json serializer will always close the yielder
                        jsonWriter.writeValue(os, yielder);
                        // Some types of OutputStream suppress flush errors in the .close() method.
                        os.flush();
                        os.close();
                    } catch (Exception ex) {
                        e = ex;
                        log.noStackTrace().error(ex, "Unable to send query response.");
                        throw new RuntimeException(ex);
                    } finally {
                        Thread.currentThread().setName(currThreadName);
                        queryLifecycle.emitLogsAndMetrics(e, req.getRemoteAddr(), os.getCount());
                        if (e == null) {
                            successfulQueryCount.incrementAndGet();
                        } else {
                            failedQueryCount.incrementAndGet();
                        }
                    }
                }
            }, ioReaderWriter.getResponseWriter().getResponseType()).header("X-Druid-Query-Id", queryId);
            transferEntityTag(responseContext, responseBuilder);
            DirectDruidClient.removeMagicResponseContextFields(responseContext);
            // Limit the response-context header, see https://github.com/apache/druid/issues/2331
            // Note that Response.ResponseBuilder.header(String key,Object value).build() calls value.toString()
            // and encodes the string using ASCII, so 1 char is = 1 byte
            final ResponseContext.SerializationResult serializationResult = responseContext.serializeWith(jsonMapper, responseContextConfig.getMaxResponseContextHeaderSize());
            if (serializationResult.isTruncated()) {
                final String logToPrint = StringUtils.format("Response Context truncated for id [%s]. Full context is [%s].", queryId, serializationResult.getFullResult());
                if (responseContextConfig.shouldFailOnTruncatedResponseContext()) {
                    log.error(logToPrint);
                    throw new QueryInterruptedException(new TruncatedResponseContextException("Serialized response context exceeds the max size[%s]", responseContextConfig.getMaxResponseContextHeaderSize()), selfNode.getHostAndPortToUse());
                } else {
                    log.warn(logToPrint);
                }
            }
            return responseBuilder.header(HEADER_RESPONSE_CONTEXT, serializationResult.getResult()).build();
        } catch (QueryException e) {
            // make sure to close yielder if anything happened before starting to serialize the response.
            yielder.close();
            throw e;
        } catch (Exception e) {
            // make sure to close yielder if anything happened before starting to serialize the response.
            yielder.close();
            throw new RuntimeException(e);
        } finally {
        // do not close yielder here, since we do not want to close the yielder prior to
        // StreamingOutput having iterated over all the results
        }
    } catch (QueryInterruptedException e) {
        interruptedQueryCount.incrementAndGet();
        queryLifecycle.emitLogsAndMetrics(e, req.getRemoteAddr(), -1);
        return ioReaderWriter.getResponseWriter().gotError(e);
    } catch (QueryTimeoutException timeout) {
        timedOutQueryCount.incrementAndGet();
        queryLifecycle.emitLogsAndMetrics(timeout, req.getRemoteAddr(), -1);
        return ioReaderWriter.getResponseWriter().gotTimeout(timeout);
    } catch (QueryCapacityExceededException cap) {
        failedQueryCount.incrementAndGet();
        queryLifecycle.emitLogsAndMetrics(cap, req.getRemoteAddr(), -1);
        return ioReaderWriter.getResponseWriter().gotLimited(cap);
    } catch (QueryUnsupportedException unsupported) {
        failedQueryCount.incrementAndGet();
        queryLifecycle.emitLogsAndMetrics(unsupported, req.getRemoteAddr(), -1);
        return ioReaderWriter.getResponseWriter().gotUnsupported(unsupported);
    } catch (BadJsonQueryException | ResourceLimitExceededException e) {
        interruptedQueryCount.incrementAndGet();
        queryLifecycle.emitLogsAndMetrics(e, req.getRemoteAddr(), -1);
        return ioReaderWriter.getResponseWriter().gotBadQuery(e);
    } catch (ForbiddenException e) {
        // send an error response if this is thrown.
        throw e;
    } catch (Exception e) {
        failedQueryCount.incrementAndGet();
        queryLifecycle.emitLogsAndMetrics(e, req.getRemoteAddr(), -1);
        log.noStackTrace().makeAlert(e, "Exception handling request").addData("query", query != null ? jsonMapper.writeValueAsString(query) : "unparseable query").addData("peer", req.getRemoteAddr()).emit();
        return ioReaderWriter.getResponseWriter().gotError(e);
    } finally {
        Thread.currentThread().setName(currThreadName);
    }
}
Also used : CountingOutputStream(com.google.common.io.CountingOutputStream) OutputStream(java.io.OutputStream) Access(org.apache.druid.server.security.Access) StreamingOutput(javax.ws.rs.core.StreamingOutput) QueryTimeoutException(org.apache.druid.query.QueryTimeoutException) CountingOutputStream(com.google.common.io.CountingOutputStream) ResponseContext(org.apache.druid.query.context.ResponseContext) QueryInterruptedException(org.apache.druid.query.QueryInterruptedException) ForbiddenException(org.apache.druid.server.security.ForbiddenException) QueryCapacityExceededException(org.apache.druid.query.QueryCapacityExceededException) TruncatedResponseContextException(org.apache.druid.query.TruncatedResponseContextException) QueryUnsupportedException(org.apache.druid.query.QueryUnsupportedException) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) BadJsonQueryException(org.apache.druid.query.BadJsonQueryException) ForbiddenException(org.apache.druid.server.security.ForbiddenException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) QueryTimeoutException(org.apache.druid.query.QueryTimeoutException) WebApplicationException(javax.ws.rs.WebApplicationException) QueryException(org.apache.druid.query.QueryException) BadQueryException(org.apache.druid.query.BadQueryException) QueryCapacityExceededException(org.apache.druid.query.QueryCapacityExceededException) QueryInterruptedException(org.apache.druid.query.QueryInterruptedException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) TruncatedResponseContextException(org.apache.druid.query.TruncatedResponseContextException) ResourceLimitExceededException(org.apache.druid.query.ResourceLimitExceededException) QueryUnsupportedException(org.apache.druid.query.QueryUnsupportedException) Response(javax.ws.rs.core.Response) BadJsonQueryException(org.apache.druid.query.BadJsonQueryException) BadJsonQueryException(org.apache.druid.query.BadJsonQueryException) QueryException(org.apache.druid.query.QueryException) BadQueryException(org.apache.druid.query.BadQueryException) ResourceLimitExceededException(org.apache.druid.query.ResourceLimitExceededException) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes)

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