com.fasterxml.jackson.databind.util.ClassUtil Java Examples
The following examples show how to use
com.fasterxml.jackson.databind.util.ClassUtil.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TypeFactory.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Method for constructing a {@link CollectionType}. *<p> * NOTE: type modifiers are NOT called on Collection type itself; but are called * for contained types. */ public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, JavaType elementType) { TypeBindings bindings = TypeBindings.createIfNeeded(collectionClass, elementType); CollectionType result = (CollectionType) _fromClass(null, collectionClass, bindings); // 17-May-2017, tatu: As per [databind#1415], we better verify bound values if (but only if) // type being resolved was non-generic (i.e.element type was ignored) if (bindings.isEmpty() && (elementType != null)) { JavaType t = result.findSuperType(Collection.class); JavaType realET = t.getContentType(); if (!realET.equals(elementType)) { throw new IllegalArgumentException(String.format( "Non-generic Collection class %s did not resolve to something with element type %s but %s ", ClassUtil.nameOf(collectionClass), elementType, realET)); } } return result; }
Example #2
Source File: ObjectMapper.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Helper method used when value to serialize is {@link Closeable} and its <code>close()</code> * method is to be called right after serialization has been called */ private final void _writeCloseableValue(JsonGenerator g, Object value, SerializationConfig cfg) throws IOException { Closeable toClose = (Closeable) value; try { _serializerProvider(cfg).serializeValue(g, value); if (cfg.isEnabled(SerializationFeature.FLUSH_AFTER_WRITE_VALUE)) { g.flush(); } } catch (Exception e) { ClassUtil.closeOnFailAndThrowAsIOE(null, toClose, e); return; } toClose.close(); }
Example #3
Source File: BeanDeserializerFactory.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Method used by module registration functionality, to construct a new bean * deserializer factory * with different configuration settings. */ @Override public DeserializerFactory withConfig(DeserializerFactoryConfig config) { if (_factoryConfig == config) { return this; } /* 22-Nov-2010, tatu: Handling of subtypes is tricky if we do immutable-with-copy-ctor; * and we pretty much have to here either choose between losing subtype instance * when registering additional deserializers, or losing deserializers. * Instead, let's actually just throw an error if this method is called when subtype * has not properly overridden this method; this to indicate problem as soon as possible. */ ClassUtil.verifyMustOverride(BeanDeserializerFactory.class, this, "withConfig"); return new BeanDeserializerFactory(config); }
Example #4
Source File: JaxbAnnotationIntrospector.java From jackson-modules-base with Apache License 2.0 | 6 votes |
/** * @param ignoreXmlIDREF Whether {@link XmlIDREF} annotation should be processed * JAXB style (meaning that references are always serialized using id), or * not (first reference as full POJO, others as ids) */ public JaxbAnnotationIntrospector(boolean ignoreXmlIDREF) { _ignoreXmlIDREF = ignoreXmlIDREF; _jaxbPackageName = XmlElement.class.getPackage().getName(); JsonSerializer<?> dataHandlerSerializer = null; JsonDeserializer<?> dataHandlerDeserializer = null; // Data handlers included dynamically, to try to prevent issues on platforms // with less than complete support for JAXB API try { dataHandlerSerializer = ClassUtil.createInstance(DataHandlerJsonSerializer.class, false); dataHandlerDeserializer = ClassUtil.createInstance(DataHandlerJsonDeserializer.class, false); } catch (Throwable e) { //dataHandlers not supported... } _dataHandlerSerializer = dataHandlerSerializer; _dataHandlerDeserializer = dataHandlerDeserializer; }
Example #5
Source File: AnnotatedMethodCollector.java From lams with GNU General Public License v2.0 | 6 votes |
protected void _addMethodMixIns(TypeResolutionContext tc, Class<?> targetClass, Map<MemberKey,MethodBuilder> methods, Class<?> mixInCls) { if (_intr == null) { return; } for (Class<?> mixin : ClassUtil.findRawSuperTypes(mixInCls, targetClass, true)) { for (Method m : ClassUtil.getDeclaredMethods(mixin)) { if (!_isIncludableMemberMethod(m)) { continue; } final MemberKey key = new MemberKey(m); MethodBuilder b = methods.get(key); Annotation[] anns = m.getDeclaredAnnotations(); if (b == null) { // nothing yet; add but do NOT specify method -- this marks it // as "mix-over", floating mix-in methods.put(key, new MethodBuilder(tc, null, collectAnnotations(anns))); } else { b.annotations = collectDefaultAnnotations(b.annotations, anns); } } } }
Example #6
Source File: ObjectWriter.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Helper method used when value to serialize is {@link Closeable} and its <code>close()</code> * method is to be called right after serialization has been called */ private final void _writeCloseable(JsonGenerator gen, Object value) throws IOException { Closeable toClose = (Closeable) value; try { _prefetch.serialize(gen, value, _serializerProvider()); Closeable tmpToClose = toClose; toClose = null; tmpToClose.close(); } catch (Exception e) { ClassUtil.closeOnFailAndThrowAsIOE(gen, toClose, e); return; } gen.close(); }
Example #7
Source File: AnnotatedClassResolver.java From lams with GNU General Public License v2.0 | 6 votes |
private AnnotationCollector _addClassMixIns(AnnotationCollector annotations, Class<?> target, Class<?> mixin) { if (mixin != null) { // Ok, first: annotations from mix-in class itself: annotations = _addAnnotationsIfNotPresent(annotations, ClassUtil.findClassAnnotations(mixin)); // And then from its supertypes, if any. But note that we will only consider // super-types up until reaching the masked class (if found); this because // often mix-in class is a sub-class (for convenience reasons). // And if so, we absolutely must NOT include super types of masked class, // as that would inverse precedence of annotations. for (Class<?> parent : ClassUtil.findSuperClasses(mixin, target, false)) { annotations = _addAnnotationsIfNotPresent(annotations, ClassUtil.findClassAnnotations(parent)); } } return annotations; }
Example #8
Source File: InnerClassProperty.java From lams with GNU General Public License v2.0 | 6 votes |
@Override public void deserializeAndSet(JsonParser p, DeserializationContext ctxt, Object bean) throws IOException { JsonToken t = p.getCurrentToken(); Object value; if (t == JsonToken.VALUE_NULL) { value = _valueDeserializer.getNullValue(ctxt); } else if (_valueTypeDeserializer != null) { value = _valueDeserializer.deserializeWithType(p, ctxt, _valueTypeDeserializer); } else { // the usual case try { value = _creator.newInstance(bean); } catch (Exception e) { ClassUtil.unwrapAndThrowAsIAE(e, String.format( "Failed to instantiate class %s, problem: %s", _creator.getDeclaringClass().getName(), e.getMessage())); value = null; } _valueDeserializer.deserialize(p, ctxt, value); } set(bean, value); }
Example #9
Source File: StdSerializer.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Method that will modify caught exception (passed in as argument) * as necessary to include reference information, and to ensure it * is a subtype of {@link IOException}, or an unchecked exception. *<p> * Rules for wrapping and unwrapping are bit complicated; essentially: *<ul> * <li>Errors are to be passed as is (if uncovered via unwrapping) * <li>"Plain" IOExceptions (ones that are not of type * {@link JsonMappingException} are to be passed as is *</ul> */ public void wrapAndThrow(SerializerProvider provider, Throwable t, Object bean, String fieldName) throws IOException { /* 05-Mar-2009, tatu: But one nasty edge is when we get * StackOverflow: usually due to infinite loop. But that * usually gets hidden within an InvocationTargetException... */ while (t instanceof InvocationTargetException && t.getCause() != null) { t = t.getCause(); } // Errors and "plain" to be passed as is ClassUtil.throwIfError(t); // Ditto for IOExceptions... except for mapping exceptions! boolean wrap = (provider == null) || provider.isEnabled(SerializationFeature.WRAP_EXCEPTIONS); if (t instanceof IOException) { if (!wrap || !(t instanceof JsonMappingException)) { throw (IOException) t; } } else if (!wrap) { ClassUtil.throwIfRTE(t); } // Need to add reference information throw JsonMappingException.wrapWithPath(t, bean, fieldName); }
Example #10
Source File: StdDeserializer.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Helper called to support {@link DeserializationFeature#UNWRAP_SINGLE_VALUE_ARRAYS}: * default implementation simply calls * {@link #deserialize(JsonParser, DeserializationContext)}, * but handling may be overridden. * * @since 2.9 */ protected T _deserializeWrappedValue(JsonParser p, DeserializationContext ctxt) throws IOException { // 23-Mar-2017, tatu: Let's specifically block recursive resolution to avoid // either supporting nested arrays, or to cause infinite looping. if (p.hasToken(JsonToken.START_ARRAY)) { String msg = String.format( "Cannot deserialize instance of %s out of %s token: nested Arrays not allowed with %s", ClassUtil.nameOf(_valueClass), JsonToken.START_ARRAY, "DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS"); @SuppressWarnings("unchecked") T result = (T) ctxt.handleUnexpectedToken(_valueClass, p.getCurrentToken(), p, msg); return result; } return (T) deserialize(p, ctxt); }
Example #11
Source File: CollectorBase.java From lams with GNU General Public License v2.0 | 6 votes |
protected final AnnotationCollector collectDefaultFromBundle(AnnotationCollector c, Annotation bundle) { Annotation[] anns = ClassUtil.findClassAnnotations(bundle.annotationType()); for (int i = 0, end = anns.length; i < end; ++i) { Annotation ann = anns[i]; // minor optimization: by-pass 2 common JDK meta-annotations if (_ignorableAnnotation(ann)) { continue; } // also only defaulting, not overrides: if (!c.isPresent(ann)) { c = c.addOrOverride(ann); if (_intr.isAnnotationBundle(ann)) { c = collectFromBundle(c, ann); } } } return c; }
Example #12
Source File: JaxbAnnotationIntrospector.java From jackson-modules-base with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") private XmlAdapter<Object,Object> findAdapterForClass(AnnotatedClass ac, boolean forSerialization) { /* As per [JACKSON-411], XmlJavaTypeAdapter should not be inherited from super-class. * It would still be nice to be able to use mix-ins; but unfortunately we seem to lose * knowledge of class that actually declared the annotation. Thus, we'll only accept * declaration from specific class itself. */ XmlJavaTypeAdapter adapterInfo = ac.getAnnotated().getAnnotation(XmlJavaTypeAdapter.class); if (adapterInfo != null) { // should we try caching this? @SuppressWarnings("rawtypes") Class<? extends XmlAdapter> cls = adapterInfo.value(); // true -> yes, force access if need be return ClassUtil.createInstance(cls, true); } return null; }
Example #13
Source File: BeanDeserializerFactory.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Helper method used to skip processing for types that we know * cannot be (i.e. are never consider to be) beans: * things like primitives, Arrays, Enums, and proxy types. *<p> * Note that usually we shouldn't really be getting these sort of * types anyway; but better safe than sorry. */ protected boolean isPotentialBeanType(Class<?> type) { String typeStr = ClassUtil.canBeABeanType(type); if (typeStr != null) { throw new IllegalArgumentException("Cannot deserialize Class "+type.getName()+" (of type "+typeStr+") as a Bean"); } if (ClassUtil.isProxyType(type)) { throw new IllegalArgumentException("Cannot deserialize Proxy class "+type.getName()+" as a Bean"); } /* also: can't deserialize some local classes: static are ok; in-method not; * other non-static inner classes are ok */ typeStr = ClassUtil.isLocalType(type, true); if (typeStr != null) { throw new IllegalArgumentException("Cannot deserialize Class "+type.getName()+" (of type "+typeStr+") as a Bean"); } return true; }
Example #14
Source File: ContainerDeserializerBase.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Helper method called by various Map(-like) deserializers. */ protected <BOGUS> BOGUS wrapAndThrow(Throwable t, Object ref, String key) throws IOException { // to handle StackOverflow: while (t instanceof InvocationTargetException && t.getCause() != null) { t = t.getCause(); } // Errors and "plain" IOExceptions to be passed as is ClassUtil.throwIfError(t); // ... except for mapping exceptions if (t instanceof IOException && !(t instanceof JsonMappingException)) { throw (IOException) t; } // for [databind#1141] throw JsonMappingException.wrapWithPath(t, ref, ClassUtil.nonNull(key, "N/A")); }
Example #15
Source File: FactoryBasedEnumDeserializer.java From lams with GNU General Public License v2.0 | 6 votes |
private Throwable throwOrReturnThrowable(Throwable t, DeserializationContext ctxt) throws IOException { t = ClassUtil.getRootCause(t); // Errors to be passed as is ClassUtil.throwIfError(t); boolean wrap = (ctxt == null) || ctxt.isEnabled(DeserializationFeature.WRAP_EXCEPTIONS); // Ditto for IOExceptions; except we may want to wrap JSON exceptions if (t instanceof IOException) { if (!wrap || !(t instanceof JsonProcessingException)) { throw (IOException) t; } } else if (!wrap) { ClassUtil.throwIfRTE(t); } return t; }
Example #16
Source File: ObjectReader.java From lams with GNU General Public License v2.0 | 6 votes |
/** * @since 2.9 */ protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, JavaType bindType) throws IOException { JsonToken t = p.nextToken(); if (t != null) { Class<?> bt = ClassUtil.rawClass(bindType); if (bt == null) { if (_valueToUpdate != null) { bt = _valueToUpdate.getClass(); } } ctxt.reportTrailingTokens(bt, p, t); } }
Example #17
Source File: TypeFactory.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Method for constructing a {@link MapType} instance *<p> * NOTE: type modifiers are NOT called on constructed type itself; but are called * for contained types. */ public MapType constructMapType(Class<? extends Map> mapClass, JavaType keyType, JavaType valueType) { TypeBindings bindings = TypeBindings.createIfNeeded(mapClass, new JavaType[] { keyType, valueType }); MapType result = (MapType) _fromClass(null, mapClass, bindings); // 17-May-2017, tatu: As per [databind#1415], we better verify bound values if (but only if) // type being resolved was non-generic (i.e.element type was ignored) if (bindings.isEmpty()) { JavaType t = result.findSuperType(Map.class); JavaType realKT = t.getKeyType(); if (!realKT.equals(keyType)) { throw new IllegalArgumentException(String.format( "Non-generic Map class %s did not resolve to something with key type %s but %s ", ClassUtil.nameOf(mapClass), keyType, realKT)); } JavaType realVT = t.getContentType(); if (!realVT.equals(valueType)) { throw new IllegalArgumentException(String.format( "Non-generic Map class %s did not resolve to something with value type %s but %s ", ClassUtil.nameOf(mapClass), valueType, realVT)); } } return result; }
Example #18
Source File: TypeBindings.java From lams with GNU General Public License v2.0 | 6 votes |
@Override public boolean equals(Object o) { if (o == this) return true; if (!ClassUtil.hasClass(o, getClass())) { return false; } TypeBindings other = (TypeBindings) o; int len = _types.length; if (len != other.size()) { return false; } JavaType[] otherTypes = other._types; for (int i = 0; i < len; ++i) { if (!otherTypes[i].equals(_types[i])) { return false; } } return true; }
Example #19
Source File: InjectableValues.java From lams with GNU General Public License v2.0 | 6 votes |
@Override public Object findInjectableValue(Object valueId, DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance) throws JsonMappingException { if (!(valueId instanceof String)) { ctxt.reportBadDefinition(ClassUtil.classOf(valueId), String.format( "Unrecognized inject value id type (%s), expecting String", ClassUtil.classNameOf(valueId))); } String key = (String) valueId; Object ob = _values.get(key); if (ob == null && !_values.containsKey(key)) { throw new IllegalArgumentException("No injectable id with value '"+key+"' found (for property '"+forProperty.getName()+"')"); } return ob; }
Example #20
Source File: CollectorBase.java From lams with GNU General Public License v2.0 | 6 votes |
protected final AnnotationCollector collectFromBundle(AnnotationCollector c, Annotation bundle) { Annotation[] anns = ClassUtil.findClassAnnotations(bundle.annotationType()); for (int i = 0, end = anns.length; i < end; ++i) { Annotation ann = anns[i]; // minor optimization: by-pass 2 common JDK meta-annotations if (_ignorableAnnotation(ann)) { continue; } if (_intr.isAnnotationBundle(ann)) { // 11-Apr-2017, tatu: Also must guard against recursive definitions... if (!c.isPresent(ann)) { c = c.addOrOverride(ann); c = collectFromBundle(c, ann); } } else { c = c.addOrOverride(ann); } } return c; }
Example #21
Source File: SerializerProvider.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Helper method called to indicate problem in POJO (serialization) definitions or settings * regarding specific property (of a type), unrelated to actual JSON content to map. * Default behavior is to construct and throw a {@link JsonMappingException}. * * @since 2.9 */ public <T> T reportBadPropertyDefinition(BeanDescription bean, BeanPropertyDefinition prop, String message, Object... msgArgs) throws JsonMappingException { message = _format(message, msgArgs); String propName = "N/A"; if (prop != null) { propName = _quotedString(prop.getName()); } String beanDesc = "N/A"; if (bean != null) { beanDesc = ClassUtil.nameOf(bean.getBeanClass()); } message = String.format("Invalid definition for property %s (of type %s): %s", propName, beanDesc, message); throw InvalidDefinitionException.from(getGenerator(), message, bean, prop); }
Example #22
Source File: TypeDeserializerBase.java From lams with GNU General Public License v2.0 | 6 votes |
protected final JsonDeserializer<Object> _findDefaultImplDeserializer(DeserializationContext ctxt) throws IOException { /* 06-Feb-2013, tatu: As per [databind#148], consider default implementation value of * {@link java.lang.Void} to mean "serialize as null"; as well as DeserializationFeature * to do swift mapping to null */ if (_defaultImpl == null) { if (!ctxt.isEnabled(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE)) { return NullifyingDeserializer.instance; } return null; } Class<?> raw = _defaultImpl.getRawClass(); if (ClassUtil.isBogusClass(raw)) { return NullifyingDeserializer.instance; } synchronized (_defaultImpl) { if (_defaultImplDeserializer == null) { _defaultImplDeserializer = ctxt.findContextualValueDeserializer( _defaultImpl, _property); } return _defaultImplDeserializer; } }
Example #23
Source File: ObjectIdInfo.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public String toString() { return "ObjectIdInfo: propName="+_propertyName +", scope="+ClassUtil.nameOf(_scope) +", generatorType="+ClassUtil.nameOf(_generator) +", alwaysAsId="+_alwaysAsId; }
Example #24
Source File: AnnotatedCreatorCollector.java From lams with GNU General Public License v2.0 | 5 votes |
protected AnnotatedConstructor constructDefaultConstructor(ClassUtil.Ctor ctor, ClassUtil.Ctor mixin) { if (_intr == null) { // when annotation processing is disabled return new AnnotatedConstructor(_typeContext, ctor.getConstructor(), _emptyAnnotationMap(), NO_ANNOTATION_MAPS); } return new AnnotatedConstructor(_typeContext, ctor.getConstructor(), collectAnnotations(ctor, mixin), collectAnnotations(ctor.getConstructor().getParameterAnnotations(), (mixin == null) ? null : mixin.getConstructor().getParameterAnnotations())); }
Example #25
Source File: TypeParser.java From lams with GNU General Public License v2.0 | 5 votes |
protected Class<?> findClass(String className, MyTokenizer tokens) { try { return _factory.findClass(className); } catch (Exception e) { ClassUtil.throwIfRTE(e); throw _problem(tokens, "Cannot locate class '"+className+"', problem: "+e.getMessage()); } }
Example #26
Source File: ObjectMapper.java From lams with GNU General Public License v2.0 | 5 votes |
/** * @since 2.9 */ protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, JavaType bindType) throws IOException { JsonToken t = p.nextToken(); if (t != null) { Class<?> bt = ClassUtil.rawClass(bindType); ctxt.reportTrailingTokens(bt, p, t); } }
Example #27
Source File: VirtualAnnotatedMember.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public boolean equals(Object o) { if (o == this) return true; if (!ClassUtil.hasClass(o, getClass())) { return false; } VirtualAnnotatedMember other = (VirtualAnnotatedMember) o; return (other._declaringClass == _declaringClass) && other._name.equals(_name); }
Example #28
Source File: TypeFactory.java From lams with GNU General Public License v2.0 | 5 votes |
protected JavaType _resolveSuperClass(ClassStack context, Class<?> rawType, TypeBindings parentBindings) { Type parent = ClassUtil.getGenericSuperclass(rawType); if (parent == null) { return null; } return _fromAny(context, parent, parentBindings); }
Example #29
Source File: DeserializerCache.java From lams with GNU General Public License v2.0 | 5 votes |
protected JsonDeserializer<Object> _handleUnknownValueDeserializer(DeserializationContext ctxt, JavaType type) throws JsonMappingException { // Let's try to figure out the reason, to give better error messages Class<?> rawClass = type.getRawClass(); if (!ClassUtil.isConcrete(rawClass)) { return ctxt.reportBadDefinition(type, "Cannot find a Value deserializer for abstract type "+type); } return ctxt.reportBadDefinition(type, "Cannot find a Value deserializer for type "+type); }
Example #30
Source File: StdKeyDeserializers.java From lams with GNU General Public License v2.0 | 5 votes |
public static KeyDeserializer findStringBasedKeyDeserializer(DeserializationConfig config, JavaType type) { /* We don't need full deserialization information, just need to * know creators. */ BeanDescription beanDesc = config.introspect(type); // Ok, so: can we find T(String) constructor? Constructor<?> ctor = beanDesc.findSingleArgConstructor(String.class); if (ctor != null) { if (config.canOverrideAccessModifiers()) { ClassUtil.checkAndFixAccess(ctor, config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS)); } return new StdKeyDeserializer.StringCtorKeyDeserializer(ctor); } /* or if not, "static T valueOf(String)" (or equivalent marked * with @JsonCreator annotation?) */ Method m = beanDesc.findFactoryMethod(String.class); if (m != null){ if (config.canOverrideAccessModifiers()) { ClassUtil.checkAndFixAccess(m, config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS)); } return new StdKeyDeserializer.StringFactoryKeyDeserializer(m); } // nope, no such luck... return null; }