List of usage examples for com.fasterxml.jackson.databind ObjectMapper enable
public ObjectMapper enable(SerializationFeature f)
From source file:com.tectonica.thirdparty.Jackson2.java
public static ObjectMapper createPropsMapper() { ObjectMapper mapper = new ObjectMapper(); // limit to props only mapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE); mapper.setVisibility(PropertyAccessor.GETTER, Visibility.ANY); mapper.setVisibility(PropertyAccessor.SETTER, Visibility.ANY); // general configuration mapper.setSerializationInclusion(Include.NON_NULL); mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); return mapper; }
From source file:com.tectonica.thirdparty.Jackson2.java
public static ObjectMapper createFieldsMapper() { ObjectMapper mapper = new ObjectMapper(); // limit to fields only mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); mapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE); mapper.setVisibility(PropertyAccessor.SETTER, Visibility.NONE); // general configuration mapper.setSerializationInclusion(Include.NON_NULL); mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); return mapper; }
From source file:de.fau.cs.inf2.tree.evaluation.TreeEvalIO.java
public static ObjectMapper createJSONMapper(final DataFormat format) { final ObjectMapper mapper; {/*from w w w . j a v a 2 s. c o m*/ switch (format) { case FORMAT_JSON: { mapper = new ObjectMapper(); break; } default: { assert (false); return null; } } } // configure mapper { mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE)); mapper.setSerializationInclusion(Include.NON_NULL); DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S"); mapper.setDateFormat(df); addMixIns(mapper, TimeSummary.class, MixInTimeSummary.class); addMixIns(mapper, DiffSummary.class, MixInDiffSummary.class); addMixIns(mapper, TreeMatcherTypeEnum.class, MixInTreeMatcherTypeEnum.class); addMixIns(mapper, PsoResult.class, MixInPSOResult.class); addMixIns(mapper, ValidationDecision.class, MixInValidationDecision.class); addMixIns(mapper, ValidationDecisionList.class, MixInValidationDecisionList.class); addMixIns(mapper, ValidationEntry.class, MixInValidationEntry.class); addMixIns(mapper, ValidationEnum.class, MixInValidationEnum.class); addMixIns(mapper, ValidationRating.class, MixInValidationRating.class); addMixIns(mapper, ValidationInputSummary.class, MixInValidationInputSummary.class); addMixIns(mapper, ValidationInfo.class, MixInValidationInfo.class); } return mapper; }
From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java
private static void mapComplexTypes(List<APITypeModel> typeModels, Field fields[], boolean onlyConsumeField) { //Should strip duplicate types Set<String> typesInList = new HashSet<>(); typeModels.forEach(type -> {/* w w w .j ava 2 s . co m*/ typesInList.add(type.getName()); }); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); for (Field field : fields) { boolean capture = true; if (onlyConsumeField) { ConsumeField consumeField = (ConsumeField) field.getAnnotation(ConsumeField.class); if (consumeField == null) { capture = false; } } if (capture) { Class fieldClass = field.getType(); DataType dataType = (DataType) field.getAnnotation(DataType.class); if (dataType != null) { fieldClass = dataType.value(); } if (ReflectionUtil.isComplexClass(fieldClass)) { APITypeModel typeModel = new APITypeModel(); typeModel.setName(fieldClass.getSimpleName()); APIDescription aPIDescription = (APIDescription) fieldClass.getAnnotation(APIDescription.class); if (aPIDescription != null) { typeModel.setDescription(aPIDescription.value()); } Set<String> fieldList = mapValueField(typeModel.getFields(), fieldClass.getDeclaredFields(), onlyConsumeField); if (fieldClass.isEnum()) { typeModel.setObject(Arrays.toString(fieldClass.getEnumConstants())); } else { if (fieldClass.isInterface() == false) { try { typeModel.setObject(objectMapper.writeValueAsString(fieldClass.newInstance())); String cleanUpJson = StringProcessor.stripeFieldJSON(typeModel.getObject(), fieldList); typeModel.setObject(cleanUpJson); } catch (InstantiationException | IllegalAccessException | JsonProcessingException ex) { log.log(Level.WARNING, "Unable to process/map complex field: " + fieldClass.getSimpleName(), ex); typeModel.setObject("{ Unable to view }"); } mapComplexTypes(typeModels, fieldClass.getDeclaredFields(), onlyConsumeField); } } typeModels.add(typeModel); typesInList.add(typeModel.getName()); } } } }
From source file:com.addthis.codec.jackson.Jackson.java
public static ObjectMapper toggleObjectMapperOptions(ObjectMapper objectMapper) { // potentially useful features, but disabled by default to maintain existing behavior // ignore final fields objectMapper.disable(ALLOW_FINAL_FIELDS_AS_MUTATORS); // do not try to modify existing containers objectMapper.disable(USE_GETTERS_AS_SETTERS); // public getters do not automaticaly imply codec should try to write to it objectMapper.disable(INFER_PROPERTY_MUTATORS); // more aggressive failure detection objectMapper.enable(FAIL_ON_READING_DUP_TREE_KEY); // essentially auto-collection everywhere, but that seems fine and this is easy objectMapper.enable(ACCEPT_SINGLE_VALUE_AS_ARRAY); // don't write out null fields objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return objectMapper; }
From source file:Main.java
public static String takeDumpJSON(ThreadMXBean threadMXBean) throws IOException { ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true); List<Map<String, Object>> threads = new ArrayList<>(); for (ThreadInfo thread : threadInfos) { Map<String, Object> threadMap = new HashMap<>(); threadMap.put("name", thread.getThreadName()); threadMap.put("id", thread.getThreadId()); threadMap.put("state", thread.getThreadState().name()); List<String> stacktrace = new ArrayList<>(); for (StackTraceElement element : thread.getStackTrace()) { stacktrace.add(element.toString()); }// w w w. j av a 2 s. c o m threadMap.put("stack", stacktrace); if (thread.getLockName() != null) { threadMap.put("lock_name", thread.getLockName()); } if (thread.getLockOwnerId() != -1) { threadMap.put("lock_owner_id", thread.getLockOwnerId()); } if (thread.getBlockedTime() > 0) { threadMap.put("blocked_time", thread.getBlockedTime()); } if (thread.getBlockedCount() > 0) { threadMap.put("blocked_count", thread.getBlockedCount()); } if (thread.getLockedMonitors().length > 0) { threadMap.put("locked_monitors", thread.getLockedMonitors()); } if (thread.getLockedSynchronizers().length > 0) { threadMap.put("locked_synchronizers", thread.getLockedSynchronizers()); } threads.add(threadMap); } ObjectMapper om = new ObjectMapper(); ObjectNode json = om.createObjectNode(); json.put("date", new Date().toString()); json.putPOJO("threads", threads); long[] deadlockedThreads = threadMXBean.findDeadlockedThreads(); long[] monitorDeadlockedThreads = threadMXBean.findMonitorDeadlockedThreads(); if (deadlockedThreads != null && deadlockedThreads.length > 0) { json.putPOJO("deadlocked_thread_ids", deadlockedThreads); } if (monitorDeadlockedThreads != null && monitorDeadlockedThreads.length > 0) { json.putPOJO("monitor_deadlocked_thread_ids", monitorDeadlockedThreads); } om.enable(SerializationFeature.INDENT_OUTPUT); return om.writerWithDefaultPrettyPrinter().writeValueAsString(json); }
From source file:com.rockagen.commons.util.JsonUtil.java
/** * Initialize mapper/* w ww. jav a 2 s . c o m*/ * * @return initialized {@link ObjectMapper} */ private static ObjectMapper initMapper() { ObjectMapper mapper = new ObjectMapper(); // to enable standard indentation ("pretty-printing"): mapper.enable(SerializationFeature.INDENT_OUTPUT); // to allow serialization of "empty" POJOs (no properties to serialize) // (without this setting, an exception is thrown in those cases) mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); // set writer flush after writer value mapper.enable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // ObjectMapper will call close() and root values that implement // java.io.Closeable; // including cases where exception is thrown and serialization does not // completely succeed. mapper.enable(SerializationFeature.CLOSE_CLOSEABLE); // to write java.util.Date, Calendar as number (timestamp): mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // disable default date to timestamp mapper.disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS); // DeserializationFeature for changing how JSON is read as POJOs: // to prevent exception when encountering unknown property: mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // disable default date to timestamp mapper.disable(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS); // to allow coercion of JSON empty String ("") to null Object value: mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS"); // Set Default date fromat mapper.setDateFormat(df); return mapper; }
From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java
private static void mapConsumedObjects(APIMethodModel methodModel, Parameter parameters[]) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); for (Parameter parameter : parameters) { //deterimine if this is "Body" object List<Annotation> paramAnnotation = new ArrayList<>(); paramAnnotation.add(parameter.getAnnotation(QueryParam.class)); paramAnnotation.add(parameter.getAnnotation(FormParam.class)); paramAnnotation.add(parameter.getAnnotation(MatrixParam.class)); paramAnnotation.add(parameter.getAnnotation(HeaderParam.class)); paramAnnotation.add(parameter.getAnnotation(CookieParam.class)); paramAnnotation.add(parameter.getAnnotation(PathParam.class)); paramAnnotation.add(parameter.getAnnotation(BeanParam.class)); boolean consumeObject = true; for (Annotation annotation : paramAnnotation) { if (annotation != null) { consumeObject = false;//from w ww . ja va2 s .c om break; } } if (consumeObject) { APIValueModel valueModel = new APIValueModel(); try { valueModel.setValueObjectName(parameter.getType().getSimpleName()); DataType dataType = (DataType) parameter.getAnnotation(DataType.class); if (dataType != null) { String typeName = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeName = dataType.actualClassName(); } valueModel.setTypeObjectName(typeName); try { valueModel .setTypeObject(objectMapper.writeValueAsString(dataType.value().newInstance())); Set<String> fieldList = mapValueField(valueModel.getTypeFields(), ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0]), true); String cleanUpJson = StringProcessor.stripeFieldJSON(valueModel.getTypeObject(), fieldList); valueModel.setTypeObject(cleanUpJson); mapComplexTypes(valueModel.getAllComplexTypes(), ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0]), true); APIDescription aPIDescription = (APIDescription) dataType.value() .getAnnotation(APIDescription.class); if (aPIDescription != null) { valueModel.setTypeDescription(aPIDescription.value()); } } catch (InstantiationException iex) { log.log(Level.WARNING, MessageFormat.format( "Unable to instantiated type: {0} make sure the type is not abstract.", parameter.getType())); } } else { try { valueModel.setValueObject( objectMapper.writeValueAsString(parameter.getType().newInstance())); Set<String> fieldList = mapValueField(valueModel.getValueFields(), ReflectionUtil.getAllFields(parameter.getType()).toArray(new Field[0]), true); String cleanUpJson = StringProcessor.stripeFieldJSON(valueModel.getValueObject(), fieldList); valueModel.setValueObject(cleanUpJson); mapComplexTypes(valueModel.getAllComplexTypes(), ReflectionUtil.getAllFields(parameter.getType()).toArray(new Field[0]), true); APIDescription aPIDescription = (APIDescription) parameter.getType() .getAnnotation(APIDescription.class); if (aPIDescription != null) { valueModel.setTypeDescription(aPIDescription.value()); } } catch (InstantiationException iex) { log.log(Level.WARNING, MessageFormat.format( "Unable to instantiated type: {0} make sure the type is not abstract.", parameter.getType())); } } } catch (IllegalAccessException | JsonProcessingException ex) { log.log(Level.WARNING, null, ex); } //There can only be one consume(Request Body Parameter) object //We take the first one and ignore the rest. methodModel.setConsumeObject(valueModel); break; } } }
From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java
public static APIResourceModel processRestClass(Class resource, String rootPath) { APIResourceModel resourceModel = new APIResourceModel(); resourceModel.setClassName(resource.getName()); resourceModel.setResourceName(/* w w w . j a v a 2 s.co m*/ String.join(" ", StringUtils.splitByCharacterTypeCamelCase(resource.getSimpleName()))); APIDescription aPIDescription = (APIDescription) resource.getAnnotation(APIDescription.class); if (aPIDescription != null) { resourceModel.setResourceDescription(aPIDescription.value()); } Path path = (Path) resource.getAnnotation(Path.class); if (path != null) { resourceModel.setResourcePath(rootPath + "/" + path.value()); } RequireAdmin requireAdmin = (RequireAdmin) resource.getAnnotation(RequireAdmin.class); if (requireAdmin != null) { resourceModel.setRequireAdmin(true); } //class parameters mapParameters(resourceModel.getResourceParams(), resource.getDeclaredFields()); //methods ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); int methodId = 0; for (Method method : resource.getDeclaredMethods()) { APIMethodModel methodModel = new APIMethodModel(); methodModel.setId(methodId++); //rest method List<String> restMethods = new ArrayList<>(); GET getMethod = (GET) method.getAnnotation(GET.class); POST postMethod = (POST) method.getAnnotation(POST.class); PUT putMethod = (PUT) method.getAnnotation(PUT.class); DELETE deleteMethod = (DELETE) method.getAnnotation(DELETE.class); if (getMethod != null) { restMethods.add("GET"); } if (postMethod != null) { restMethods.add("POST"); } if (putMethod != null) { restMethods.add("PUT"); } if (deleteMethod != null) { restMethods.add("DELETE"); } methodModel.setRestMethod(String.join(",", restMethods)); if (restMethods.isEmpty()) { //skip non-rest methods continue; } //produces Produces produces = (Produces) method.getAnnotation(Produces.class); if (produces != null) { methodModel.setProducesTypes(String.join(",", produces.value())); } //consumes Consumes consumes = (Consumes) method.getAnnotation(Consumes.class); if (consumes != null) { methodModel.setConsumesTypes(String.join(",", consumes.value())); } aPIDescription = (APIDescription) method.getAnnotation(APIDescription.class); if (aPIDescription != null) { methodModel.setDescription(aPIDescription.value()); } path = (Path) method.getAnnotation(Path.class); if (path != null) { methodModel.setMethodPath(path.value()); } requireAdmin = (RequireAdmin) method.getAnnotation(RequireAdmin.class); if (requireAdmin != null) { methodModel.setRequireAdmin(true); } try { if (!(method.getReturnType().getSimpleName().equalsIgnoreCase(Void.class.getSimpleName()))) { APIValueModel valueModel = new APIValueModel(); DataType dataType = (DataType) method.getAnnotation(DataType.class); boolean addResponseObject = true; if ("javax.ws.rs.core.Response".equals(method.getReturnType().getName()) && dataType == null) { addResponseObject = false; } if (addResponseObject) { valueModel.setValueObjectName(method.getReturnType().getSimpleName()); ReturnType returnType = (ReturnType) method.getAnnotation(ReturnType.class); Class returnTypeClass; if (returnType != null) { returnTypeClass = returnType.value(); } else { returnTypeClass = method.getReturnType(); } if (!"javax.ws.rs.core.Response".equals(method.getReturnType().getName())) { if (ReflectionUtil.isCollectionClass(method.getReturnType()) == false) { try { valueModel.setValueObject( objectMapper.writeValueAsString(returnTypeClass.newInstance())); mapValueField(valueModel.getValueFields(), ReflectionUtil.getAllFields(returnTypeClass).toArray(new Field[0])); mapComplexTypes(valueModel.getAllComplexTypes(), ReflectionUtil.getAllFields(returnTypeClass).toArray(new Field[0]), false); aPIDescription = (APIDescription) returnTypeClass .getAnnotation(APIDescription.class); if (aPIDescription != null) { valueModel.setValueDescription(aPIDescription.value()); } } catch (InstantiationException iex) { log.log(Level.WARNING, MessageFormat.format( "Unable to instantiated type: {0} make sure the type is not abstract.", returnTypeClass)); } } } if (dataType != null) { String typeName = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeName = dataType.actualClassName(); } valueModel.setTypeObjectName(typeName); try { valueModel.setTypeObject( objectMapper.writeValueAsString(dataType.value().newInstance())); mapValueField(valueModel.getTypeFields(), ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0])); mapComplexTypes(valueModel.getAllComplexTypes(), ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0]), false); aPIDescription = (APIDescription) dataType.value() .getAnnotation(APIDescription.class); if (aPIDescription != null) { valueModel.setTypeDescription(aPIDescription.value()); } } catch (InstantiationException iex) { log.log(Level.WARNING, MessageFormat.format( "Unable to instantiated type: {0} make sure the type is not abstract.", dataType.value())); } } methodModel.setResponseObject(valueModel); } } } catch (IllegalAccessException | JsonProcessingException ex) { log.log(Level.WARNING, null, ex); } //method parameters mapMethodParameters(methodModel.getMethodParams(), method.getParameters()); //Handle Consumed Objects mapConsumedObjects(methodModel, method.getParameters()); resourceModel.getMethods().add(methodModel); } Collections.sort(resourceModel.getMethods(), new ApiMethodComparator<>()); return resourceModel; }
From source file:com.helger.wsdlgen.exchange.InterfaceReader.java
@Nonnull private static ObjectMapper _createJSONFactory() { final ObjectMapper aObjectMapper = new ObjectMapper(); // Necessary configuration to allow control characters inside of JSON // strings (like newline etc.) aObjectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); // Feature that determines whether parser will allow use of unquoted field // names (which is allowed by Javascript, but not by JSON specification). aObjectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); // Always use BigDecimal aObjectMapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS); // As of 2.1.4 BigDecimals are compacted by default - with this method // everything stays as it was aObjectMapper.setNodeFactory(JsonNodeFactory.withExactBigDecimals(true)); return aObjectMapper; }