Java Code Examples for com.fasterxml.jackson.databind.JavaType#getRawClass()

The following examples show how to use com.fasterxml.jackson.databind.JavaType#getRawClass() . 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: GuavaTypeModifier.java    From jackson-datatypes-collections with Apache License 2.0 6 votes vote down vote up
@Override
public JavaType modifyType(JavaType type, Type jdkType, TypeBindings bindings, TypeFactory typeFactory)
{
    if (type.isReferenceType() || type.isContainerType()) {
        return type;
    }

    final Class<?> raw = type.getRawClass();
    // First: make Multimaps look more Map-like
    if (raw == Multimap.class) {
        return MapLikeType.upgradeFrom(type,
                        type.containedTypeOrUnknown(0),
                        type.containedTypeOrUnknown(1));
    }
    if (raw == Optional.class) {
        return ReferenceType.upgradeFrom(type, type.containedTypeOrUnknown(0));
    }
    return type;
}
 
Example 2
Source File: JsonUtility.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
public static Type java2Type(JavaType java) {
    Type type = null;
    if (java.isArrayType()) {
        // 数组类型
        type = java.getRawClass();
    } else if (java.hasGenericTypes()) {
        // 泛型类型
        List<JavaType> javas = java.getBindings().getTypeParameters();
        Type[] generics = new Type[javas.size()];
        int index = 0;
        for (JavaType term : javas) {
            generics[index++] = java2Type(term);
        }
        Class<?> clazz = java.getRawClass();
        type = TypeUtility.parameterize(clazz, generics);
    } else {
        type = java.getRawClass();
    }
    return type;
}
 
Example 3
Source File: TypeFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method similar to {@link #constructSpecializedType}, but that creates a
 * less-specific type of given type. Usually this is as simple as simply
 * finding super-type with type erasure of <code>superClass</code>, but
 * there may be need for some additional work-arounds.
 *
 * @param superClass
 *
 * @since 2.7
 */
public JavaType constructGeneralizedType(JavaType baseType, Class<?> superClass)
{
    // simple optimization to avoid costly introspection if type-erased type does NOT differ
    final Class<?> rawBase = baseType.getRawClass();
    if (rawBase == superClass) {
        return baseType;
    }
    JavaType superType = baseType.findSuperType(superClass);
    if (superType == null) {
        // Most likely, caller did not verify sub/super-type relationship
        if (!superClass.isAssignableFrom(rawBase)) {
            throw new IllegalArgumentException(String.format(
                    "Class %s not a super-type of %s", superClass.getName(), baseType));
        }
        // 01-Nov-2015, tatu: Should never happen, but ch
        throw new IllegalArgumentException(String.format(
                "Internal error: class %s not included as super-type for %s",
                superClass.getName(), baseType));
    }
    return superType;
}
 
Example 4
Source File: MarshallerService.java    From dawnsci with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean useForType(JavaType type) {
	Class<?> clazz = type.getRawClass();
	// Note: This does not work well with generics defined at or above the same scope as the call
	// to marshal or unmarshal. As a result, only use such generics there when dealing with a primitive
	// type or registered class, as these will cope with the idResolver.

	// We can lookup the class in the registry, for marshalling and unmarshalling.
	Boolean registryHasClass = registry.isClass(clazz);

	// We only ever declare as object if we intend to use one of our own classes (or a primitive).
	Boolean isObject = (Object.class.equals(clazz));

	// Also include abstract classes and interfaces as these are always defined with a type id. This
	// is not the case for container types, however, so these are excluded.
	Boolean isAbstract = type.isAbstract();
	Boolean isInterface = type.isInterface();
	Boolean isNotContainer = !type.isContainerType();

	// Primitive types are considered abstract, so exclude these as well.
	Boolean isNotPrimitive = !type.isPrimitive();

	return registryHasClass || ((isObject || isAbstract || isInterface) && isNotContainer && isNotPrimitive);
}
 
Example 5
Source File: ObjectApiBuilder.java    From simple-json-rpc with MIT License 5 votes vote down vote up
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    // Check that it's a JSON-RPC method
    MethodMetadata methodMetadata = classMetadata.getMethods().get(method);
    if (methodMetadata == null) {
        throw new IllegalStateException("Method '" + method.getName() + "' is not JSON-RPC available");
    }

    // Get method name (annotation or the actual name), params and id generator
    String methodName = methodMetadata.getName();
    JsonNode params = getParams(methodMetadata, args, getParamsType(classMetadata, methodMetadata));
    IdGenerator<?> idGenerator = userIdGenerator != null ? userIdGenerator : classMetadata.getIdGenerator();

    //  Construct a request
    ValueNode id = new POJONode(idGenerator.generate());
    String textResponse = execute(request(id, methodName, params));

    // Parse a response
    JsonNode responseNode = mapper.readTree(textResponse);
    JsonNode result = responseNode.get(RESULT);
    JsonNode error = responseNode.get(ERROR);
    if (result != null) {
        JavaType returnType = mapper.getTypeFactory().constructType(method.getGenericReturnType());
        if (returnType.getRawClass() == void.class) {
            return null;
        }
        return mapper.convertValue(result, returnType);
    } else {
        ErrorMessage errorMessage = mapper.treeToValue(error, ErrorMessage.class);
        throw new JsonRpcException(errorMessage);
    }
}
 
Example 6
Source File: AnnotatedFieldCollector.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Map<String,FieldBuilder> _findFields(TypeResolutionContext tc,
        JavaType type, Map<String,FieldBuilder> fields)
{
    // First, a quick test: we only care for regular classes (not interfaces,
    //primitive types etc), except for Object.class. A simple check to rule out
    // other cases is to see if there is a super class or not.
    JavaType parent = type.getSuperClass();
    if (parent == null) {
        return fields;
    }
    final Class<?> cls = type.getRawClass();
    // Let's add super-class' fields first, then ours.
    fields = _findFields(new TypeResolutionContext.Basic(_typeFactory, parent.getBindings()),
            parent, fields);
    for (Field f : ClassUtil.getDeclaredFields(cls)) {
        // static fields not included (transients are at this point, filtered out later)
        if (!_isIncludableField(f)) {
            continue;
        }
        // Ok now: we can (and need) not filter out ignorable fields at this point; partly
        // because mix-ins haven't been added, and partly because logic can be done
        // when determining get/settability of the field.
        if (fields == null) {
            fields = new LinkedHashMap<>();
        }
        FieldBuilder b = new FieldBuilder(tc, f);
        if (_intr != null) {
            b.annotations = collectAnnotations(b.annotations, f.getDeclaredAnnotations());
        }
        fields.put(f.getName(), b);
    }
    // And then... any mix-in overrides?
    if (_mixInResolver != null) {
        Class<?> mixin = _mixInResolver.findMixInClassFor(cls);
        if (mixin != null) {
            _addFieldMixIns(mixin, cls, fields);
        }
    }
    return fields;
}
 
Example 7
Source File: ProtobufModule.java    From curiostack with MIT License 5 votes vote down vote up
@Override
@Nullable
public JsonDeserializer<?> findBeanDeserializer(
    JavaType type, DeserializationConfig config, BeanDescription beanDesc) {
  if (Message.class.isAssignableFrom(type.getRawClass())) {
    return new MessageDeserializer(type.getRawClass());
  }
  return null;
}
 
Example 8
Source File: MappingJackson2JsonViewTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public JsonSerializer<Object> createSerializer(SerializerProvider prov, JavaType type) throws JsonMappingException {
	if (type.getRawClass() == TestBeanSimple.class) {
		return new TestBeanSimpleSerializer();
	}
	else {
		return super.createSerializer(prov, type);
	}
}
 
