All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.restup.registry.ResourceRelationship Maven / Gradle / Ivy

There is a newer version: 0.0.5
Show newest version
package com.github.restup.registry;

import static com.github.restup.annotations.field.RelationshipType.manyToOne;
import static com.github.restup.annotations.field.RelationshipType.oneToMany;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import com.github.restup.annotations.field.RelationshipType;
import com.github.restup.path.ResourcePath;

public interface ResourceRelationship {

    RelationshipType getType(Resource resource);

    Set getFromIds(Object from);

    Set getToIds(Object to);

    @SuppressWarnings("rawtypes")
    Set getJoinIds(Resource resource, Object data);

    Set getIds(FROM from);

    Set getIds(Collection from);

    Set getIdsTo(TO to);

    Set getIdsTo(Collection to);

    Resource getFrom();

    Resource getTo();

    List getFromPaths();

    List getToPaths();

    boolean isFrom(Resource resource);

    boolean isTo(Resource resource);

    boolean isToOneRelationship(Resource resource);

    static  ResourceRelationship of(Resource from,
            Resource to, List fromPaths) {
        return new BasicResourceRelationship<>(from, to, fromPaths);
    }

    static String getRelationshipNameForToResource(ResourceRelationship relationship) {
        Resource to = relationship.getTo();
        Resource from = relationship.getFrom();
        if (relationship.isToOneRelationship(to)) {
            return from.getName();
        }
        return from.getPluralName();
    }

    /**
     * @param resource to get paths from
     * @return A list of *all* relationships defined from this resource, including nested objects
     */
    static List getAllRelationshipPaths(Resource resource) {
        return resource.getAllPaths().stream()
                .filter(path -> path.lastMappedField().isRelationship())
                .collect(Collectors.toList());
    }

    static RelationshipType converse(RelationshipType type, List fromPaths) {
        switch (type) {
            case manyToOne:
                return oneToMany;
            case oneToOne:
                // if there is more than one relationship then it may be to more than one
                // resource, thus even if it is oneToOne individually, overall it is oneToMany
                return fromPaths.size() == 1 ? type : oneToMany;
            case manyToMany:
                return type;
            case oneToMany:
                return manyToOne;
        }
        return null;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy