Search in sources :

Example 6 with MappingException

use of org.neo4j.ogm.exception.core.MappingException in project neo4j-ogm by neo4j.

the class MappingContext method generateIdIfNecessary.

private static void generateIdIfNecessary(Object entity, ClassInfo classInfo) {
    if (classInfo.idStrategyClass() == null || InternalIdStrategy.class.equals(classInfo.idStrategyClass())) {
        return;
    }
    if (classInfo.idStrategy() == null) {
        throw new MappingException("Id strategy " + classInfo.idStrategyClass() + " could not be instantiated " + "and wasn't registered. Either provide no argument constructor or register instance " + "with SessionFactory");
    }
    FieldInfo primaryIndexField = classInfo.primaryIndexField();
    Object existingUuid = classInfo.readPrimaryIndexValueOf(entity);
    if (existingUuid == null) {
        IdStrategy strategy = classInfo.idStrategy();
        Object id = strategy.generateId(entity);
        if (strategy instanceof UuidStrategy && primaryIndexField.isTypeOf(String.class)) {
            id = id.toString();
        }
        primaryIndexField.writeDirect(entity, id);
    }
}
Also used : IdStrategy(org.neo4j.ogm.id.IdStrategy) InternalIdStrategy(org.neo4j.ogm.id.InternalIdStrategy) UuidStrategy(org.neo4j.ogm.id.UuidStrategy) InternalIdStrategy(org.neo4j.ogm.id.InternalIdStrategy) FieldInfo(org.neo4j.ogm.metadata.FieldInfo) MappingException(org.neo4j.ogm.exception.core.MappingException)

Example 7 with MappingException

use of org.neo4j.ogm.exception.core.MappingException in project neo4j-ogm by neo4j.

the class MappingContext method nativeId.

public Long nativeId(Object entity) {
    ClassInfo classInfo = metaData.classInfo(entity);
    if (classInfo == null) {
        throw new IllegalArgumentException("Class " + entity.getClass() + " is not a valid entity class. " + "Please check the entity mapping.");
    }
    generateIdIfNecessary(entity, classInfo);
    if (classInfo.hasIdentityField()) {
        return EntityUtils.identity(entity, metaData);
    } else {
        final Object primaryIndexValue = classInfo.readPrimaryIndexValueOf(entity);
        if (primaryIndexValue == null) {
            throw new MappingException("Field with primary id is null for entity " + entity);
        }
        LabelPrimaryId key = LabelPrimaryId.of(classInfo, primaryIndexValue);
        Long graphId = primaryIdToNativeId.get(key);
        if (graphId == null) {
            graphId = EntityUtils.nextRef();
            primaryIdToNativeId.put(key, graphId);
        }
        return graphId;
    }
}
Also used : ClassInfo(org.neo4j.ogm.metadata.ClassInfo) MappingException(org.neo4j.ogm.exception.core.MappingException)

Example 8 with MappingException

use of org.neo4j.ogm.exception.core.MappingException in project neo4j-ogm by neo4j.

the class DomainInfo method registerDefaultFieldConverters.

private void registerDefaultFieldConverters(ClassInfo classInfo, FieldInfo fieldInfo) {
    if (!fieldInfo.hasPropertyConverter() && !fieldInfo.hasCompositeConverter()) {
        final String typeDescriptor = fieldInfo.getTypeDescriptor();
        // Check if there's a registered set of attribute converters for the given field info and if so,
        // select the correct one based on the features of the field
        Function<AttributeConverters, Optional<AttributeConverter<?, ?>>> selectAttributeConverter = ac -> DomainInfo.selectAttributeConverterFor(fieldInfo, ac);
        Optional<AttributeConverter<?, ?>> registeredAttributeConverter = ConvertibleTypes.REGISTRY.entrySet().stream().filter(e -> typeDescriptor.contains(e.getKey())).sorted(comparingInt((Map.Entry<String, ?> e) -> e.getKey().length()).reversed()).findFirst().map(Map.Entry::getValue).flatMap(selectAttributeConverter);
        boolean isSupportedNativeType = typeSystem.supportsAsNativeType(DescriptorMappings.getType(fieldInfo.getTypeDescriptor()));
        // We can use a registered converter
        if (registeredAttributeConverter.isPresent() && !isSupportedNativeType) {
            fieldInfo.setPropertyConverter(registeredAttributeConverter.get());
        } else {
            // Check if the user configured one through the convert annotation
            if (fieldInfo.getAnnotations().get(Convert.class) != null) {
                // no converter's been set but this method is annotated with @Convert so we need to proxy it
                Class<?> entityAttributeType = DescriptorMappings.getType(typeDescriptor);
                String graphTypeDescriptor = fieldInfo.getAnnotations().get(Convert.class).get(Convert.GRAPH_TYPE, null);
                if (graphTypeDescriptor == null) {
                    throw new MappingException("Found annotation to convert a " + (entityAttributeType != null ? entityAttributeType.getName() : " null object ") + " on " + classInfo.name() + '.' + fieldInfo.getName() + " but no target graph property type or specific AttributeConverter have been specified.");
                }
                fieldInfo.setPropertyConverter(new ProxyAttributeConverter(entityAttributeType, DescriptorMappings.getType(graphTypeDescriptor), this.conversionCallbackRegistry));
            }
            Class fieldType = DescriptorMappings.getType(typeDescriptor);
            if (fieldType == null) {
                throw new RuntimeException("Class " + classInfo.name() + " field " + fieldInfo.getName() + " has null field type.");
            }
            boolean enumConverterSet = false;
            for (Class enumClass : enumTypes) {
                if (fieldType.equals(enumClass)) {
                    setEnumFieldConverter(fieldInfo, enumClass);
                    enumConverterSet = true;
                    break;
                }
            }
            if (!enumConverterSet && isEnum(fieldType)) {
                LOGGER.debug("Setting default enum converter for unscanned class " + classInfo.name() + ", field: " + fieldInfo.getName());
                setEnumFieldConverter(fieldInfo, fieldType);
            }
        }
    }
}
Also used : ClassGraph(io.github.classgraph.ClassGraph) java.util(java.util) RelationshipEntity(org.neo4j.ogm.annotation.RelationshipEntity) LoggerFactory(org.slf4j.LoggerFactory) ConversionCallback(org.neo4j.ogm.typeconversion.ConversionCallback) Function(java.util.function.Function) ConvertibleTypes(org.neo4j.ogm.typeconversion.ConvertibleTypes) AttributeConverters(org.neo4j.ogm.typeconversion.AttributeConverters) ScanResult(io.github.classgraph.ScanResult) NodeEntity(org.neo4j.ogm.annotation.NodeEntity) NoNativeTypes(org.neo4j.ogm.driver.TypeSystem.NoNativeTypes) Convert(org.neo4j.ogm.annotation.typeconversion.Convert) Logger(org.slf4j.Logger) Predicate(java.util.function.Predicate) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ProxyAttributeConverter(org.neo4j.ogm.typeconversion.ProxyAttributeConverter) InputStreamReader(java.io.InputStreamReader) ConversionCallbackRegistry(org.neo4j.ogm.typeconversion.ConversionCallbackRegistry) ClassUtils(org.neo4j.ogm.support.ClassUtils) TypeSystem(org.neo4j.ogm.driver.TypeSystem) Configuration(org.neo4j.ogm.config.Configuration) BufferedReader(java.io.BufferedReader) Pattern(java.util.regex.Pattern) MappingException(org.neo4j.ogm.exception.core.MappingException) Comparator(java.util.Comparator) AttributeConverter(org.neo4j.ogm.typeconversion.AttributeConverter) InputStream(java.io.InputStream) Convert(org.neo4j.ogm.annotation.typeconversion.Convert) AttributeConverters(org.neo4j.ogm.typeconversion.AttributeConverters) ProxyAttributeConverter(org.neo4j.ogm.typeconversion.ProxyAttributeConverter) MappingException(org.neo4j.ogm.exception.core.MappingException) ProxyAttributeConverter(org.neo4j.ogm.typeconversion.ProxyAttributeConverter) AttributeConverter(org.neo4j.ogm.typeconversion.AttributeConverter) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 9 with MappingException

use of org.neo4j.ogm.exception.core.MappingException in project neo4j-ogm by neo4j.

the class DomainInfo method getClassInfo.

private ClassInfo getClassInfo(String fullOrPartialClassName, Map<String, ClassInfo> infos) {
    // It is a fully, qualified name or at least matches to one.
    if (infos.containsKey(fullOrPartialClassName)) {
        return infos.get(fullOrPartialClassName);
    }
    Optional<String> foundKey = fqnLookup.computeIfAbsent(fullOrPartialClassName, k -> {
        Pattern partialClassNamePattern = Pattern.compile(".+[\\\\.\\$]" + Pattern.quote(k) + "$");
        String matchingKey = null;
        for (String key : infos.keySet()) {
            boolean isCandidate = partialClassNamePattern.matcher(key).matches();
            if (isCandidate) {
                ClassInfo candidate = infos.get(key);
                String candidateNeo4jName = candidate.neo4jName() != null ? candidate.neo4jName() : key;
                if (matchingKey != null) {
                    ClassInfo existingMatch = infos.get(matchingKey);
                    String previousMatchNeo4jName = existingMatch.neo4jName() != null ? existingMatch.neo4jName() : key;
                    boolean sameLabel = candidateNeo4jName.equals(previousMatchNeo4jName);
                    if (sameLabel) {
                        throw new MappingException("More than one class has simple name: " + fullOrPartialClassName);
                    }
                }
                if (matchingKey == null || candidateNeo4jName.equals(fullOrPartialClassName)) {
                    matchingKey = key;
                }
            }
        }
        return Optional.ofNullable(matchingKey);
    });
    return foundKey.map(infos::get).orElse(null);
}
Also used : Pattern(java.util.regex.Pattern) MappingException(org.neo4j.ogm.exception.core.MappingException)

Example 10 with MappingException

use of org.neo4j.ogm.exception.core.MappingException in project neo4j-ogm by neo4j.

the class PizzaIntegrationTest method shouldRaiseExceptionWhenAmbiguousClassLabelApplied.

// See #159
@Test
public void shouldRaiseExceptionWhenAmbiguousClassLabelApplied() {
    Session sessionWithAmbiguousDomain = new SessionFactory(getDriver(), "org.neo4j.ogm.domain.pizza", "org.neo4j.ogm.domain.music").openSession();
    Pizza pizza = new Pizza();
    pizza.setName("Mushroom & Pepperoni");
    List<String> labels = new ArrayList<>();
    // We're adding the studio label, which is mapped to a type
    labels.add("Studio");
    pizza.setLabels(labels);
    sessionWithAmbiguousDomain.save(pizza);
    sessionWithAmbiguousDomain.clear();
    try {
        sessionWithAmbiguousDomain.load(Pizza.class, pizza.getId());
    } catch (MappingException e) {
        assertThat(e.getMessage()).isEqualTo("Multiple classes found in type hierarchy that map to: [Pizza, Studio]");
    }
}
Also used : SessionFactory(org.neo4j.ogm.session.SessionFactory) ArrayList(java.util.ArrayList) Session(org.neo4j.ogm.session.Session) Neo4jSession(org.neo4j.ogm.session.Neo4jSession) MappingException(org.neo4j.ogm.exception.core.MappingException) Test(org.junit.Test)

Aggregations

MappingException (org.neo4j.ogm.exception.core.MappingException)10 ClassInfo (org.neo4j.ogm.metadata.ClassInfo)4 FieldInfo (org.neo4j.ogm.metadata.FieldInfo)3 java.util (java.util)2 Predicate (java.util.function.Predicate)2 Pattern (java.util.regex.Pattern)2 Convert (org.neo4j.ogm.annotation.typeconversion.Convert)2 MetaData (org.neo4j.ogm.metadata.MetaData)2 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2 ClassGraph (io.github.classgraph.ClassGraph)1 ScanResult (io.github.classgraph.ScanResult)1 BufferedReader (java.io.BufferedReader)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Instant (java.time.Instant)1 ArrayList (java.util.ArrayList)1 Comparator (java.util.Comparator)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1