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

com.github.hal4j.resources.GenericResource Maven / Gradle / Ivy

There is a newer version: 1.1.0
Show newest version
package com.github.hal4j.resources;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public final class GenericResource extends ResourceSupport {

    public final Map model;

    public GenericResource(Map model,
                           Map> _links,
                           Map> _embedded,
                           BindingContext ctx) {
        super(_links, _embedded, ctx);
        this.model = model != null ? Collections.unmodifiableMap(model) : null;
    }

    public GenericResource(Map model,
                           Map> _links,
                           Map> _embedded) {
        this(model, _links, _embedded, null);
    }

    public GenericResource(Map> _links,
                           Map> _attachments) {
        this(null, _links, _attachments, null);
    }

    public  Resource as(Class clazz) {
        T instance = context().bind(this.model, clazz);
        return new Resource<>(this, instance);
    }

    @SuppressWarnings("unchecked")
    public  Resources asCollectionOf(Class clazz) {
        List attachment = this.embedded().findAll(HALLink.REL_ITEMS);
        List> resources = attachment.stream()
                .map(object -> context().bind(object, GenericResource.class))
                .map(resource -> resource.as(clazz))
                .collect(Collectors.toList());

        return new Resources(this.links().asIs(), this.embedded().asIs(), (Class) Resource.class, resources, context());
    }

    public  Stream> asStreamOf(Class clazz) {
        return asCollectionOf(clazz).stream();
    }

    public NavigationResource asRoot() {
        return new NavigationResource(this.links().asIs(), this.embedded().asIs());
    }

    public Map get() {
        return this.model;
    }
}