Example 9
Source File: VavrTypeModifier.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Override
public JavaType modifyType(JavaType type, Type jdkType, TypeBindings bindings, TypeFactory typeFactory)
{
    final Class<?> raw = type.getRawClass();
    if (Seq.class.isAssignableFrom(raw) && CharSeq.class != raw) {
        return CollectionLikeType.upgradeFrom(type, type.containedTypeOrUnknown(0));
    }
    if (Set.class.isAssignableFrom(raw)) {
        return CollectionLikeType.upgradeFrom(type, type.containedTypeOrUnknown(0));
    }
    if (PriorityQueue.class.isAssignableFrom(raw)) {
        return CollectionLikeType.upgradeFrom(type, type.containedTypeOrUnknown(0));
    }
    if (Map.class.isAssignableFrom(raw)) {
        return MapLikeType.upgradeFrom(type, type.containedTypeOrUnknown(0), type.containedTypeOrUnknown(1));
    }
    if (Multimap.class.isAssignableFrom(raw)) {
        return MapLikeType.upgradeFrom(type, type.containedTypeOrUnknown(0), type.containedTypeOrUnknown(1));
    }
    if (Lazy.class.isAssignableFrom(raw)) {
        return ReferenceType.upgradeFrom(type, type.containedTypeOrUnknown(0));
    }
    if (Option.class.isAssignableFrom(raw)) {
        return ReferenceType.upgradeFrom(type, type.containedTypeOrUnknown(0));
    }
    return type;
}
 
Example 10
Source File: MessageWriteSchema.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public MessageWriteSchema(ProtoMapper protoMapper, Message message, JavaType javaType) {
  this.protoMapper = protoMapper;
  this.message = message;
  this.javaType = javaType;
  this.mainPojoCls = (Class<T>) javaType.getRawClass();
}
 
Example 11
Source File: AbstractTypeMaterializer.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
protected boolean _suitableType(JavaType type)
{
    // Future plans may include calling of this method for all kinds of abstract types.
    // So as simple precaution, let's limit kinds of types we will try materialize
    // implementations for.
    if (type.isContainerType() || type.isReferenceType()
            || type.isEnumType() || type.isPrimitive()) {
        return false;
    }
    Class<?> cls = type.getRawClass();
    if ((cls == Number.class)
            // 22-Jun-2016, tatu: As per [#12], avoid these too
            || (cls == Date.class) || (cls == Calendar.class)
            || (cls == CharSequence.class) || (cls == Iterable.class) || (cls == Iterator.class)
            // 06-Feb-2019, tatu: [modules-base#74] and:
            || (cls == java.io.Serializable.class)
    ) {
        return false;
    }

    // Fail on non-public classes, since we can't easily force  access to such
    // classes (unless we tried to generate impl classes in same package)
    if (!Modifier.isPublic(cls.getModifiers())) {
        if (isEnabled(Feature.FAIL_ON_NON_PUBLIC_TYPES)) {
            throw new IllegalArgumentException("Can not materialize implementation of "+cls+" since it is not public ");
        }
        return false;
    }
    return true;
}
 
Example 12
Source File: RequestTypeToIgnoreConverter.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
	if (type.isSchemaProperty()) {
		JavaType javaType = Json.mapper().constructType(type.getType());
		Class<?> cls = javaType.getRawClass();
		if (AbstractRequestBuilder.isRequestTypeToIgnore(cls))
			return null;
	}
	return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null;
}
 
Example 13
Source File: AnnotatedClassResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
AnnotatedClassResolver(MapperConfig<?> config, JavaType type, MixInResolver r) {
    _config = config;
    _type = type;
    _class = type.getRawClass();
    _mixInResolver = r;
    _bindings = type.getBindings();
    _intr = config.isAnnotationProcessingEnabled()
            ? config.getAnnotationIntrospector() : null;
    _primaryMixin = _config.findMixInClassFor(_class);
}
 
