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

io.yawp.repository.features.Feature Maven / Gradle / Ivy

There is a newer version: 2.08alpha
Show newest version
package io.yawp.repository.features;

import io.yawp.commons.http.RequestContext;
import io.yawp.commons.utils.JsonUtils;
import io.yawp.commons.utils.ReflectionUtils;
import io.yawp.repository.IdRef;
import io.yawp.repository.Repository;
import io.yawp.repository.query.QueryBuilder;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Feature {

    protected Repository yawp;

    protected RequestContext requestContext;

    public void setRepository(Repository yawp) {
        this.yawp = yawp;
        this.requestContext = yawp.getRequestContext();
    }

    public  QueryBuilder yawp(Class clazz) {
        return yawp.query(clazz);
    }

    public  QueryBuilder yawpWithHooks(Class clazz) {
        return yawp.queryWithHooks(clazz);
    }

    public boolean isOnRequest() {
        return requestContext != null;
    }

    public  T feature(Class clazz) {
        try {
            T feature = clazz.newInstance();
            feature.setRepository(yawp);
            return feature;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public  IdRef id(Class clazz, Long id) {
        return IdRef.create(yawp, clazz, id);
    }

    public  IdRef id(Class clazz, String name) {
        return IdRef.create(yawp, clazz, name);
    }

    public IdRef id(String uri) {
        return IdRef.parse(yawp, uri);
    }


    public  T from(String json, Class clazz) {
        return JsonUtils.from(yawp, json, clazz);
    }

    public  List fromList(String json, Class clazz) {
        return JsonUtils.fromList(yawp, json, clazz);
    }

    public  Map fromMap(String json, Class keyClazz, Class valueClazz) {
        return JsonUtils.fromMap(yawp, json, keyClazz, valueClazz);
    }
    
    public String to(Object object) {
        return JsonUtils.to(object);
    }

    protected Map asMap(Object object) {
        try {
            Map map = new HashMap<>();
            List fields = ReflectionUtils.getFieldsRecursively(object.getClass());
            for (Field field : fields) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(object));
            }
            return map;
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy