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

com.elepy.mongo.querybuilding.MongoSearch Maven / Gradle / Ivy

There is a newer version: 3.0.0-alpha-29
Show newest version
package com.elepy.mongo.querybuilding;

import com.elepy.annotations.Searchable;
import com.elepy.annotations.Unique;
import com.elepy.exceptions.ElepyConfigException;
import com.elepy.utils.ReflectionUtils;
import com.google.common.base.Strings;
import org.jongo.marshall.jackson.oid.MongoId;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class MongoSearch {

    private final String qry;
    private final Class cls;

    private String compiled;

    private List searchableFields;

    public MongoSearch(String qry, Class cls) {
        this.qry = qry;
        this.cls = cls;

        this.searchableFields = getSearchableFields();
    }

    public String getQuery() {
        return qry;
    }

    private List getSearchableFields() {
        List fields = ReflectionUtils.searchForFieldsWithAnnotation(cls, Searchable.class);

        fields.add(ReflectionUtils.getIdField(cls).orElseThrow(() -> new ElepyConfigException("No id field")));
        return fields;
    }

    public String compile() {
        if (compiled == null) {
            String searchRegex = searchableFields.stream()
                    .map(field -> String.format("{%s: {$regex: #, $options: 'i'}}", ReflectionUtils.getPropertyName(field)))
                    .collect(Collectors.joining(","));

            compiled = String.format("{$or: [%s]}", searchRegex);
        }
        return compiled;
    }

    public Serializable[] getParameters() {

        if (Strings.isNullOrEmpty(qry)) {
            return new Serializable[0];
        }
        return searchableFields.stream()
                .map(field -> Pattern.compile(".*" + qry + ".*", Pattern.CASE_INSENSITIVE).toString())
                .toArray(Serializable[]::new);

    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy