javax.persistence.AttributeConverter Java Examples

The following examples show how to use javax.persistence.AttributeConverter. 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: Where.java    From warpdb with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: DBEntityMappings.java    From jeddict with Apache License 2.0 6 votes vote down vote up
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);

    }
 
Example #3
Source File: AbstractConverterDescriptor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private AutoApplicableConverterDescriptor resolveAutoApplicableDescriptor(
		Class<? extends AttributeConverter> converterClass,
		Boolean forceAutoApply) {
	final boolean autoApply;

	if ( forceAutoApply != null ) {
		// if the caller explicitly specified whether to auto-apply, honor that
		autoApply = forceAutoApply;
	}
	else {
		// otherwise, look at the converter's @Converter annotation
		final Converter annotation = converterClass.getAnnotation( Converter.class );
		autoApply = annotation != null && annotation.autoApply();
	}

	return autoApply
			? new AutoApplicableConverterDescriptorStandardImpl( this )
			: AutoApplicableConverterDescriptorBypassedImpl.INSTANCE;
}
 
Example #4
Source File: AccessibleProperty.java    From warpdb with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #5
Source File: AccessibleProperty.java    From warpdb with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #6
Source File: MetadataBuilderImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public MetadataBuilder applyAttributeConverter(Class<? extends AttributeConverter> attributeConverterClass, boolean autoApply) {
	this.bootstrapContext.addAttributeConverterInfo(
			new AttributeConverterInfo() {
				@Override
				public Class<? extends AttributeConverter> getConverterClass() {
					return attributeConverterClass;
				}

				@Override
				public ConverterDescriptor toConverterDescriptor(MetadataBuildingContext context) {
					return new ClassBasedConverterDescriptor(
							attributeConverterClass,
							autoApply,
							context.getBootstrapContext().getClassmateContext()
					);
				}
			}
	);
	return this;
}
 
Example #7
Source File: MetadataBuilderImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public MetadataBuilder applyAttributeConverter(Class<? extends AttributeConverter> attributeConverterClass) {
	this.bootstrapContext.addAttributeConverterInfo(
			new AttributeConverterInfo() {
				@Override
				public Class<? extends AttributeConverter> getConverterClass() {
					return attributeConverterClass;
				}

				@Override
				public ConverterDescriptor toConverterDescriptor(MetadataBuildingContext context) {
					return new ClassBasedConverterDescriptor(
							attributeConverterClass,
							null,
							context.getBootstrapContext().getClassmateContext()
					);
				}
			}
	);
	return this;
}
 
Example #8
Source File: InstanceBasedConverterDescriptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public InstanceBasedConverterDescriptor(
		AttributeConverter converterInstance,
		Boolean forceAutoApply,
		ClassmateContext classmateContext) {
	super( converterInstance.getClass(), forceAutoApply, classmateContext );
	this.converterInstance = converterInstance;
}
 
Example #9
Source File: Where.java    From warpdb with Apache License 2.0 5 votes vote down vote up
@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]));
}
 
Example #10
Source File: AccessibleProperty.java    From warpdb with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #11
Source File: AttributeConversionInfo.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public AttributeConversionInfo(
		Class<? extends AttributeConverter> converterClass,
		boolean conversionDisabled,
		String attributeName,
		XAnnotatedElement source) {
	this.converterClass = converterClass;
	this.conversionDisabled = conversionDisabled;
	this.attributeName = attributeName;
	this.source = source;
}
 
Example #12
Source File: AbstractConverterDescriptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("WeakerAccess")
public AbstractConverterDescriptor(
		Class<? extends AttributeConverter> converterClass,
		Boolean forceAutoApply,
		ClassmateContext classmateContext) {
	this.converterClass = converterClass;

	final ResolvedType converterType = classmateContext.getTypeResolver().resolve( converterClass );
	final List<ResolvedType> converterParamTypes = converterType.typeParametersFor( AttributeConverter.class );
	if ( converterParamTypes == null ) {
		throw new AnnotationException(
				"Could not extract type parameter information from AttributeConverter implementation ["
						+ converterClass.getName() + "]"
		);
	}
	else if ( converterParamTypes.size() != 2 ) {
		throw new AnnotationException(
				"Unexpected type parameter information for AttributeConverter implementation [" +
						converterClass.getName() + "]; expected 2 parameter types, but found " + converterParamTypes.size()
		);
	}

	this.domainType = converterParamTypes.get( 0 );
	this.jdbcType = converterParamTypes.get( 1 );

	this.autoApplicableDescriptor = resolveAutoApplicableDescriptor( converterClass, forceAutoApply );
}
 
Example #13
Source File: ExtraMappingMetadataContributor.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
/**
 * 处理枚举类型的转换器
 */
private void handleEnumType(PersistentClass pclazz, SimpleValue value) {
	// 自动装载枚举转换
	if (!"org.hibernate.type.EnumType".equals(value.getTypeName())) {
		return;
	}
	if (value.getTypeParameters() == null) {
		return;
	}
	String returnedClass = value.getTypeParameters().getProperty(
			"org.hibernate.type.ParameterType.returnedClass");
	if (StringUtils.isBlank(returnedClass)) {
		return;
	}

	Class<?> enumClass = ReflectUtil.classForName(returnedClass);
	Class<?>[] inners = enumClass.getClasses();
	if (inners == null) {
		return;
	}
	for (Class<?> inner : inners) {
		if (!AttributeConverter.class.isAssignableFrom(inner)) {
			continue;
		}
		String propertyName = value.getTypeParameters().getProperty(
				"org.hibernate.type.ParameterType.propertyName");
		value.setTypeName(StringHelper.join(
				AttributeConverterTypeAdapter.NAME_PREFIX,
				inner.getName()));
		value.setTypeName(null);
		value.setTypeParameters(null);
		value.setTypeUsingReflection(pclazz.getClassName(), propertyName);
		return;
	}
}
 
Example #14
Source File: InstanceStatusConverterTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public AttributeConverter<InstanceStatus, String> getVictim() {
    return new InstanceStatusConverter();
}
 
Example #15
Source File: InstanceMetadataTypeConverterTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public AttributeConverter<InstanceMetadataType, String> getVictim() {
    return new InstanceMetadataTypeConverter();
}
 
Example #16
Source File: GatewayTypeConverterTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public AttributeConverter<GatewayType, String> getVictim() {
    return new GatewayTypeConverter();
}
 
Example #17
Source File: DirectoryTypeConverterTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public AttributeConverter<DirectoryType, String> getVictim() {
    return new DirectoryTypeConverter();
}
 
Example #18
Source File: Where.java    From warpdb with Apache License 2.0 4 votes vote down vote up
CompiledClause(String clause, AttributeConverter<Object, Object>[] converters) {
	this.clause = clause;
	this.converters = converters;
}
 
Example #19
Source File: AccessibleProperty.java    From warpdb with Apache License 2.0 4 votes vote down vote up
@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.convertGetter = this.converter == null ? getter : (bean) -> {
		Object value = getter.get(bean);
		if (value != null) {
			value = this.converter.convertToDatabaseColumn(value);
		}
		return value;
	};
	this.convertSetter = this.converter == null ? setter : (bean, value) -> {
		if (value != null && this.converter != null) {
			value = this.converter.convertToEntityAttribute(value);
		}
		setter.set(bean, value);
	};
}
 
Example #20
Source File: InstanceLifeCycleConverterTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public AttributeConverter<InstanceLifeCycle, String> getVictim() {
    return new InstanceLifeCycleConverter();
}
 
Example #21
Source File: ArrayConverter.java    From java-platform with Apache License 2.0 4 votes vote down vote up
public ArrayConverter(AttributeConverter<Object, String> elementConverter) {
	this.elementConverter = elementConverter;
}
 
Example #22
Source File: ResourceTypeConverterTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public AttributeConverter<ResourceType, String> getVictim() {
    return new ResourceTypeConverter();
}
 
Example #23
Source File: StackTypeConverterTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public AttributeConverter<StackType, String> getVictim() {
    return new StackTypeConverter();
}
 
Example #24
Source File: S3GuardTableCreationConverterTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public AttributeConverter<S3GuardTableCreation, String> getVictim() {
    return new S3GuardTableCreationConverter();
}
 
Example #25
Source File: DatabaseAvailabilityTypeConverterTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public AttributeConverter<DatabaseAvailabilityType, String> getVictim() {
    return new DatabaseAvailabilityTypeConverter();
}
 
Example #26
Source File: InFlightMetadataCollectorImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void addAttributeConverter(Class<? extends AttributeConverter> converterClass) {
	attributeConverterManager.addConverter(
			new ClassBasedConverterDescriptor( converterClass, getBootstrapContext().getClassmateContext() )
	);
}
 
Example #27
Source File: AnnotationMetadataSourceProcessorImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public void addAttributeConverter(Class<? extends AttributeConverter> converterClass) {
	rootMetadataBuildingContext.getMetadataCollector().addAttributeConverter( converterClass );
}
 
Example #28
Source File: ScanningCoordinator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public void applyScanResultsToManagedResources(
		ManagedResourcesImpl managedResources,
		ScanResult scanResult,
		BootstrapContext bootstrapContext,
		XmlMappingBinderAccess xmlMappingBinderAccess) {

	final ScanEnvironment scanEnvironment = bootstrapContext.getScanEnvironment();
	final ServiceRegistry serviceRegistry = bootstrapContext.getServiceRegistry();
	final ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class );


	// mapping files ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	final Set<String> nonLocatedMappingFileNames = new HashSet<String>();
	final List<String> explicitMappingFileNames = scanEnvironment.getExplicitlyListedMappingFiles();
	if ( explicitMappingFileNames != null ) {
		nonLocatedMappingFileNames.addAll( explicitMappingFileNames );
	}

	for ( MappingFileDescriptor mappingFileDescriptor : scanResult.getLocatedMappingFiles() ) {
		managedResources.addXmlBinding( xmlMappingBinderAccess.bind( mappingFileDescriptor.getStreamAccess() ) );
		nonLocatedMappingFileNames.remove( mappingFileDescriptor.getName() );
	}

	for ( String name : nonLocatedMappingFileNames ) {
		final URL url = classLoaderService.locateResource( name );
		if ( url == null ) {
			throw new MappingException(
					"Unable to resolve explicitly named mapping-file : " + name,
					new Origin( SourceType.RESOURCE, name )
			);
		}
		final UrlInputStreamAccess inputStreamAccess = new UrlInputStreamAccess( url );
		managedResources.addXmlBinding( xmlMappingBinderAccess.bind( inputStreamAccess ) );
	}


	// classes and packages ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	final List<String> unresolvedListedClassNames = scanEnvironment.getExplicitlyListedClassNames() == null
			? new ArrayList<String>()
			: new ArrayList<String>( scanEnvironment.getExplicitlyListedClassNames() );

	for ( ClassDescriptor classDescriptor : scanResult.getLocatedClasses() ) {
		if ( classDescriptor.getCategorization() == ClassDescriptor.Categorization.CONVERTER ) {
			// converter classes are safe to load because we never enhance them,
			// and notice we use the ClassLoaderService specifically, not the temp ClassLoader (if any)
			managedResources.addAttributeConverterDefinition(
					AttributeConverterDefinition.from(
							classLoaderService.<AttributeConverter>classForName( classDescriptor.getName() )
					)
			);
		}
		else if ( classDescriptor.getCategorization() == ClassDescriptor.Categorization.MODEL ) {
			managedResources.addAnnotatedClassName( classDescriptor.getName() );
		}
		unresolvedListedClassNames.remove( classDescriptor.getName() );
	}

	// IMPL NOTE : "explicitlyListedClassNames" can contain class or package names...
	for ( PackageDescriptor packageDescriptor : scanResult.getLocatedPackages() ) {
		managedResources.addAnnotatedPackageName( packageDescriptor.getName() );
		unresolvedListedClassNames.remove( packageDescriptor.getName() );
	}

	for ( String unresolvedListedClassName : unresolvedListedClassNames ) {
		// because the explicit list can contain either class names or package names
		// we need to check for both here...

		// First, try it as a class name
		final String classFileName = unresolvedListedClassName.replace( '.', '/' ) + ".class";
		final URL classFileUrl = classLoaderService.locateResource( classFileName );
		if ( classFileUrl != null ) {
			managedResources.addAnnotatedClassName( unresolvedListedClassName );
			continue;
		}

		// Then, try it as a package name
		final String packageInfoFileName = unresolvedListedClassName.replace( '.', '/' ) + "/package-info.class";
		final URL packageInfoFileUrl = classLoaderService.locateResource( packageInfoFileName );
		if ( packageInfoFileUrl != null ) {
			managedResources.addAnnotatedPackageName( unresolvedListedClassName );
			continue;
		}

		log.debugf(
				"Unable to resolve class [%s] named in persistence unit [%s]",
				unresolvedListedClassName,
				scanEnvironment.getRootUrl()
		);
	}
}
 
Example #29
Source File: ClusterStateConverterTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public AttributeConverter<ClusterState, String> getVictim() {
    return new ClusterStateConverter();
}
 
Example #30
Source File: InstanceBasedConverterDescriptor.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected ManagedBean<? extends AttributeConverter> createManagedBean(JpaAttributeConverterCreationContext context) {
	return new ProvidedInstanceManagedBeanImpl( converterInstance );
}