Example 14
Source File: AbstractTypeMaterializer.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
/**
 * NOTE: should not be called for generic types.
 */
public Class<?> materializeRawType(MapperConfig<?> config, AnnotatedClass typeDef)
{
    final JavaType type = typeDef.getType();

    Class<?> rawType = type.getRawClass();
    String newName = _defaultPackage+rawType.getName();
    BeanBuilder builder = BeanBuilder.construct(config, type, typeDef);
    byte[] bytecode = builder.implement(isEnabled(Feature.FAIL_ON_UNMATERIALIZED_METHOD)).build(newName);
    return _classLoader.loadAndResolve(newName, bytecode, rawType);
}
 
Example 15
Source File: MappingJackson2JsonViewTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public JsonSerializer<Object> createSerializer(SerializerProvider prov, JavaType type) throws JsonMappingException {
	if (type.getRawClass() == TestBeanSimple.class) {
		return new TestBeanSimpleSerializer();
	}
	else {
		return super.createSerializer(prov, type);
	}
}
 
Example 16
Source File: ReadableObjectId.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public Referring(UnresolvedForwardReference ref, JavaType beanType) {
    _reference = ref;
    _beanType = beanType.getRawClass();
}
 
Example 17
Source File: CyclopsSerializers.java    From cyclops with Apache License 2.0 4 votes vote down vote up
@Override
public JsonSerializer<?> findSerializer(SerializationConfig config, JavaType type, BeanDescription beanDesc) {

  if (Tuple1.class==type.getRawClass()) {
    return new Tuple1Serializer();
  }
  if (Tuple2.class==type.getRawClass()) {
    return new Tuple2Serializer();
  }
  if (Tuple3.class==type.getRawClass()) {
    return new Tuple3Serializer();
  }
  if (Tuple4.class==type.getRawClass()) {
    return new Tuple4Serializer();
  }
  if (Tuple5.class==type.getRawClass()) {
    return new Tuple5Serializer();
  }
  if (Tuple6.class==type.getRawClass()) {
    return new Tuple6Serializer();
  }
  if (Tuple7.class==type.getRawClass()) {
    return new Tuple7Serializer();
  }
  if (Tuple8.class==type.getRawClass()) {
    return new Tuple8Serializer();
  }
  if(PersistentMap.class.isAssignableFrom(type.getRawClass())) {
    return new PersistentMapSerializer();
  }

  if (Either.class.isAssignableFrom(type.getRawClass())) {
    return new Sealed2Serializer();
  }

  if (Sealed2.class.isAssignableFrom(type.getRawClass())) {
    return new Sealed2Serializer();
  }
  if (Sealed3.class.isAssignableFrom(type.getRawClass())) {
    return new Sealed3Serializer();
  }
  if (Sealed4.class.isAssignableFrom(type.getRawClass())) {
    return new Sealed4Serializer();
  }
  if (Sealed5.class.isAssignableFrom(type.getRawClass())) {
    return new Sealed5Serializer();
  }
  return super.findSerializer(config, type, beanDesc);
}
 
Example 18
Source File: SubTypeValidator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public void validateSubType(DeserializationContext ctxt, JavaType type,
        BeanDescription beanDesc) throws JsonMappingException
{
    // There are certain nasty classes that could cause problems, mostly
    // via default typing -- catch them here.
    final Class<?> raw = type.getRawClass();
    String full = raw.getName();

    main_check:
    do {
        if (_cfgIllegalClassNames.contains(full)) {
            break;
        }

        // 18-Dec-2017, tatu: As per [databind#1855], need bit more sophisticated handling
        //    for some Spring framework types
        // 05-Jan-2017, tatu: ... also, only applies to classes, not interfaces
        if (raw.isInterface()) {
            ;
        } else if (full.startsWith(PREFIX_SPRING)) {
            for (Class<?> cls = raw; (cls != null) && (cls != Object.class); cls = cls.getSuperclass()){
                String name = cls.getSimpleName();
                // looking for "AbstractBeanFactoryPointcutAdvisor" but no point to allow any is there?
                if ("AbstractPointcutAdvisor".equals(name)
                        // ditto  for "FileSystemXmlApplicationContext": block all ApplicationContexts
                        || "AbstractApplicationContext".equals(name)) {
                    break main_check;
                }
            }
        } else if (full.startsWith(PREFIX_C3P0)) {
            // [databind#1737]; more 3rd party
            // s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource");
            // s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource");
            // [databind#1931]; more 3rd party
            // com.mchange.v2.c3p0.ComboPooledDataSource
            // com.mchange.v2.c3p0.debug.AfterCloseLoggingComboPooledDataSource 
            if (full.endsWith("DataSource")) {
                break main_check;
            }
        }
        return;
    } while (false);

    ctxt.reportBadTypeDefinition(beanDesc,
            "Illegal type (%s) to deserialize: prevented for security reasons", full);
}
 
Example 19
Source File: ServerModelResolver.java    From proteus with Apache License 2.0 4 votes vote down vote up
@Override
public Schema resolve(AnnotatedType annotatedType, ModelConverterContext context, Iterator<ModelConverter> next)
{
    JavaType classType = TypeFactory.defaultInstance().constructType(annotatedType.getType());
    Class<?> rawClass = classType.getRawClass();
    JavaType resolvedType = classType;

    if ((rawClass != null) &&!resolvedType.isPrimitive())
    {
        if (rawClass.isAssignableFrom(ServerResponse.class))
        {
            resolvedType = classType.containedType(0);
        }
        else if (rawClass.isAssignableFrom(CompletableFuture.class))
        {
            Class<?> futureCls = classType.containedType(0).getRawClass();

            if (futureCls.isAssignableFrom(ServerResponse.class))
            {
                final JavaType futureType = TypeFactory.defaultInstance().constructType(classType.containedType(0));

                resolvedType = futureType.containedType(0);
            }
            else
            {
                resolvedType = classType.containedType(0);
            }
        }

        if (resolvedType != null)
        {
            if (resolvedType.getTypeName().contains("java.lang.Void"))
            {
                resolvedType = TypeFactory.defaultInstance().constructFromCanonical(Void.class.getName());
            }
            else if (resolvedType.getTypeName().contains("Optional"))
            {
                if (resolvedType.getTypeName().contains("java.nio.file.Path"))
                {
                    resolvedType = TypeFactory.defaultInstance().constructParametricType(Optional.class, File.class);
                }

                if (resolvedType.getTypeName().contains("ByteBuffer"))
                {
                    resolvedType = TypeFactory.defaultInstance().constructParametricType(Optional.class, File.class);
                }
            }
            else
            {
                if (resolvedType.getTypeName().contains("java.nio.file.Path"))
                {
                    resolvedType = TypeFactory.defaultInstance().constructFromCanonical(File.class.getName());
                }

                if (resolvedType.getTypeName().contains("ByteBuffer"))
                {
                    resolvedType = TypeFactory.defaultInstance().constructFromCanonical(File.class.getName());
                }
            }

            annotatedType.setType(resolvedType);

        }
    }

    try {

        return super.resolve(annotatedType, context, next);

    } catch (Exception e) {

        log.error("Error processing " + annotatedType + " " + classType + " " + annotatedType.getName(), e);

        return null;
    }
}
 
Example 20
Source File: PolymorphicModelConverter.java    From springdoc-openapi with Apache License 2.0 2 votes vote down vote up
/**
 * Is concrete class boolean.
 *
 * @param type the type
 * @return the boolean
 */
private boolean isConcreteClass(AnnotatedType type) {
	JavaType javaType = Json.mapper().constructType(type.getType());
	Class<?> clazz = javaType.getRawClass();
	return !Modifier.isAbstract(clazz.getModifiers()) && !clazz.isInterface();
}