下面列出了怎么用com.fasterxml.jackson.core.JsonGenerator.Feature的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Serialize parquet metadata to json and write to a file.
*
* @param parquetMetadata parquet table or directory metadata
* @param p file path
* @param fs Drill file system
* @throws IOException if metadata can't be serialized
*/
private void writeFile(Object parquetMetadata, Path p, FileSystem fs) throws IOException {
JsonFactory jsonFactory = new JsonFactory();
jsonFactory.configure(Feature.AUTO_CLOSE_TARGET, false);
jsonFactory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
ObjectMapper mapper = new ObjectMapper(jsonFactory);
SimpleModule module = new SimpleModule();
module.addSerializer(Path.class, new PathSerDe.Se());
if (parquetMetadata instanceof Metadata_V4.FileMetadata) {
module.addSerializer(ColumnMetadata_v4.class, new ColumnMetadata_v4.Serializer());
}
mapper.registerModule(module);
OutputStream os = fs.create(p);
mapper.writerWithDefaultPrettyPrinter().writeValue(os, parquetMetadata);
os.flush();
os.close();
}
public FilterableJsonSerializer(FilterableJsonSerializerConfig config) {
NullArgumentChecker.DEFAULT.check(config, "config");
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.setSerializerModifier(new FilterableBeanSerializerModifier(config));
mapper.registerModule(module);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
mapper.configure(Feature.AUTO_CLOSE_TARGET, false);
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
_mapper = mapper;
}
private void init() throws IOException {
JsonFactory factory = new JsonFactory();
factory.configure(Feature.AUTO_CLOSE_TARGET, false);
generator = factory.createGenerator(writer);
if (prettyPrint) {
if (prettyPrinter == null) {
prettyPrinter = new JCalPrettyPrinter();
}
generator.setPrettyPrinter(prettyPrinter);
}
if (wrapInArray) {
generator.writeStartArray();
}
}
private void configMapper() {
_mapper.configure(Feature.AUTO_CLOSE_TARGET, false);
_mapper.configure(Feature.IGNORE_UNKNOWN, true);
_mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
_mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
_mapper.configure(JsonParser.Feature.IGNORE_UNDEFINED, true);
_mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
_mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
_mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
_mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
_mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
_mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
}
private JacksonJsonBytesSerializer() {
_mapper.configure(Feature.AUTO_CLOSE_TARGET, false);
_mapper.configure(Feature.IGNORE_UNKNOWN, true);
_mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
_mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
_mapper.configure(JsonParser.Feature.IGNORE_UNDEFINED, true);
_mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
_mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
_mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
_mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
_mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
_mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
}
private JacksonJsonSerializer() {
_mapper.configure(Feature.AUTO_CLOSE_TARGET, false);
_mapper.configure(Feature.IGNORE_UNKNOWN, true);
_mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
_mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
_mapper.configure(JsonParser.Feature.IGNORE_UNDEFINED, true);
_mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
_mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
_mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
_mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
_mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
_mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
_mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
}
private JacksonXmlSerializer() {
_mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
_mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
_mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
_mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
_mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
_mapper.configure(Feature.AUTO_CLOSE_TARGET, false);
}
private JacksonProtobuf2Serializer() {
_mapperWrapper = new ProtobufMapperWrapper();
_mapperWrapper.mapper().configure(Feature.AUTO_CLOSE_TARGET, false);
_mapperWrapper.mapper().configure(Feature.IGNORE_UNKNOWN, true);
_mapperWrapper.mapper().configure(JsonParser.Feature.IGNORE_UNDEFINED, true);
_mapperWrapper.mapper().configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
_mapperWrapper.mapper().configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
_mapperWrapper.mapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
_mapperWrapper.mapper().configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
_mapperWrapper.mapper().configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
_mapperWrapper.mapper().configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
}
private GoogleProtobuf2Serializer() {
ProtobufConfig protobufConfig = new ProtobufConfig();
protobufConfig.setEnumMode(EnumMode.ByValue);
_mapperWrapper = new ProtobufMapperWrapper(protobufConfig);
_mapperWrapper.mapper().configure(Feature.AUTO_CLOSE_TARGET, false);
_mapperWrapper.mapper().configure(Feature.IGNORE_UNKNOWN, true);
_mapperWrapper.mapper().configure(JsonParser.Feature.IGNORE_UNDEFINED, true);
_mapperWrapper.mapper().configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
_mapperWrapper.mapper().configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
_mapperWrapper.mapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
_mapperWrapper.mapper().configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
_mapperWrapper.mapper().configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
_mapperWrapper.mapper().configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
}
@Provides
static ObjectMapper objectMapper() {
return new ObjectMapper()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.enable(Feature.IGNORE_UNKNOWN)
.findAndRegisterModules();
}
protected void init(ObjectMapper objectMapper) {
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.setVisibility(objectMapper.getSerializationConfig()
.getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.enable(Feature.WRITE_BIGDECIMAL_AS_PLAIN);
objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
objectMapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
objectMapper.addMixIn(Throwable.class, ThrowableMixIn.class);
}
public static void toJSON(final ResValuesFile input,
final File outputDirectory) throws Exception {
String[] paths = input.getPath().split("/"); // always "/" even on Windows
final String outName = paths[paths.length - 1].replaceFirst("\\.xml$",
".json");
final File outFile = new File(outputDirectory, outName);
p("Saving to: " + outFile);
JsonGenerator generator = json.createGenerator(
new FileOutputStream(outFile), JsonEncoding.UTF8);
// Ensure output stream is auto closed when generator.close() is called.
generator.configure(Feature.AUTO_CLOSE_TARGET, true);
generator.configure(Feature.AUTO_CLOSE_JSON_CONTENT, true);
generator.configure(Feature.FLUSH_PASSED_TO_STREAM, true);
generator.configure(Feature.QUOTE_NON_NUMERIC_NUMBERS, true);
generator.configure(Feature.WRITE_NUMBERS_AS_STRINGS, true);
generator.configure(Feature.QUOTE_FIELD_NAMES, true);
// generator.configure(Feature.ESCAPE_NON_ASCII, true); // don't escape non
// ascii
generator.useDefaultPrettyPrinter();
// ResStringValue extends ResScalarValue which has field mRawValue
final Field valueField = ResScalarValue.class.getDeclaredField("mRawValue");
valueField.setAccessible(true);
generator.writeStartObject();
for (ResResource resource : input.listResources()) {
if (input.isSynthesized(resource)) {
continue;
}
final String name = resource.getResSpec().getName();
// Get the value field from the ResStringValue object.
final String value = (String) valueField.get(resource.getValue());
generator.writeStringField(name, value);
}
generator.writeEndObject();
generator.flush();
generator.close();
}
@Test
public void transactionTest() throws Exception {
final String serviceName = "serviceName-1";
final String instanceId = "instanceId-1";
final String globalTxId = UUID.randomUUID().toString();
final String localTxId_1 = UUID.randomUUID().toString();
final String localTxId_2 = UUID.randomUUID().toString();
final String localTxId_3 = UUID.randomUUID().toString();
List<BaseEvent> events = new ArrayList();
events.add(SagaStartedEvent.builder().serviceName("service_g").instanceId("instance_g")
.globalTxId(globalTxId).build());
events.add(TxStartedEvent.builder().serviceName("service_c1").instanceId("instance_c1")
.globalTxId(globalTxId).parentTxId(globalTxId).localTxId(localTxId_1).build());
events.add(TxEndedEvent.builder().serviceName("service_c1").instanceId("instance_c1")
.globalTxId(globalTxId).parentTxId(globalTxId).localTxId(localTxId_1).build());
events.add(TxStartedEvent.builder().serviceName("service_c2").instanceId("instance_c2")
.globalTxId(globalTxId).parentTxId(globalTxId).localTxId(localTxId_2).build());
events.add(TxEndedEvent.builder().serviceName("service_c2").instanceId("instance_c2")
.globalTxId(globalTxId).parentTxId(globalTxId).localTxId(localTxId_2).build());
events.add(TxStartedEvent.builder().serviceName("service_c3").instanceId("instance_c3")
.globalTxId(globalTxId).parentTxId(globalTxId).localTxId(localTxId_3).build());
events.add(TxEndedEvent.builder().serviceName("service_c3").instanceId("instance_c3")
.globalTxId(globalTxId).parentTxId(globalTxId).localTxId(localTxId_3).build());
events.add(SagaEndedEvent.builder().serviceName("service_g").instanceId("instance_g")
.globalTxId(globalTxId).build());
List<SagaSubTransaction> subTransactions = new ArrayList();
subTransactions
.add(SagaSubTransaction.builder().parentTxId(globalTxId).localTxId(localTxId_1).state(
TxState.COMMITTED).beginTime(new Date()).endTime(new Date()).build());
subTransactions
.add(SagaSubTransaction.builder().parentTxId(globalTxId).localTxId(localTxId_2).state(
TxState.COMMITTED).beginTime(new Date()).endTime(new Date()).build());
subTransactions
.add(SagaSubTransaction.builder().parentTxId(globalTxId).localTxId(localTxId_3).state(
TxState.COMMITTED).beginTime(new Date()).endTime(new Date()).build());
List<GlobalTransaction> globalTransactions = new ArrayList<>();
globalTransactions.add(GlobalTransaction.builder()
.serviceName(serviceName)
.instanceId(instanceId)
.globalTxId(globalTxId)
.type(TransactionType.SAGA)
.state(SagaActorState.COMMITTED.name())
.beginTime(new Date())
.endTime(new Date())
.subTxSize(3)
.events(events)
.subTransactions(subTransactions)
.build());
PagingGlobalTransactions paging = PagingGlobalTransactions.builder()
.page(0)
.size(50)
.elapsed(10)
.total(1)
.globalTransactions(globalTransactions)
.build();
when(transactionRepository.getGlobalTransactions(null,0, 50)).thenReturn(paging);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
mapper.configure(Feature.QUOTE_NON_NUMERIC_NUMBERS, false);
mockMvc.perform(get("/alpha/api/v1/transaction?page=0&size=50"))
.andExpect(status().isOk())
.andExpect(
MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.total").value(1))
.andExpect(jsonPath("$.page").value(0))
.andExpect(jsonPath("$.size").value(50))
.andExpect(jsonPath("$.elapsed").value(10))
.andExpect(jsonPath("$.globalTransactions", hasSize(1)))
.andExpect(jsonPath("$.globalTransactions[0].globalTxId")
.value(globalTransactions.get(0).getGlobalTxId()))
.andExpect(jsonPath("$.globalTransactions[0].type")
.value(globalTransactions.get(0).getType().name()))
.andExpect(jsonPath("$.globalTransactions[0].serviceName")
.value(globalTransactions.get(0).getServiceName()))
.andExpect(jsonPath("$.globalTransactions[0].instanceId")
.value(globalTransactions.get(0).getInstanceId()))
.andExpect(jsonPath("$.globalTransactions[0].beginTime")
.value(globalTransactions.get(0).getBeginTime().getTime()))
.andExpect(jsonPath("$.globalTransactions[0].endTime")
.value(globalTransactions.get(0).getEndTime().getTime()))
.andExpect(jsonPath("$.globalTransactions[0].state")
.value(globalTransactions.get(0).getState()))
.andExpect(jsonPath("$.globalTransactions[0].subTxSize")
.value(globalTransactions.get(0).getSubTxSize()))
.andExpect(jsonPath("$.globalTransactions[0].durationTime")
.value(globalTransactions.get(0).getDurationTime()))
.andExpect(jsonPath("$.globalTransactions[0].subTransactions", hasSize(3)))
.andExpect(jsonPath("$.globalTransactions[0].events", hasSize(8)))
.andReturn();
}
@Test
public void globalTransactionByGlobalTxIdTest() throws Exception {
final String serviceName = "serviceName-1";
final String instanceId = "instanceId-1";
final String globalTxId = UUID.randomUUID().toString();
final String localTxId_1 = UUID.randomUUID().toString();
final String localTxId_2 = UUID.randomUUID().toString();
final String localTxId_3 = UUID.randomUUID().toString();
List<BaseEvent> events = new ArrayList();
events.add(SagaStartedEvent.builder().serviceName("service_g").instanceId("instance_g")
.globalTxId(globalTxId).build());
events.add(TxStartedEvent.builder().serviceName("service_c1").instanceId("instance_c1")
.globalTxId(globalTxId).parentTxId(globalTxId).localTxId(localTxId_1).build());
events.add(TxEndedEvent.builder().serviceName("service_c1").instanceId("instance_c1")
.globalTxId(globalTxId).parentTxId(globalTxId).localTxId(localTxId_1).build());
events.add(TxStartedEvent.builder().serviceName("service_c2").instanceId("instance_c2")
.globalTxId(globalTxId).parentTxId(globalTxId).localTxId(localTxId_2).build());
events.add(TxEndedEvent.builder().serviceName("service_c2").instanceId("instance_c2")
.globalTxId(globalTxId).parentTxId(globalTxId).localTxId(localTxId_2).build());
events.add(TxStartedEvent.builder().serviceName("service_c3").instanceId("instance_c3")
.globalTxId(globalTxId).parentTxId(globalTxId).localTxId(localTxId_3).build());
events.add(TxEndedEvent.builder().serviceName("service_c3").instanceId("instance_c3")
.globalTxId(globalTxId).parentTxId(globalTxId).localTxId(localTxId_3).build());
events.add(SagaEndedEvent.builder().serviceName("service_g").instanceId("instance_g")
.globalTxId(globalTxId).build());
List<SagaSubTransaction> subTransactions = new ArrayList();
subTransactions
.add(SagaSubTransaction.builder().parentTxId(globalTxId).localTxId(localTxId_1).state(
TxState.COMMITTED).beginTime(new Date()).endTime(new Date()).build());
subTransactions
.add(SagaSubTransaction.builder().parentTxId(globalTxId).localTxId(localTxId_2).state(
TxState.COMMITTED).beginTime(new Date()).endTime(new Date()).build());
subTransactions
.add(SagaSubTransaction.builder().parentTxId(globalTxId).localTxId(localTxId_3).state(
TxState.COMMITTED).beginTime(new Date()).endTime(new Date()).build());
GlobalTransaction globalTransaction = GlobalTransaction.builder()
.serviceName(serviceName)
.instanceId(instanceId)
.globalTxId(globalTxId)
.type(TransactionType.SAGA)
.state(SagaActorState.COMMITTED.name())
.beginTime(new Date())
.endTime(new Date())
.subTxSize(3)
.events(events)
.subTransactions(subTransactions)
.build();
when(transactionRepository.getGlobalTransactionByGlobalTxId(globalTxId)).thenReturn(globalTransaction);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
mapper.configure(Feature.QUOTE_NON_NUMERIC_NUMBERS, false);
mockMvc.perform(get("/alpha/api/v1/transaction/"+globalTxId))
.andDo(print())
.andExpect(status().isOk())
.andExpect(
MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.globalTxId")
.value(globalTransaction.getGlobalTxId()))
.andExpect(jsonPath("$.type")
.value(globalTransaction.getType().name()))
.andExpect(jsonPath("$.serviceName")
.value(globalTransaction.getServiceName()))
.andExpect(jsonPath("$.instanceId")
.value(globalTransaction.getInstanceId()))
.andExpect(jsonPath("$.beginTime")
.value(globalTransaction.getBeginTime().getTime()))
.andExpect(jsonPath("$.endTime")
.value(globalTransaction.getEndTime().getTime()))
.andExpect(jsonPath("$.state")
.value(globalTransaction.getState()))
.andExpect(jsonPath("$.subTxSize")
.value(globalTransaction.getSubTxSize()))
.andExpect(jsonPath("$.durationTime")
.value(globalTransaction.getDurationTime()))
.andExpect(jsonPath("$.subTransactions", hasSize(3)))
.andExpect(jsonPath("$.events", hasSize(8)))
.andReturn();
}
public JacksonService() {
// fun Jackson API with circular dependencies ... so we create a mapper
// first, and grab implicitly created factory from it
this.sharedMapper = new ObjectMapper();
this.sharedFactory = sharedMapper.getFactory();
final SerializableString LINE_SEPARATOR = new SerializedString("\\u2028");
final SerializableString PARAGRAPH_SEPARATOR = new SerializedString("\\u2029");
this.sharedFactory.setCharacterEscapes(new CharacterEscapes() {
private static final long serialVersionUID = 3995801066651016289L;
@Override
public int[] getEscapeCodesForAscii() {
return standardAsciiEscapesForJSON();
}
@Override
public SerializableString getEscapeSequence(int ch) {
// see ECMA-262 Section 7.3;
// in most cases our client is browser,
// and JSON is parsed into JS;
// therefore these two whitespace characters,
// which are perfectly valid in JSON but invalid in JS strings,
// need to be escaped...
switch (ch) {
case '\u2028':
return LINE_SEPARATOR;
case '\u2029':
return PARAGRAPH_SEPARATOR;
default:
return null;
}
}
});
// make sure mapper does not attempt closing streams it does not
// manage... why is this even a default in jackson?
sharedFactory.disable(Feature.AUTO_CLOSE_TARGET);
// do not flush every time. why would we want to do that?
// this is having a HUGE impact on extrest serializers (5x speedup)
sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE);
}