Java 类javax.persistence.AttributeConverter 实例源码

项目:lams    文件:LiteralNode.java   
@Override
public void setExpectedType(Type expectedType) {
    if ( this.expectedType != null ) {
        return;
    }

    if ( AttributeConverterTypeAdapter.class.isInstance( expectedType ) ) {
        final AttributeConverterTypeAdapter adapterType = (AttributeConverterTypeAdapter) expectedType;
        if ( getDataType().getReturnedClass().equals( adapterType.getModelType() ) ) {
            // apply the converter
            final AttributeConverter converter = ( (AttributeConverterTypeAdapter) expectedType ).getAttributeConverter();
            final Object converted = converter.convertToDatabaseColumn( getLiteralValue() );
            if ( isCharacterData( adapterType.sqlType() ) ) {
                setText( "'" + converted.toString() + "'" );
            }
            else {
                setText( converted.toString() );
            }
        }
        this.expectedType = expectedType;
    }
}
项目:warpdb    文件:AccessibleProperty.java   
@SuppressWarnings("unchecked")
private AttributeConverter<Object, Object> getConverter(AccessibleObject accessible) {
    Convert converter = accessible.getAnnotation(Convert.class);
    if (converter != null) {
        Class<?> converterClass = converter.converter();
        if (!AttributeConverter.class.isAssignableFrom(converterClass)) {
            throw new RuntimeException(
                    "Converter class must be AttributeConverter rather than " + converterClass.getName());
        }
        try {
            Constructor<?> cs = converterClass.getDeclaredConstructor();
            cs.setAccessible(true);
            return (AttributeConverter<Object, Object>) cs.newInstance();
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException
                | InvocationTargetException e) {
            throw new RuntimeException("Cannot instantiate Converter: " + converterClass.getName(), e);
        }
    }
    return null;
}
项目:warpdb    文件:AccessibleProperty.java   
private static Class<?> getConverterType(AttributeConverter<Object, Object> converter) {
    if (converter != null) {
        List<Type> types = ClassUtils.getGenericInterfacesIncludeHierarchy(converter.getClass());
        for (Type type : types) {
            if (type instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) type;
                if (pt.getRawType() == AttributeConverter.class) {
                    Type dbType = pt.getActualTypeArguments()[1];
                    if (dbType instanceof Class) {
                        return (Class<?>) dbType;
                    }
                }
            }

        }
    }
    return null;
}
项目:warpdb    文件:Where.java   
Where<T> append(String type, String clause, Object... params) {
    // check clause:
    Mapper<T> mapper = this.criteria.mapper;
    CompiledClause cc = CompiledClause.compile(mapper, clause);
    if (cc.converters.length != params.length) {
        throw new IllegalArgumentException("Arguments not match the placeholder.");
    }
    // convert params:
    int n = 0;
    for (AttributeConverter<Object, Object> converter : cc.converters) {
        if (converter != null) {
            params[n] = converter.convertToDatabaseColumn(params[n]);
        }
        n++;
    }
    // add:
    if (type != null) {
        this.criteria.where.add(type);
    }
    this.criteria.where.add(cc.clause);
    for (Object param : params) {
        this.criteria.whereParams.add(param);
    }
    return this;
}
项目:jeddict    文件:DBEntityMappings.java   
private void createConverterClass(Converter convert, ClassLoader classLoader) {
        //create Java Class
        Class<?> attributeConverter = new ByteBuddy()
//                .subclass(TypeDescription.Generic.Builder.parameterizedType(AttributeConverter.class, String.class, Integer.class).build())
                .subclass(AttributeConverter.class)
                .name(convert.getClazz())
                .annotateType(AnnotationDescription.Builder.ofType(javax.persistence.Converter.class).build())
                .make()
                .load(classLoader, ClassLoadingStrategy.Default.INJECTION)
                .getLoaded();

        //create MetadataClass
        MetadataClass metadataClass = new MetadataClass(getMetadataFactory(), convert.getClazz());
        metadataClass.addInterface(AttributeConverter.class.getName());
        metadataClass.addGenericType("");
        metadataClass.addGenericType("");
        metadataClass.addGenericType(convert.getAttributeType());
        metadataClass.addGenericType("");
        metadataClass.addGenericType(convert.getFieldType());
        getMetadataFactory().addMetadataClass(metadataClass);

    }
项目:lams    文件:Configuration.java   
private AttributeConverter instantiateAttributeConverter(Class<? extends AttributeConverter> attributeConverterClass) {
    AttributeConverter attributeConverter;
    try {
        attributeConverter = attributeConverterClass.newInstance();
    }
    catch (Exception e) {
        throw new AnnotationException(
                "Unable to instantiate AttributeConverter [" + attributeConverterClass.getName() + "]",
                e
        );
    }
    return attributeConverter;
}
项目:lams    文件:Configuration.java   
/**
 * Adds the AttributeConverter instance to this Configuration.  This form is mainly intended for developers
 * to programatically add their own AttributeConverter instance.  HEM, instead, uses the
 * {@link #addAttributeConverter(Class, boolean)} form
 *
 * @param attributeConverter The AttributeConverter instance.
 */
public void addAttributeConverter(AttributeConverter attributeConverter) {
    boolean autoApply = false;
    Converter converterAnnotation = attributeConverter.getClass().getAnnotation( Converter.class );
    if ( converterAnnotation != null ) {
        autoApply = converterAnnotation.autoApply();
    }

    addAttributeConverter( new AttributeConverterDefinition( attributeConverter, autoApply ) );
}
项目:lams    文件:AttributeConversionInfo.java   
public AttributeConversionInfo(
        Class<? extends AttributeConverter> converterClass,
        boolean conversionDisabled,
        String attributeName,
        XAnnotatedElement source) {
    this.converterClass = converterClass;
    this.conversionDisabled = conversionDisabled;
    this.attributeName = attributeName;
    this.source = source;
}
项目:lams    文件:AttributeConverterDefinition.java   
public AttributeConverterDefinition(AttributeConverter attributeConverter, boolean autoApply) {
    this.attributeConverter = attributeConverter;
    this.autoApply = autoApply;

    final Class attributeConverterClass = attributeConverter.getClass();
    final ParameterizedType attributeConverterSignature = extractAttributeConverterParameterizedType( attributeConverterClass );

    if ( attributeConverterSignature.getActualTypeArguments().length < 2 ) {
        throw new AnnotationException(
                "AttributeConverter [" + attributeConverterClass.getName()
                        + "] did not retain parameterized type information"
        );
    }

    if ( attributeConverterSignature.getActualTypeArguments().length > 2 ) {
        throw new AnnotationException(
                "AttributeConverter [" + attributeConverterClass.getName()
                        + "] specified more than 2 parameterized types"
        );
    }
    entityAttributeType = (Class) attributeConverterSignature.getActualTypeArguments()[0];
    if ( entityAttributeType == null ) {
        throw new AnnotationException(
                "Could not determine 'entity attribute' type from given AttributeConverter [" +
                        attributeConverterClass.getName() + "]"
        );
    }

    databaseColumnType = (Class) attributeConverterSignature.getActualTypeArguments()[1];
    if ( databaseColumnType == null ) {
        throw new AnnotationException(
                "Could not determine 'database column' type from given AttributeConverter [" +
                        attributeConverterClass.getName() + "]"
        );
    }
}
项目:lams    文件:AttributeConverterDefinition.java   
private ParameterizedType extractAttributeConverterParameterizedType(Class attributeConverterClass) {
    for ( Type type : attributeConverterClass.getGenericInterfaces() ) {
        if ( ParameterizedType.class.isInstance( type ) ) {
            final ParameterizedType parameterizedType = (ParameterizedType) type;
            if ( AttributeConverter.class.equals( parameterizedType.getRawType() ) ) {
                return parameterizedType;
            }
        }
    }

    throw new AssertionFailure(
            "Could not extract ParameterizedType representation of AttributeConverter definition " +
                    "from AttributeConverter implementation class [" + attributeConverterClass.getName() + "]"
    );
}
项目:lams    文件:AttributeConverterTypeAdapter.java   
public AttributeConverterTypeAdapter(
        String name,
        AttributeConverter<? extends T,?> attributeConverter,
        SqlTypeDescriptor sqlTypeDescriptorAdapter,
        Class modelType,
        Class jdbcType,
        JavaTypeDescriptor<T> entityAttributeJavaTypeDescriptor) {
    super( sqlTypeDescriptorAdapter, entityAttributeJavaTypeDescriptor );
    this.name = name;
    this.modelType = modelType;
    this.jdbcType = jdbcType;
    this.attributeConverter = attributeConverter;

    log.debug( "Created AttributeConverterTypeAdapter -> " + name );
}
项目:lams    文件:AttributeConverterSqlTypeDescriptorAdapter.java   
public AttributeConverterSqlTypeDescriptorAdapter(
        AttributeConverter converter,
        SqlTypeDescriptor delegate,
        JavaTypeDescriptor intermediateJavaTypeDescriptor) {
    this.converter = converter;
    this.delegate = delegate;
    this.intermediateJavaTypeDescriptor = intermediateJavaTypeDescriptor;
}
项目:warpdb    文件:AccessibleProperty.java   
private static Class<?> checkPropertyType(Class<?> typeClass, AttributeConverter<Object, Object> converter) {
    Class<?> converterType = getConverterType(converter);
    if (converterType != null) {
        typeClass = converterType;
    }
    if (typeClass.isEnum() || DEFAULT_COLUMN_TYPES.containsKey(typeClass)) {
        return typeClass;
    }
    throw new RuntimeException("Unsupported type: " + typeClass);
}
项目:warpdb    文件:Where.java   
@SuppressWarnings("unchecked")
static CompiledClause doCompile(Mapper<?> mapper, String clause) {
    Map<String, AccessibleProperty> properties = mapper.allPropertiesMap;
    StringBuilder sb = new StringBuilder(clause.length() + 10);
    List<AttributeConverter<Object, Object>> list = new ArrayList<>();
    int start = 0;
    Matcher m = p.matcher(clause.toLowerCase());
    while (m.find()) {
        sb.append(clause.substring(start, m.start()));
        String s = clause.substring(m.start(), m.end());
        if (properties.containsKey(s.toLowerCase())) {
            AccessibleProperty ap = properties.get(s.toLowerCase());
            sb.append(ap.columnName);
            list.add(ap.converter);
        } else {
            if (s.toLowerCase().equals("between")) {
                list.add(list.get(list.size() - 1));
            } else if (s.toLowerCase().equals("null")) {
                list.remove(list.size() - 1);
            } else {
                if (!KEYWORDS.contains(s.toLowerCase())) {
                    throw new IllegalArgumentException("Invalid string \"" + s + "\" found in clause: " + clause);
                }
            }
            sb.append(s);
        }
        start = m.end();
    }
    sb.append(clause.substring(start));
    if (list.size() != numOfPlaceholder(clause)) {
        throw new IllegalArgumentException("Invalid number of placeholder.");
    }
    return new CompiledClause(sb.toString(), list.toArray(new AttributeConverter[0]));
}
项目:hibernate-semantic-query    文件:SingularAttributeBasic.java   
public SingularAttributeBasic(
        ManagedTypeImplementor declaringType,
        String name,
        PropertyAccess propertyAccess,
        BasicType ormType,
        Disposition disposition,
        AttributeConverter attributeConverter,
        List<Column> columns) {
    super( declaringType, name, propertyAccess, ormType, disposition, true );
    this.attributeConverter = attributeConverter;
    this.columns = columns;
}
项目:lams    文件:AttributeConversionInfo.java   
public Class<? extends AttributeConverter> getConverterClass() {
    return converterClass;
}
项目:lams    文件:AttributeConverterDefinition.java   
public AttributeConverter getAttributeConverter() {
    return attributeConverter;
}
项目:lams    文件:AttributeConverterTypeAdapter.java   
public AttributeConverter<? extends T,?> getAttributeConverter() {
    return attributeConverter;
}
项目:spring4-understanding    文件:LocalSessionFactoryBuilder.java   
@SuppressWarnings("unchecked")
public static void registerConverter(Configuration config, Class<?> converterClass) {
    config.addAttributeConverter((Class<? extends AttributeConverter<?, ?>>) converterClass);
}
项目:java-platform    文件:ArrayConverter.java   
public ArrayConverter(AttributeConverter<Object, String> elementConverter) {
    this.elementConverter = elementConverter;
}
项目:warpdb    文件:AccessibleProperty.java   
@SuppressWarnings({ "unchecked", "rawtypes" })
private AccessibleProperty(final Class<?> type, final String propertyName, final AccessibleObject accessible,
        final PropertyGetter getter, final PropertySetter setter) {
    accessible.setAccessible(true);
    this.accessible = accessible;
    // check:
    AttributeConverter<Object, Object> converter = getConverter(accessible);
    String columnDefinition = null;
    if (converter == null && type.isEnum()) {
        converter = new EnumToStringConverter(type);
        columnDefinition = "VARCHAR(50)";
    }
    final Class<?> propertyType = checkPropertyType(type, converter);
    final String columnName = getColumnName(accessible, propertyName);
    if (columnDefinition == null) {
        Class<?> ddlType = getConverterType(converter);
        if (ddlType == null) {
            ddlType = propertyType;
        }
        columnDefinition = getColumnDefinition(accessible, ddlType);
    } // init:
    this.nullable = isNullable();
    this.unique = isUnique();
    this.converter = converter;
    this.propertyType = propertyType;
    this.propertyName = propertyName;
    this.columnName = columnName;
    this.columnDefinition = columnDefinition;
    this.getter = getter;
    this.convertGetter = (bean) -> {
        Object value = getter.get(bean);
        if (value != null && this.converter != null) {
            value = this.converter.convertToDatabaseColumn(value);
        }
        return value;
    };
    this.setter = setter;
    this.convertSetter = (bean, value) -> {
        if (value != null && this.converter != null) {
            value = this.converter.convertToEntityAttribute(value);
        }
        setter.set(bean, value);
    };
}
项目:warpdb    文件:Where.java   
CompiledClause(String clause, AttributeConverter<Object, Object>[] converters) {
    this.clause = clause;
    this.converters = converters;
}
项目:rise    文件:PersistenceUnitManagerHelper.java   
public MutablePersistenceUnitInfo createUnit(Class<? extends Annotation> qualifier, String unitName) {
    ClassLoader classLoader = holder.getCurrentReloadableClassLoader();
    MutablePersistenceUnitInfo result = new MutablePersistenceUnitInfo();
    result.setExcludeUnlistedClasses(true);
    result.setValidationMode(ValidationMode.NONE);
    result.setPersistenceUnitName(unitName);
    result.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);

    try {
        result.setPersistenceUnitRootUrl(new URL("http://foo.foo"));
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }

    result.addProperty(PersistenceUnitProperties.SESSION_CUSTOMIZER, CompositeSessionCustomizer.class.getName());

    // search for entities
    {
        Set<Class<?>> jpaAnnotations = new HashSet<>(
                Arrays.asList(Entity.class, MappedSuperclass.class, Embeddable.class));
        for (ClassNode classNode : index.getAllNodes()) {
            String className = Type.getObjectType(classNode.name).getClassName();

            if (classNode.visibleAnnotations == null)
                continue;

            boolean jpaAnnotationFound = false;
            for (AnnotationNode annotation : classNode.visibleAnnotations) {
                Class<?> annotationClass = AsmUtil.loadClass(Type.getType(annotation.desc), classLoader);

                // test if the annotation is one of the jpa annotations
                if (jpaAnnotations.contains(annotationClass))
                    jpaAnnotationFound = true;

            }

            if (jpaAnnotationFound && isPartOfPU(classNode, qualifier, classLoader)) {
                result.addManagedClassName(className);
            }
        }
    }

    // search converters
    {
        index.getAllChildren(AttributeConverter.class).stream()
                .filter(node -> isPartOfPU(node, qualifier, classLoader))
                .map(node -> AsmUtil.loadClass(Type.getObjectType(node.name), classLoader)).forEach(cls -> {
                    Converter converter = cls.getAnnotation(Converter.class);
                    if (converter != null && converter.autoApply())
                        result.addManagedClassName(cls.getName());
                });
    }
    return result;
}
项目:hibernate-semantic-query    文件:PersisterHelper.java   
public AbstractOrmAttribute buildSingularAttribute(
            PersisterCreationContext creationContext,
            OrmNavigableSource source,
            Value value,
            String attributeName,
            Type attributeType,
            List<Column> columns) {
        final SingularAttributeClassification classification = interpretSingularAttributeClassification( attributeType );
        if ( classification == SingularAttributeClassification.ANY ) {
            throw new NotYetImplementedException();
        }
        else if ( classification == SingularAttributeClassification.EMBEDDED ) {
            return new SingularAttributeEmbedded(
                    (ManagedTypeImplementor) source,
                    attributeName,
                    PropertyAccess.DUMMY,
                    SingularAttribute.Disposition.NORMAL,
                    buildEmbeddablePersister(
                            creationContext,
                            (EmbeddableContainer) source,
                            attributeName,
                            (Component) value,
                            columns
                    )
            );
        }
        else if ( classification == SingularAttributeClassification.BASIC ) {
            // todo : need to be able to locate the AttributeConverter (if one) associated with this singular basic attribute
//          final AttributeConverter attributeConverter = ( (SimpleValue) value ).getAttributeConverterDescriptor().getAttributeConverter();
            final AttributeConverter attributeConverter = null;
            return new SingularAttributeBasic(
                    (ManagedTypeImplementor) source,
                    attributeName,
                    PropertyAccess.DUMMY,
                    (BasicType) attributeType,
                    SingularAttribute.Disposition.NORMAL,
                    attributeConverter,
                    columns
            );
        }
        else {
            final EntityType ormEntityType = (EntityType) attributeType;
            return new SingularAttributeEntity(
                    (ManagedTypeImplementor) source,
                    attributeName,
                    PropertyAccess.DUMMY,
                    SingularAttribute.Disposition.NORMAL,
                    classification,
                    ormEntityType,
                    columns
            );
        }
    }
项目:hibernate-semantic-query    文件:SingularAttributeBasic.java   
@Override
public Optional<AttributeConverter> getAttributeConverter() {
    return Optional.of( attributeConverter );
}
项目:jeddict    文件:ConvertPanel.java   
static void importAttributeConverter(String classHandle, AtomicBoolean validated, ModelerFile modelerFile) {
    if(StringUtils.isBlank(classHandle)){
        validated.set(true);
        return;
    }
    FileObject pkg = SourceGroupSupport.findSourceGroupForFile(modelerFile.getFileObject()).getRootFolder();
    try {
        JavaSource javaSource = JavaSource.create(ClasspathInfo.create(pkg));
        javaSource.runUserActionTask(controller -> {
            try {
                controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                TypeElement jc = controller.getElements().getTypeElement(classHandle);
                EntityMappings entityMappings = (EntityMappings)modelerFile.getDefinitionElement();
                Optional<Converter> converter = entityMappings.findConverter(classHandle);
                if (jc != null) {
                    DeclaredType attributeConverterType = null;
                    if (!jc.getInterfaces().isEmpty()) { //fetch interface info
                        for (TypeMirror interfaceType : jc.getInterfaces()) {
                            if (interfaceType.getKind() == TypeKind.DECLARED
                                    && AttributeConverter.class.getName().equals(((DeclaredType) interfaceType).asElement().toString())) {
                                attributeConverterType = (DeclaredType) interfaceType;
                            }
                        }
                    }
                    if (attributeConverterType != null && attributeConverterType.getTypeArguments().size() == 2) {
                        TypeMirror attributeType = attributeConverterType.getTypeArguments().get(0);
                        TypeMirror dbFieldType = attributeConverterType.getTypeArguments().get(1);
                        if (!entityMappings.addConverter(classHandle, attributeType.toString(), dbFieldType.toString())) {
                            message("MSG_ATTRIBUTE_CONVERTER_TYPE_CONFLICT", classHandle);
                        } else {
                            if(!converter.isPresent()) {
                                message("MSG_ATTRIBUTE_CONVERTER_TYPE_REGISTERED", classHandle, attributeType.toString(), dbFieldType.toString());
                            }
                            validated.set(true);
                        }
                    } else {
                        message("MSG_ATTRIBUTE_CONVERTER_NOT_IMPLEMENTED", classHandle);
                    }
                } else {
                    if(converter.isPresent()){
                        validated.set(true);
                    } else {
                       message("MSG_ARTIFACT_NOT_FOUND", classHandle, pkg.getPath());
                    }
                }
            } catch (IOException t) {
                ExceptionUtils.printStackTrace(t);
            }
        }, true);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}
项目:lams    文件:Configuration.java   
/**
 * Adds the AttributeConverter Class to this Configuration.
 *
 * @param attributeConverterClass The AttributeConverter class.
 * @param autoApply Should the AttributeConverter be auto applied to property types as specified
 * by its "entity attribute" parameterized type?
 */
public void addAttributeConverter(Class<? extends AttributeConverter> attributeConverterClass, boolean autoApply) {
    addAttributeConverter(
            instantiateAttributeConverter( attributeConverterClass ),
            autoApply
    );
}
项目:lams    文件:Configuration.java   
/**
 * Adds the AttributeConverter Class to this Configuration.
 *
 * @param attributeConverterClass The AttributeConverter class.
 */
public void addAttributeConverter(Class<? extends AttributeConverter> attributeConverterClass) {
    addAttributeConverter( instantiateAttributeConverter( attributeConverterClass ) );
}
项目:lams    文件:Configuration.java   
/**
 * Adds the AttributeConverter instance to this Configuration.  This form is mainly intended for developers
 * to programatically add their own AttributeConverter instance.  HEM, instead, uses the
 * {@link #addAttributeConverter(Class, boolean)} form
 *
 * @param attributeConverter The AttributeConverter instance.
 * @param autoApply Should the AttributeConverter be auto applied to property types as specified
 * by its "entity attribute" parameterized type?
 */
public void addAttributeConverter(AttributeConverter attributeConverter, boolean autoApply) {
    addAttributeConverter( new AttributeConverterDefinition( attributeConverter, autoApply ) );
}
项目:hibernate-semantic-query    文件:ConvertibleOrmNavigable.java   
Optional<AttributeConverter> getAttributeConverter();