org.eclipse.persistence.mappings.converters.Converter Java Examples

The following examples show how to use org.eclipse.persistence.mappings.converters.Converter. 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: EclipseLinkAnnotationMetadataProviderImplTest.java    From rice with Educational Community License v2.0 6 votes vote down vote up
@Test
public void testConvertersEstabished_directAssignment() throws Exception {
	ClassDescriptor classDescriptor = jpaMetadataProvider.getClassDescriptor(TestDataObject.class);
	DatabaseMapping attribute = classDescriptor.getMappingForAttributeName("nonStandardDataType");
	assertEquals("attribute data type mismatch", DirectToFieldMapping.class, attribute.getClass());
	Converter converter = ((org.eclipse.persistence.mappings.DirectToFieldMapping) attribute).getConverter();
	assertNotNull("converter not assigned", converter);
	assertEquals("Mismatch - converter should have been the EclipseLink JPA wrapper class", ConverterClass.class,
               converter.getClass());
	Field f = ConverterClass.class.getDeclaredField("attributeConverterClassName");
	f.setAccessible(true);
	String attributeConverterClassName = (String) f.get(converter);
	assertNotNull("attributeConverterClassName missing", attributeConverterClassName);
	assertEquals("Converter class incorrect", "org.kuali.rice.krad.data.jpa.testbo.NonStandardDataTypeConverter",
               attributeConverterClassName);
}
 
Example #2
Source File: EclipseLinkAnnotationMetadataProviderImplTest.java    From rice with Educational Community License v2.0 6 votes vote down vote up
@Test
public void testConvertersEstabished_autoApply() throws Exception {
	ClassDescriptor classDescriptor = jpaMetadataProvider.getClassDescriptor(TestDataObject.class);
	DatabaseMapping attribute = classDescriptor.getMappingForAttributeName("currencyProperty");
	assertEquals("attribute data type mismatch", DirectToFieldMapping.class, attribute.getClass());
	Converter converter = ((org.eclipse.persistence.mappings.DirectToFieldMapping) attribute).getConverter();
	assertNotNull("converter not assigned", converter);
	assertEquals("Mismatch - converter should have been the EclipseLink JPA wrapper class", ConverterClass.class,
               converter.getClass());
	Field f = ConverterClass.class.getDeclaredField("attributeConverterClassName");
	f.setAccessible(true);
	String attributeConverterClassName = (String) f.get(converter);
	assertNotNull("attributeConverterClassName missing", attributeConverterClassName);
	assertEquals("Converter class incorrect", "org.kuali.rice.krad.data.jpa.converters.KualiDecimalConverter",
               attributeConverterClassName);
}
 
Example #3
Source File: EclipseLinkAnnotationMetadataProviderImplTest.java    From rice with Educational Community License v2.0 6 votes vote down vote up
@Test
public void testConvertersEstabished_autoApply_Boolean() throws Exception {
	ClassDescriptor classDescriptor = jpaMetadataProvider.getClassDescriptor(TestDataObject.class);
	DatabaseMapping attribute = classDescriptor.getMappingForAttributeName("booleanProperty");
	assertEquals("attribute data type mismatch", DirectToFieldMapping.class, attribute.getClass());
	Converter converter = ((org.eclipse.persistence.mappings.DirectToFieldMapping) attribute).getConverter();
	assertNotNull("converter not assigned", converter);
	assertEquals("Mismatch - converter should have been the EclipseLink JPA wrapper class", ConverterClass.class,
               converter.getClass());
	Field f = ConverterClass.class.getDeclaredField("attributeConverterClassName");
	f.setAccessible(true);
	String attributeConverterClassName = (String) f.get(converter);
	assertNotNull("attributeConverterClassName missing", attributeConverterClassName);
	assertEquals("Converter class incorrect", "org.kuali.rice.krad.data.jpa.converters.BooleanYNConverter",
               attributeConverterClassName);
}
 
Example #4
Source File: PersistenceTools.java    From cuba with Apache License 2.0 4 votes vote down vote up
/**
 * Returns an ID of directly referenced entity without loading it from DB.
 * <p>
 * If the view does not contain the reference and {@link View#loadPartialEntities()} is true,
 * the returned {@link RefId} will have {@link RefId#isLoaded()} = false.
 *
 * <p>Usage example:
 * <pre>
 *   PersistenceTools.RefId refId = persistenceTools.getReferenceId(doc, "currency");
 *   if (refId.isLoaded()) {
 *       String currencyCode = (String) refId.getValue();
 *   }
 * </pre>
 *
 * @param entity   entity instance in managed state
 * @param property name of reference property
 * @return {@link RefId} instance which contains the referenced entity ID
 * @throws IllegalArgumentException if the specified property is not a reference
 * @throws IllegalStateException    if the entity is not in Managed state
 * @throws RuntimeException         if anything goes wrong when retrieving the ID
 */
public RefId getReferenceId(BaseGenericIdEntity entity, String property) {
    MetaClass metaClass = metadata.getClassNN(entity.getClass());
    MetaProperty metaProperty = metaClass.getPropertyNN(property);

    if (!metaProperty.getRange().isClass() || metaProperty.getRange().getCardinality().isMany())
        throw new IllegalArgumentException("Property is not a reference");

    if (!entityStates.isManaged(entity))
        throw new IllegalStateException("Entity must be in managed state");

    String[] inaccessibleAttributes = BaseEntityInternalAccess.getInaccessibleAttributes(entity);
    if (inaccessibleAttributes != null) {
        for (String inaccessibleAttr : inaccessibleAttributes) {
            if (inaccessibleAttr.equals(property))
                return RefId.createNotLoaded(property);
        }
    }

    if (entity instanceof FetchGroupTracker) {
        FetchGroup fetchGroup = ((FetchGroupTracker) entity)._persistence_getFetchGroup();
        if (fetchGroup != null) {
            if (!fetchGroup.containsAttributeInternal(property))
                return RefId.createNotLoaded(property);
            else {
                Entity refEntity = (Entity) entity.getValue(property);
                return RefId.create(property, refEntity == null ? null : refEntity.getId());
            }
        }
    }

    try {
        Class<?> declaringClass = metaProperty.getDeclaringClass();
        if (declaringClass == null) {
            throw new RuntimeException("Property does not belong to persistent class");
        }

        Method vhMethod = declaringClass.getDeclaredMethod(String.format("_persistence_get_%s_vh", property));
        vhMethod.setAccessible(true);

        ValueHolderInterface vh = (ValueHolderInterface) vhMethod.invoke(entity);
        if (vh instanceof DatabaseValueHolder) {
            AbstractRecord row = ((DatabaseValueHolder) vh).getRow();
            if (row != null) {
                Session session = persistence.getEntityManager().getDelegate().unwrap(Session.class);
                ClassDescriptor descriptor = session.getDescriptor(entity);
                DatabaseMapping mapping = descriptor.getMappingForAttributeName(property);
                Vector<DatabaseField> fields = mapping.getFields();
                if (fields.size() != 1) {
                    throw new IllegalStateException("Invalid number of columns in mapping: " + fields);
                }
                Object value = row.get(fields.get(0));
                if (value != null) {
                    ClassDescriptor refDescriptor = mapping.getReferenceDescriptor();
                    DatabaseMapping refMapping = refDescriptor.getMappingForAttributeName(metadata.getTools().getPrimaryKeyName(metaClass));
                    if (refMapping instanceof AbstractColumnMapping) {
                        Converter converter = ((AbstractColumnMapping) refMapping).getConverter();
                        if (converter != null) {
                            return RefId.create(property, converter.convertDataValueToObjectValue(value, session));
                        }
                    }
                }
                return RefId.create(property, value);
            } else {
                return RefId.create(property, null);
            }
        }
        return RefId.createNotLoaded(property);
    } catch (Exception e) {
        throw new RuntimeException(
                String.format("Error retrieving reference ID from %s.%s", entity.getClass().getSimpleName(), property),
                e);
    }
}
 
Example #5
Source File: JPAMDefaultTableGenerator.java    From jeddict with Apache License 2.0 4 votes vote down vote up
/**
     *
     * @param baseDescriptor
     * @param intrinsicEntity defines the Entity Object that contains embedded
     * Object where Entity object will be intrinsicEntity and Embeddable object
     * will be descriptorManagedClass
     * @param intrinsicAttribute
     */
    protected void postInitTableSchema(ClassDescriptor baseDescriptor, LinkedList<Entity> intrinsicEntity, LinkedList<Attribute> intrinsicAttribute) {

        DBRelationalDescriptor descriptor = (DBRelationalDescriptor) baseDescriptor;
        ManagedClass descriptorManagedClass = null;

        if (intrinsicEntity == null) {
            if (descriptor.getAccessor() instanceof EntitySpecAccessor) {
                intrinsicEntity = new LinkedList<>();
                intrinsicAttribute = new LinkedList<>();
                intrinsicEntity.offer(((EntitySpecAccessor) descriptor.getAccessor()).getEntity());
                descriptorManagedClass = intrinsicEntity.peek();
            } else {
                throw new IllegalStateException(descriptor.getAccessor() + " not supported");
            }
        } else if (descriptor.getAccessor() instanceof EmbeddableSpecAccessor) {
            descriptorManagedClass = ((EmbeddableSpecAccessor) descriptor.getAccessor()).getEmbeddable();
        }  else if (descriptor.getAccessor() instanceof DefaultClassSpecAccessor) {
//            descriptorManagedClass = ((DefaultClassSpecAccessor) descriptor.getAccessor()).getDefaultClass();
        } else {
            throw new IllegalStateException(descriptor.getAccessor() + " not supported");
        }

        for (DatabaseMapping mapping : descriptor.getMappings()) {
            ManagedClass managedClass = descriptorManagedClass;
            Attribute managedAttribute = (Attribute) mapping.getProperty(Attribute.class);
            Boolean isInherited = (Boolean) mapping.getProperty(Inheritance.class);
            isInherited = isInherited == null ? false : isInherited;
            
            if (intrinsicAttribute.peek() == null) {
                intrinsicAttribute.offer(managedAttribute);
            }

           if(managedAttribute instanceof RelationAttribute && !((RelationAttribute)managedAttribute).isOwner()){
               //skip non-owner
           } else if (descriptor.isChildDescriptor() && descriptor.getInheritancePolicy().getParentDescriptor().getMappingForAttributeName(mapping.getAttributeName()) != null) {
                // If we are an inheritance subclass, do nothing. That is, don't
                // generate mappings that will be generated by our parent,
                // otherwise the fields for that mapping will be generated n
                // times for the same table.
            } else if (mapping.isManyToManyMapping()) {
                buildRelationTableDefinition(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (ManyToManyMapping) mapping, ((ManyToManyMapping) mapping).getRelationTableMechanism(), ((ManyToManyMapping) mapping).getListOrderField(), mapping.getContainerPolicy());
            } else if (mapping.isDirectCollectionMapping()) {
                buildDirectCollectionTableDefinition(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (DirectCollectionMapping) mapping, descriptor);
            } else if (mapping.isDirectToFieldMapping()) {
                Converter converter = ((DirectToFieldMapping) mapping).getConverter();
                if (converter != null) {
                    if (converter instanceof TypeConversionConverter) {
                        resetFieldTypeForLOB((DirectToFieldMapping) mapping);
                    }

                    // uncomment on upgrade to eclipselink v2.7.2+
//                    if (converter instanceof SerializedObjectConverter) {
//                        //serialized object mapping field should be BLOB/IMAGE
//                        getFieldDefFromDBField(mapping.getField()).setType(((SerializedObjectConverter) converter).getSerializer().getType());
//                    }
                }
            } else if (mapping.isAggregateCollectionMapping()) {
                //need to figure out the target foreign key field and add it into the aggregate target table
//               if(managedAttribute instanceof ElementCollection || ((ElementCollection)managedAttribute).getConnectedClass()!=null){
//                   ClassDescriptor refDescriptor = mapping.getReferenceDescriptor();
//                                    Attribute attribute = getManagedAttribute(refDescriptor, dbField, intrinsicAttribute);//TODO intrinsicAttribute nested path/attribute not set
//
//               }
                createAggregateTargetTable(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (AggregateCollectionMapping) mapping);
            } else if (mapping.isForeignReferenceMapping()) {
                if (mapping.isOneToOneMapping()) {
                    RelationTableMechanism relationTableMechanism = ((OneToOneMapping) mapping).getRelationTableMechanism();
                    if (relationTableMechanism == null) {
                        addForeignKeyFieldToSourceTargetTable(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (OneToOneMapping) mapping);
                    } else {
                        buildRelationTableDefinition(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (OneToOneMapping) mapping, relationTableMechanism, null, null);
                    }
                } else if (mapping.isOneToManyMapping()) {
                    addForeignKeyFieldToSourceTargetTable(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, (OneToManyMapping) mapping);
                    TableDefinition targTblDef = getTableDefFromDBTable(((OneToManyMapping) mapping).getReferenceDescriptor().getDefaultTable());//TODO pass entity
                    addFieldsForMappedKeyMapContainerPolicy(managedClass, managedAttribute, intrinsicEntity, intrinsicAttribute, isInherited, mapping.getContainerPolicy(), targTblDef);
                }
            } else if (mapping.isTransformationMapping()) {
                resetTransformedFieldType((TransformationMapping) mapping);
            } else if (mapping.isAggregateObjectMapping()) {
                postInitTableSchema(((AggregateObjectMapping) mapping).getReferenceDescriptor(), new LinkedList<>(intrinsicEntity), new LinkedList<>(intrinsicAttribute));
            }
            intrinsicAttribute.clear();
        }

        processAdditionalTablePkFields(intrinsicEntity, descriptor);
        intrinsicEntity.clear();

    }
 
Example #6
Source File: EclipseLinkJpaMetadataProviderImpl.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
    * {@inheritDoc}
    */
@Override
protected void populateImplementationSpecificAttributeLevelMetadata(DataObjectAttributeImpl attribute,
		SingularAttribute<?, ?> attr) {

	if (attr instanceof SingularAttributeImpl) {
		DatabaseMapping mapping = ((SingularAttributeImpl<?, ?>) attr).getMapping();
		if (mapping != null && mapping.getField() != null) {
               attribute.setReadOnly(mapping.isReadOnly());
			attribute.setBackingObjectName(mapping.getField().getName());
			if (mapping.getField().getLength() != 0) {
				attribute.setMaxLength((long) mapping.getField().getLength());
			}

			// Special check on the converters to attempt to default secure attributes from being shown on the UI
			// We check for a converter which has "encrypt" in its name and auto-set the attribute security
			// to mask the attribute.
			if (mapping instanceof DirectToFieldMapping) {
				Converter converter = ((DirectToFieldMapping) mapping).getConverter();
				// ConverterClass is the internal wrapper EclipseLink uses to wrap the JPA AttributeConverter
				// classes
				// and make them conform to the EclipseLink internal API
				if (converter != null && converter instanceof ConverterClass) {
					// Unfortunately, there is no access to the actual converter class, so we have to hack it
					try {
						Field f = ConverterClass.class.getDeclaredField("attributeConverterClassName");
						f.setAccessible(true);
						String attributeConverterClassName = (String) f.get(converter);
						if (StringUtils.containsIgnoreCase(attributeConverterClassName, "encrypt")) {
							attribute.setSensitive(true);
						}
					} catch (Exception e) {
						LOG.warn("Unable to access the converter name for attribute: "
								+ attribute.getOwningType().getName() + "." + attribute.getName()
								+ "  Skipping attempt to detect converter.");
					}
				}
			}

		}
	}
}