Java 类com.fasterxml.jackson.core.JsonEncoding 实例源码

项目:linux-memory-monitor    文件:CallbackMappingJackson2HttpMessageConverter.java   
@Override   //Object就是springmvc返回值
protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException,
        HttpMessageNotWritableException {
    // 从threadLocal中获取当前的Request对象
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes()).getRequest();

    String callbackParam = request.getParameter(callbackName);
    if (StringUtils.isEmpty(callbackParam)) {
        // 没有找到callback参数,直接返回json数据
        super.writeInternal(object, outputMessage);
    } else {
        JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
        try {
            //将对象转换为json串,然后用回调方法包括起来
            String result = callbackParam + "(" + super.getObjectMapper().writeValueAsString(object)
                    + ");";
            IOUtils.write(result, outputMessage.getBody(), encoding.getJavaName());
        } catch (JsonProcessingException ex) {
            throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
        }
    }

}
项目:GitHub    文件:GeneratorFailFromReaderTest.java   
private void _testFailOnWritingStringNotFieldName(JsonFactory f, boolean useReader) throws Exception
{
    JsonGenerator gen;
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    if (useReader) {
        gen = f.createGenerator(ObjectWriteContext.empty(), new OutputStreamWriter(bout, "UTF-8"));
    } else {
        gen = f.createGenerator(ObjectWriteContext.empty(), bout, JsonEncoding.UTF8);
    }
    gen.writeStartObject();

    try {
        StringReader reader = new StringReader("a");
        gen.writeString(reader, -1);
        gen.flush();
        String json = bout.toString("UTF-8");
        fail("Should not have let "+gen.getClass().getName()+".writeString() be used in place of 'writeFieldName()': output = "+json);
    } catch (JsonProcessingException e) {
        verifyException(e, "can not write a String");
    }
    gen.close();
}
项目:GitHub    文件:GeneratorFailFromReaderTest.java   
private void _testFailOnWritingStringFromReaderWithTooFewCharacters(JsonFactory f, boolean useReader) throws Exception{
    JsonGenerator gen;
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    if (useReader) {
        gen = f.createGenerator(ObjectWriteContext.empty(), new OutputStreamWriter(bout, "UTF-8"));
    } else {
        gen = f.createGenerator(ObjectWriteContext.empty(), bout, JsonEncoding.UTF8);
    }
    gen.writeStartObject();

    try {
        String testStr = "aaaaaaaaa";
        StringReader reader = new StringReader(testStr);
        gen.writeFieldName("a");
        gen.writeString(reader, testStr.length() + 1);
        gen.flush();
        String json = bout.toString("UTF-8");
        fail("Should not have let "+gen.getClass().getName()+".writeString() ': output = "+json);
    } catch (JsonProcessingException e) {
        verifyException(e, "Didn't read enough from reader");
    }
    gen.close();
}
项目:GitHub    文件:GeneratorFailFromReaderTest.java   
private void _testFailOnWritingStringFromNullReader(JsonFactory f, boolean useReader) throws Exception{
    JsonGenerator gen;
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    if (useReader) {
        gen = f.createGenerator(ObjectWriteContext.empty(), new OutputStreamWriter(bout, "UTF-8"));
    } else {
        gen = f.createGenerator(ObjectWriteContext.empty(), bout, JsonEncoding.UTF8);
    }
    gen.writeStartObject();

    try {
        gen.writeFieldName("a");
        gen.writeString(null, -1);
        gen.flush();
        String json = bout.toString("UTF-8");
        fail("Should not have let "+gen.getClass().getName()+".writeString() ': output = "+json);
    } catch (JsonProcessingException e) {
        verifyException(e, "null reader");
    }
    gen.close();
}
项目:GitHub    文件:GeneratorFailTest.java   
private void _testDupFieldNameWrites(JsonFactory f, boolean useReader) throws Exception
{
    JsonGenerator gen;
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    if (useReader) {
        gen = f.createGenerator(ObjectWriteContext.empty(), new OutputStreamWriter(bout, "UTF-8"));
    } else {
        gen = f.createGenerator(ObjectWriteContext.empty(), bout, JsonEncoding.UTF8);
    }
    gen.writeStartObject();
    gen.writeFieldName("a");

    try {
        gen.writeFieldName("b");
        gen.flush();
        String json = bout.toString("UTF-8");
        fail("Should not have let two consecutive field name writes succeed: output = "+json);
    } catch (JsonProcessingException e) {
        verifyException(e, "can not write a field name, expecting a value");
    }
    gen.close();
}
项目:GitHub    文件:GeneratorFailTest.java   
private void _testFailOnWritingStringNotFieldName(JsonFactory f, boolean useReader) throws Exception
{
    JsonGenerator gen;
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    if (useReader) {
        gen = f.createGenerator(ObjectWriteContext.empty(), new OutputStreamWriter(bout, "UTF-8"));
    } else {
        gen = f.createGenerator(ObjectWriteContext.empty(), bout, JsonEncoding.UTF8);
    }
    gen.writeStartObject();

    try {
        gen.writeString("a");
        gen.flush();
        String json = bout.toString("UTF-8");
        fail("Should not have let "+gen.getClass().getName()+".writeString() be used in place of 'writeFieldName()': output = "+json);
    } catch (JsonProcessingException e) {
        verifyException(e, "can not write a String");
    }
    gen.close();
}
项目:GitHub    文件:GeneratorFailTest.java   
private void _testFailOnWritingFieldNameInRoot(JsonFactory f, boolean useReader) throws Exception
{
    JsonGenerator gen;
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    if (useReader) {
        gen = f.createGenerator(ObjectWriteContext.empty(), new OutputStreamWriter(bout, "UTF-8"));
    } else {
        gen = f.createGenerator(ObjectWriteContext.empty(), bout, JsonEncoding.UTF8);
    }
    try {
        gen.writeFieldName("a");
        gen.flush();
        String json = bout.toString("UTF-8");
        fail("Should not have let "+gen.getClass().getName()+".writeFieldName() be used in root context: output = "+json);
    } catch (JsonProcessingException e) {
        verifyException(e, "can not write a field name");
    }
    gen.close();
}
项目:graphium    文件:GenericJacksonWayGraphOutputFormat.java   
public GenericJacksonWayGraphOutputFormat(ISegmentOutputFormat<T> segmentOutputFormat, 
        IAdapter<IGraphVersionMetadataDTO, IWayGraphVersionMetadata> adapter,
        OutputStream stream, 
        JsonGenerator generator)
{
    this.segmentOutputFormat = segmentOutputFormat;
    this.adapter = adapter;
    if (generator == null) {
        try {
            this.generator = new MappingJsonFactory().createGenerator(stream, JsonEncoding.UTF8);
            this.generator.useDefaultPrettyPrinter();
        } catch (IOException e) {
            log.error("error creating jackson json factory", e);
        }
    } else {
        this.generator = generator;
    }
}
项目:graphium    文件:GenericJacksonSegmentOutputFormat.java   
public GenericJacksonSegmentOutputFormat(ISegmentAdapterRegistry<? extends IBaseSegmentDTO, T> adapterRegistry,
        OutputStream stream, JsonGenerator generator, int flushBatchCount)
{
    this.adapterRegistry = adapterRegistry;
    if (generator == null) {
        try {
            this.generator = new MappingJsonFactory().createGenerator(new BufferedOutputStream(stream), JsonEncoding.UTF8);
            this.generator.useDefaultPrettyPrinter();
        } catch (IOException e) {
            log.error("error creating jackson json factory", e);
        }
    }
    if (flushBatchCount > 0 ) {
        this.flushBatchCount = flushBatchCount;
    } else {
        log.warn("flushBatchCount ignored, can not be negative or 0");
    }
}
项目:uckefu    文件:UKResultMapper.java   
private String buildJSONFromFields(Collection<SearchHitField> values) {
    JsonFactory nodeFactory = new JsonFactory();
    try {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        JsonGenerator generator = nodeFactory.createGenerator(stream, JsonEncoding.UTF8);
        generator.writeStartObject();
        for (SearchHitField value : values) {
            if (value.getValues().size() > 1) {
                generator.writeArrayFieldStart(value.getName());
                for (Object val : value.getValues()) {
                    generator.writeObject(val);
                }
                generator.writeEndArray();
            } else {
                generator.writeObjectField(value.getName(), value.getValue());
            }
        }
        generator.writeEndObject();
        generator.flush();
        return new String(stream.toByteArray(), Charset.forName("UTF-8"));
    } catch (IOException e) {
        return null;
    }
}
项目:monarch    文件:PdxToJSON.java   
public String getJSON() {
  JsonFactory jf = new JsonFactory();
  // OutputStream os = new ByteArrayOutputStream();
  HeapDataOutputStream hdos = new HeapDataOutputStream(org.apache.geode.internal.Version.CURRENT);
  try {
    JsonGenerator jg = jf.createJsonGenerator(hdos, JsonEncoding.UTF8);
    enableDisableJSONGeneratorFeature(jg);
    getJSONString(jg, m_pdxInstance);
    jg.close();
    return new String(hdos.toByteArray());
  } catch (IOException e) {
    throw new RuntimeException(e.getMessage());
  } finally {
    hdos.close();
  }
}
项目:athena    文件:JsonRpcReaderUtil.java   
/**
 * Check whether the encoding is valid.
 * @param in input of bytes
 * @throws IOException this is an IO exception
 * @throws UnsupportedException this is an unsupported exception
 */
private static void checkEncoding(ByteBuf in) throws IOException {
    int inputStart = 0;
    int inputLength = 4;
    fliterCharaters(in);
    byte[] buff = new byte[4];
    in.getBytes(in.readerIndex(), buff);
    ByteSourceJsonBootstrapper strapper = new ByteSourceJsonBootstrapper(new IOContext(new BufferRecycler(),
                                                                                       null,
                                                                                       false),
                                                                         buff, inputStart,
                                                                         inputLength);
    JsonEncoding jsonEncoding = strapper.detectEncoding();
    if (!JsonEncoding.UTF8.equals(jsonEncoding)) {
        throw new UnsupportedException("Only UTF-8 encoding is supported.");
    }
}
项目:swblocks-decisiontree    文件:JsonJacksonSerialiser.java   
/**
 * Serialises the {@link DecisionTreeRuleSet} into the {@link OutputStream} in Json format.
 *
 * <p>Any exceptions are wrapped and thrown via the {@link EhSupport} API.
 *
 * @param out     {@link OutputStream} to write into
 * @param ruleSet {@link DecisionTreeRuleSet} to serialise
 */
public static void toJsonWriter(final OutputStream out, final DecisionTreeRuleSet ruleSet) {
    EhSupport.propagate(() -> {
        try (JsonGenerator generator = new JsonFactory().createGenerator(out, JsonEncoding.UTF8)) {
            generator.useDefaultPrettyPrinter();
            generator.writeStartObject();
            generator.writeStringField("name", ruleSet.getName());
            writeRuleSetDrivers(generator, ruleSet);
            writeRuleSetGroups(generator, ruleSet.getValueGroups());
            writeRules(generator, ruleSet);

            generator.writeEndObject();
            generator.flush();
        }
    });
}
项目:spring-data-jest    文件:DefaultJestResultsMapper.java   
private String buildJSONFromFields(Collection<SearchHitField> values) {
    JsonFactory nodeFactory = new JsonFactory();
    try {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        JsonGenerator generator = nodeFactory.createGenerator(stream, JsonEncoding.UTF8);
        generator.writeStartObject();
        for (SearchHitField value : values) {
            if (value.getValues().size() > 1) {
                generator.writeArrayFieldStart(value.getName());
                for (Object val : value.getValues()) {
                    generator.writeObject(val);
                }
                generator.writeEndArray();
            } else {
                generator.writeObjectField(value.getName(), value.getValue());
            }
        }
        generator.writeEndObject();
        generator.flush();
        return new String(stream.toByteArray(), Charset.forName("UTF-8"));
    } catch (IOException e) {
        return null;
    }
}
项目:the-mathmos-server    文件:TextSearchAnnotationMapper.java   
private String buildJSONFromFields(Collection<SearchHitField> values) {
JsonFactory nodeFactory = new JsonFactory();
try {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    JsonGenerator generator = nodeFactory.createGenerator(stream, JsonEncoding.UTF8);
    generator.writeStartObject();
    for (SearchHitField value : values) {
    if (value.getValues().size() > 1) {
        generator.writeArrayFieldStart(value.getName());
        for (Object val : value.getValues()) {
        generator.writeObject(val);
        }
        generator.writeEndArray();
    } else {
        generator.writeObjectField(value.getName(), value.getValue());
    }
    }
    generator.writeEndObject();
    generator.flush();
    return new String(stream.toByteArray(), Charset.forName("UTF-8"));
} catch (IOException e) {
    LOG.error("IOException in buildJSONFromFields ", e);
    return null;
}
   }
项目:WhiteLab2.0-Neo4J-Plugin    文件:CypherExecutor.java   
public Response getQueryResult(final Query query) {
    StreamingOutput stream = new StreamingOutput() {
        @Override
        public void write( OutputStream os ) throws IOException, WebApplicationException {
            JsonGenerator jg = objectMapper.getFactory().createGenerator(os, JsonEncoding.UTF8);
            jg.setPrettyPrinter(new DefaultPrettyPrinter());
            jg.writeStartObject();
            if (query != null && query.toCypher().length() > 0) {
                writeQueryDetails(jg, query);
                System.out.println(query.toCypher());
                executeQuery(jg, query);
            } else {
                jg.writeStringField("error", "No query supplied.");
            }
            jg.writeEndObject();
            jg.flush();
            jg.close();
        }
    };

    return Response.ok().entity( stream ).type( MediaType.APPLICATION_JSON ).build();
}
项目:WhiteLab2.0-Neo4J-Plugin    文件:MetadatumSearcher.java   
protected Response getMetadataLabel(final String label) {
    StreamingOutput stream = new StreamingOutput()
    {
        @Override
        public void write( OutputStream os ) throws IOException, WebApplicationException
        {
            try ( Transaction tx = database.beginTx() ) {
                JsonGenerator jg = objectMapper.getFactory().createGenerator(os, JsonEncoding.UTF8);
                IndexManager index = database.index();
                Index<Node> metadata = index.forNodes("Metadatum");
                jg.writeStartArray();
                for ( Node metadatum : metadata.query( "label:"+label ) ) {
                    executor.writeField(metadatum, jg);
                }
                jg.writeEndArray();
                jg.flush();
                tx.success();
            }
        }
    };

    return Response.ok().entity( stream ).type( MediaType.APPLICATION_JSON ).build();
}
项目:WhiteLab2.0-Neo4J-Plugin    文件:MetadatumSearcher.java   
protected Response updateMetadataLabel(final String label, final String property, final String value) {
    StreamingOutput stream = new StreamingOutput()
    {
        @Override
        public void write( OutputStream os ) throws IOException, WebApplicationException
        {
            try ( Transaction tx = database.beginTx() ) {
                JsonGenerator jg = objectMapper.getFactory().createGenerator(os, JsonEncoding.UTF8);
                IndexManager index = database.index();
                Index<Node> metadata = index.forNodes("Metadatum");
                for ( Node metadatum : metadata.query( "label:"+label ) ) {
                    if (property.equals("explorable") || property.equals("searchable"))
                        metadatum.setProperty(property, Boolean.valueOf(value));
                    else
                        metadatum.setProperty(property, value);
                }
                jg.writeString("Updated "+label);
                jg.flush();
                tx.success();
            }
        }
    };

    return Response.ok().entity( stream ).type( MediaType.APPLICATION_JSON ).build();
}
项目:WhiteLab2.0-Neo4J-Plugin    文件:MetadatumSearcher.java   
protected Response getMetadataGroupKey(final String group, final String key) {
    StreamingOutput stream = new StreamingOutput()
    {
        @Override
        public void write( OutputStream os ) throws IOException, WebApplicationException
        {
            try ( Transaction tx = database.beginTx() ) {
                JsonGenerator jg = objectMapper.getFactory().createGenerator(os, JsonEncoding.UTF8);
                IndexManager index = database.index();
                Index<Node> metadata = index.forNodes("Metadatum");
                jg.writeStartArray();
                for ( Node metadatum : metadata.query( "group:"+group+" AND key:"+key ) ) {
                    executor.writeField(metadatum, jg);
                }
                jg.writeEndArray();
                jg.flush();
                tx.success();
            }
        }
    };

    return Response.ok().entity( stream ).type( MediaType.APPLICATION_JSON ).build();
}
项目:vespa    文件:MockQueryHandler.java   
private String getResponse(String query) throws IOException {
    List<MockQueryHit> hits = hitMap.get(query);
    if (hits == null) {
        return null;
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    JsonGenerator g = new JsonFactory().createGenerator(out, JsonEncoding.UTF8);

    writeResultStart(g, hits.size());
    for (MockQueryHit hit : hits) {
        writeHit(g, hit);
    }
    writeResultsEnd(g);
    g.close();

    return out.toString();
}
项目:odata    文件:JsonWriterUtilTest.java   
@Test
public void testWritePrimitiveValues() throws Exception {

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    JsonGenerator jsonGenerator = new JsonFactory().createGenerator(stream, JsonEncoding.UTF8);

    jsonGenerator.writeStartObject();
    appendPrimitiveValue("MyString", "Some text", jsonGenerator);
    appendPrimitiveValue("MyByteProperty", Byte.MAX_VALUE, jsonGenerator);
    appendPrimitiveValue("MyShortProperty", (short) 1, jsonGenerator);
    appendPrimitiveValue("MyIntegerProperty", 2, jsonGenerator);
    appendPrimitiveValue("MyFloatProperty", 3.0f, jsonGenerator);
    appendPrimitiveValue("MyDoubleProperty", 4.0d, jsonGenerator);
    appendPrimitiveValue("MyLongProperty", (long) 5, jsonGenerator);
    appendPrimitiveValue("MyBooleanProperty", true, jsonGenerator);
    appendPrimitiveValue("MyUUIDProperty", UUID.fromString("23492a5b-c4f1-4a50-b7a5-d8ebd6067902"), jsonGenerator);
    appendPrimitiveValue("DecimalValueProperty", BigDecimal.valueOf(21), jsonGenerator);

    jsonGenerator.writeEndObject();
    jsonGenerator.close();

    assertEquals(prettyPrintJson(readContent(EXPECTED_PRIMITIVE_VALUES_PATH)), prettyPrintJson(stream.toString()));
}
项目:extract    文件:DumpReportTask.java   
/**
 * Dump the report as JSON to the given output stream.
 *
 * @param reportMap the report to dump
 * @param output the stream to dump to
 * @param match only dump matching results
 */
private void dump(final ReportMap reportMap, final OutputStream output, final ExtractionStatus match) throws
        IOException {
    final ObjectMapper mapper = new ObjectMapper();
    final SimpleModule module = new SimpleModule();

    module.addSerializer(ReportMap.class, new ReportSerializer(monitor, match));
    mapper.registerModule(module);

    try (final JsonGenerator jsonGenerator = new JsonFactory().setCodec(mapper).createGenerator(output,
            JsonEncoding.UTF8)) {
        jsonGenerator.useDefaultPrettyPrinter();
        jsonGenerator.writeObject(reportMap);
        jsonGenerator.writeRaw('\n');
    }
}
项目:ShoppingMall    文件:MappingJackson2HttpMessageConverter.java   
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
    JsonGenerator jsonGenerator =
            this.objectMapper.getFactory().createJsonGenerator(outputMessage.getBody(), encoding);
    try {
        if (this.prefixJson) {
            jsonGenerator.writeRaw("{} && ");
        }
        this.objectMapper.writeValue(jsonGenerator, object);
    }
    catch (IOException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}
项目:logback-json-encoder    文件:JSONEncoder.java   
public void doEncode(ILoggingEvent event) throws IOException {
    long l = System.nanoTime();
    if (layoutNode != null) {
        JsonGenerator generator = JSON_FACTORY.createGenerator(
                outputStream, JsonEncoding.UTF8);
        JsonParser parser = layoutNode.traverse();
        try {
            encodeJson(parser, generator, event);
        } finally {
            parser.close();
            generator.writeRaw("\n");
        }

        if (isImmediateFlush())
            generator.flush();
    }
    l = System.nanoTime() - l;
    System.out.println("==> " + l);
}
项目:QuizUpWinner    文件:ObjectWriter.java   
public byte[] writeValueAsBytes(Object paramObject)
{
  ByteArrayBuilder localByteArrayBuilder = new ByteArrayBuilder(this._jsonFactory._getBufferRecycler());
  try
  {
    _configAndWriteValue(this._jsonFactory.createGenerator(localByteArrayBuilder, JsonEncoding.UTF8), paramObject);
  }
  catch (JsonProcessingException localJsonProcessingException)
  {
    throw localJsonProcessingException;
  }
  catch (IOException localIOException)
  {
    throw JsonMappingException.fromUnexpectedIOE(localIOException);
  }
  byte[] arrayOfByte = localByteArrayBuilder.toByteArray();
  localByteArrayBuilder.release();
  return arrayOfByte;
}
项目:hydra-java    文件:SirenMessageConverter.java   
@Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException,
        HttpMessageNotWritableException {
    SirenEntity entity = new SirenEntity();
    sirenUtils.toSirenEntity(entity, o);

    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders()
            .getContentType());
    JsonGenerator jsonGenerator = this.objectMapper.getFactory()
            .createGenerator(outputMessage.getBody(), encoding);

    // A workaround for JsonGenerators not applying serialization features
    // https://github.com/FasterXML/jackson-databind/issues/12
    if (this.objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
        jsonGenerator.useDefaultPrettyPrinter();
    }

    try {
        this.objectMapper.writeValue(jsonGenerator, entity);
    } catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}
项目:hydra-java    文件:UberJackson2HttpMessageConverter.java   
@Override
protected void writeInternal(Object t, HttpOutputMessage outputMessage) throws IOException,
        HttpMessageNotWritableException {

    UberMessageModel uberModel = new UberMessageModel(t);
    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders()
            .getContentType());
    JsonGenerator jsonGenerator = this.objectMapper.getFactory()
            .createGenerator(outputMessage.getBody(), encoding);

    // A workaround for JsonGenerators not applying serialization features
    // https://github.com/FasterXML/jackson-databind/issues/12
    if (this.objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
        jsonGenerator.useDefaultPrettyPrinter();
    }

    try {
        this.objectMapper.writeValue(jsonGenerator, uberModel);
    } catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}
项目:JsonResponse    文件:JsonResponseAwareJsonMessageConverter.java   
protected void writeJson(ResponseWrapper response, HttpOutputMessage outputMessage) throws IOException,
        HttpMessageNotWritableException {

    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());

    ObjectMapper mapper = new ObjectMapper();

    // Add support for jackson mixins
    JsonMixin[] jsonMixins = response.getJsonResponse().mixins();
    for (JsonMixin jsonMixin : jsonMixins) {
        mapper.addMixInAnnotations(jsonMixin.target(), jsonMixin.mixin());
    }

    JsonGenerator jsonGenerator = mapper.getFactory().createGenerator(outputMessage.getBody(), encoding);
    try {
        mapper.writeValue(jsonGenerator, response.getOriginalResponse());
    } catch (IOException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}
项目:class-guard    文件:MappingJackson2HttpMessageConverter.java   
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
    JsonGenerator jsonGenerator =
            this.objectMapper.getJsonFactory().createJsonGenerator(outputMessage.getBody(), encoding);

    // A workaround for JsonGenerators not applying serialization features
    // https://github.com/FasterXML/jackson-databind/issues/12
    if (this.objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
        jsonGenerator.useDefaultPrettyPrinter();
    }

    try {
        if (this.jsonPrefix != null) {
            jsonGenerator.writeRaw(this.jsonPrefix);
        }
        this.objectMapper.writeValue(jsonGenerator, object);
    }
    catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}
项目:hawkular-metrics    文件:NamedDataPointObserver.java   
public NamedDataPointObserver(AsyncResponse response, ObjectMapper mapper, MetricType<T> type) {
    this.response = response;
    jsonOutputStream = new ByteArrayOutputStream();
    try {
        this.generator = mapper.getFactory().createGenerator(jsonOutputStream, JsonEncoding.UTF8);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    if (type == MetricType.GAUGE || type == MetricType.GAUGE_RATE || type == MetricType.COUNTER_RATE) {
        writeValue = dataPoint -> generator.writeNumberField("value", (Double) dataPoint.getValue());
    } else if (type == MetricType.COUNTER) {
        writeValue = dataPoint -> generator.writeNumberField("value", (Long) dataPoint.getValue());
    } else if (type == MetricType.AVAILABILITY) {
        writeValue = dataPoint -> {
            AvailabilityType availability = (AvailabilityType) dataPoint.getValue();
            generator.writeStringField("value", availability.getText());
        };
    } else if (type == MetricType.STRING) {
        writeValue = dataPoint -> generator.writeStringField("value", (String) dataPoint.getValue());
    } else {
        throw new IllegalArgumentException(type + " is not supported metric type. This class should be " +
                "updated to add support for it!");
    }
}
项目:onos    文件:JsonRpcReaderUtil.java   
/**
 * Check whether the encoding is valid.
 * @param in input of bytes
 * @throws IOException this is an IO exception
 * @throws UnsupportedException this is an unsupported exception
 */
private static void checkEncoding(ByteBuf in) throws IOException {
    int inputStart = 0;
    int inputLength = 4;
    fliterCharaters(in);
    byte[] buff = new byte[4];
    in.getBytes(in.readerIndex(), buff);
    ByteSourceJsonBootstrapper strapper = new ByteSourceJsonBootstrapper(new IOContext(new BufferRecycler(),
                                                                                       null,
                                                                                       false),
                                                                         buff, inputStart,
                                                                         inputLength);
    JsonEncoding jsonEncoding = strapper.detectEncoding();
    if (!JsonEncoding.UTF8.equals(jsonEncoding)) {
        throw new UnsupportedException("Only UTF-8 encoding is supported.");
    }
}
项目:usergrid    文件:ResultsLog.java   
@Override
public void open() throws IOException {
    synchronized ( isOpen ) {
        if ( isOpen.compareAndSet( false, true ) ) {
            resultCount.set( 0 );

            // write the json header for recording the chop results
            JsonFactory factory = new JsonFactory();
            jgen = factory.createGenerator(  new File( resultsFile.get() ), JsonEncoding.UTF8 );

            if ( prettyPrint.get() ) {
                jgen.useDefaultPrettyPrinter();
            }

            jgen.setCodec( new ObjectMapper() );

            setupJsonStream();

            thread = new Thread( this, "ResultLog Writer" );
            thread.start();
        }
    }
}
项目:GitHub    文件:IOContext.java   
/**
 * @since 3.0
 */
public IOContext(BufferRecycler br, Object sourceRef, boolean managedResource,
        JsonEncoding enc)
{
    _bufferRecycler = br;
    _sourceRef = sourceRef;
    _managedResource = managedResource;
    _encoding = enc;
}
项目:GitHub    文件:TestMergedStream.java   
public void testSimple() throws Exception
{
    BufferRecycler rec = new BufferRecycler();
    IOContext ctxt = new IOContext(rec, null, false);
    // bit complicated; must use recyclable buffer...
    byte[] first = ctxt.allocReadIOBuffer();
    System.arraycopy("ABCDE".getBytes("UTF-8"), 0, first, 99, 5);
    byte[] second = "FGHIJ".getBytes("UTF-8");

    assertNull(ctxt.getSourceReference());
    assertFalse(ctxt.isResourceManaged());
    ctxt.setEncoding(JsonEncoding.UTF8);
    MergedStream ms = new MergedStream(ctxt, new ByteArrayInputStream(second),
                                       first, 99, 99+5);
    // Ok, first, should have 5 bytes from first buffer:
    assertEquals(5, ms.available());
    // not supported when there's buffered stuff...
    assertFalse(ms.markSupported());
    // so this won't work, but shouldn't throw exception
    ms.mark(1);
    assertEquals((byte) 'A', ms.read());
    assertEquals(3, ms.skip(3));
    byte[] buffer = new byte[5];
    /* Ok, now, code is allowed to return anywhere between 1 and 3,
     * but we now it will return 1...
     */
    assertEquals(1, ms.read(buffer, 1, 3));
    assertEquals((byte) 'E', buffer[1]);
    // So let's read bit more
    assertEquals(3, ms.read(buffer, 0, 3));
    assertEquals((byte) 'F', buffer[0]);
    assertEquals((byte) 'G', buffer[1]);
    assertEquals((byte) 'H', buffer[2]);
    assertEquals(2, ms.available());
    // And then skip the reset
    assertEquals(2, ms.skip(200));

    ms.close();
}
项目:teamcity-hashicorp-vault-plugin    文件:AbstractJackson2HttpMessageConverter.java   
@Override
@SuppressWarnings("deprecation")
protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
    JsonGenerator generator = this.objectMapper.getFactory().createGenerator(outputMessage.getBody(), encoding);
    try {

        JavaType javaType = null;
        if (jackson26Available && type != null && object != null && TypeUtils.isAssignable(type, object.getClass())) {
            javaType = getJavaType(type, null);
        }
        ObjectWriter objectWriter;
        objectWriter = this.objectMapper.writer();
        if (javaType != null && javaType.isContainerType()) {
            objectWriter = objectWriter.withType(javaType);
        }
        objectWriter.writeValue(generator, object);

        generator.flush();

    }
    catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write content: " + ex.getMessage(), ex);
    }
}
项目:teamcity-hashicorp-vault-plugin    文件:AbstractJackson2HttpMessageConverter.java   
/**
 * Determine the JSON encoding to use for the given content type.
 * @param contentType the media type as requested by the caller
 * @return the JSON encoding to use (never {@code null})
 */
protected JsonEncoding getJsonEncoding(MediaType contentType) {
    if (contentType != null && contentType.getCharSet() != null) {
        Charset charset = contentType.getCharSet();
        for (JsonEncoding encoding : JsonEncoding.values()) {
            if (charset.name().equals(encoding.getJavaName())) {
                return encoding;
            }
        }
    }
    return JsonEncoding.UTF8;
}
项目:graphium    文件:GenericJacksonSegmentOutputFormat.java   
public GenericJacksonSegmentOutputFormat(ISegmentAdapterRegistry<? extends IBaseSegmentDTO, T> adapterRegistry, 
        OutputStream stream, JsonGenerator generator)
{
    this.adapterRegistry = adapterRegistry;
    if (generator == null) {
        try {
            this.generator = new MappingJsonFactory().createGenerator(stream, JsonEncoding.UTF8);
            this.generator.useDefaultPrettyPrinter();
        } catch (IOException e) {
            log.error("error creating jackson json factory", e);
        }
    } else {
        this.generator = generator;
    }
}
项目:lams    文件:MappingJackson2HttpMessageConverter.java   
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
    // The following has been deprecated as late as Jackson 2.2 (April 2013);
    // preserved for the time being, for Jackson 2.0/2.1 compatibility.
    @SuppressWarnings("deprecation")
    JsonGenerator jsonGenerator =
            this.objectMapper.getJsonFactory().createJsonGenerator(outputMessage.getBody(), encoding);

    // A workaround for JsonGenerators not applying serialization features
    // https://github.com/FasterXML/jackson-databind/issues/12
    if (this.objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
        jsonGenerator.useDefaultPrettyPrinter();
    }

    try {
        if (this.jsonPrefix != null) {
            jsonGenerator.writeRaw(this.jsonPrefix);
        }
        this.objectMapper.writeValue(jsonGenerator, object);
    }
    catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}
项目:lams    文件:MappingJackson2HttpMessageConverter.java   
/**
 * Determine the JSON encoding to use for the given content type.
 * @param contentType the media type as requested by the caller
 * @return the JSON encoding to use (never {@code null})
 */
protected JsonEncoding getJsonEncoding(MediaType contentType) {
    if (contentType != null && contentType.getCharSet() != null) {
        Charset charset = contentType.getCharSet();
        for (JsonEncoding encoding : JsonEncoding.values()) {
            if (charset.name().equals(encoding.getJavaName())) {
                return encoding;
            }
        }
    }
    return JsonEncoding.UTF8;
}
项目:WIFIProbe    文件:MapToJsonTest.java   
@Test
public void jsonTest() throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(System.out, JsonEncoding.UTF8);
    List<Map> mapList = new ArrayList<>();
    Map map = new HashMap();
    map.put("name","hello");
    map.put("k",1);
    mapList.add(map);
    jsonGenerator.writeObject(mapList);
}