SolrUtils--自定义solrUtils

package com.cn.solr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cn.admin.entity.User;
import com.cn.event.entity.Event;
import com.cn.event.entity.SolrEvent;
import com.cn.event.entity.SolrScanningEvent;
import com.cn.util.auth.DataUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Quentin on 2017/4/6.
 */
public class SolrUtils {

    private static Logger logger = Logger.getLogger(SolrUtils.class);

    public static Map getSearchProperty(Object model)
            throws NoSuchMethodException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        Map resultMap = new TreeMap();
        // 获取实体类的所有属性,返回Field数组
        Field[] field = model.getClass().getDeclaredFields();
        for (int i = 0; i < field.length; i++) { // 遍历所有属性
            String name = field[i].getName(); // 获取属性的名字
            // 获取属性的类型
            String type = field[i].getGenericType().toString();
            //logger.info(type);
            if (type.equals("class java.lang.String")) { // 如果type是类类型,则前面包含"class ",后面跟类名
                Method m = model.getClass().getMethod(
                        "get" + UpperCaseField(name));
                String value = (String) m.invoke(model); // 调用getter方法获取属性值
                if (value != null) {
                    resultMap.put(name, value);
                }
            }
        }
        return resultMap;
    }

    // 转化字段首字母为大写
    private static String UpperCaseField(String fieldName) {
        fieldName = fieldName.replaceFirst(fieldName.substring(0, 1), fieldName
                .substring(0, 1).toUpperCase());
        return fieldName;
    }

    /**
     * 将Map按属性添加至document
     * @param map
     * @return
     */
    public static SolrInputDocument addFileds(Map map, SolrInputDocument document){

        if(document == null){
            document = new SolrInputDocument();
        }
        Iterator iterator = map.keySet().iterator();
        while (iterator.hasNext()){
            String key = iterator.next().toString();
            document.setField(key,map.get(key));
        }
        return document;
    }

    /**
     * 将SolrDocument 转换为Bean
     * @param record
     * @param clazz
     * @return bean
     */
    public static Object toBean(SolrDocument record, Class clazz){
        Object obj = null;
        try {
            obj = clazz.newInstance();
        } catch (InstantiationException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        }
        Field[] fields = clazz.getDeclaredFields();
        for(Field field:fields){
            Object value = record.get(field.getName());
            try {
                BeanUtils.setProperty(obj, field.getName(), value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return obj;
    }

    /**
     *  solrDocument 转为 jsonObject
     * @param solrDocument
     * @return jsonObject
     */

    public static JSONObject solrDocument2Json(SolrDocument solrDocument){
        JSONObject jsonObject = new JSONObject();
        Collection fieldNames = solrDocument.getFieldNames();
        for(String field:fieldNames){
            jsonObject.put(field, solrDocument.get(field));
            //System.out.println(field + ":"+solrDocument.get(field));
        }
        return jsonObject;
    }
    public static SolrEvent solrDataToEntity(SolrDocument solrDocument){
        SolrEvent solrEvent= new SolrEvent();
            Class aClass =solrEvent.getClass();
            Collection fieldNames = solrDocument.getFieldNames();
            for(String field:fieldNames){
        try {
                Field f =aClass.getDeclaredField(field);
                //noinspection unchecked
                Method method = aClass.getDeclaredMethod("set" + StringUtils.capitalize(field), f.getType());
                method.invoke(solrEvent,solrDocument.get(field));
        } catch (Exception e) {
            e.printStackTrace();
        }
            }
        return solrEvent;
    }
    public static Object[] solrDataToArray(SolrDocument solrDocument, String[] split){
            Collection fieldNames = solrDocument.getFieldNames();
            if (CollectionUtils.isEmpty(fieldNames))return null;
            Object [] objects = new Object[split.length];
            for (int i = 0; i < split.length; i++) {
                objects[i] = solrDocument.get(split[i]);
            }
        return objects;
    }
    /**
     *  solr查询结果转换为Json
     * @param solrDocumentList
     * @return JSONArray  结果转为jsonArray
     */
    public static JSONArray solrDocumentList2Json(SolrDocumentList solrDocumentList){
        JSONArray jsonArray = new JSONArray();

        for(org.apache.solr.common.SolrDocument solrDocument:solrDocumentList){
            JSONObject jsonObject = solrDocument2Json(solrDocument);
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    /**
     * solr查询结果转换为Map
     * @param solrDocumentList
     * @return Map
     *     count :符合查询条件的总数
     *     list :当前返回的结果集 jsonArray
     */

    public static Map solrDocumentList2Map(SolrDocumentList solrDocumentList){
           Map oMap = new HashMap();
           oMap.put("count",solrDocumentList.getNumFound());
           JSONArray jsonArray = new JSONArray();

         for(org.apache.solr.common.SolrDocument solrDocument:solrDocumentList){
            JSONObject jsonObject = solrDocument2Json(solrDocument);
            jsonArray.add(jsonObject);
         }

          oMap.put("list",jsonArray);

          return oMap;

    }

    public static List  toBeanList(SolrDocumentList records, Class  clazz){
        List list = new ArrayList();
        for(SolrDocument record : records){
            list.add(toBean(record,clazz));
        }
        return list;
    }
    public static void toBeans(){
       // MapSolrParams.toMap();
    }

    public   static  SolrInputDocument  entity2SolrInputDocument(Object obj){
        if(obj!=null){
            Class cls=obj.getClass();
            Field[] filedArrays = cls.getDeclaredFields();
            //获取类中所有属性
            Method m = null;
            SolrInputDocument sid=new SolrInputDocument();
            for(Field f:filedArrays){
                //因为如果对象序列化之后,会增加该属性,不用对该属性进行反射
                if(!f.getName().equals("serialVersionUID")){
                    try{
                        //跟进属性xx构造对应的getXx()方法
                        String dynamicGetMethod=dynamicMethodName(f.getName(),"get");
                        //调用构造的getXx()方法
                        m=cls.getMethod(dynamicGetMethod);
                        //属性名,与对应的属性值get方法获取到的值
                      // System.out.println(f.getName() + ":" + m.invoke(obj));
                        sid.addField(""+f.getName(),m.invoke(obj));
                    }catch(IllegalArgumentException e){
                        e.printStackTrace();
                    }catch(IllegalAccessException e){
                        e.printStackTrace();
                    }catch(SecurityException e){
                        e.printStackTrace();
                    }catch(InvocationTargetException e){
                        e.printStackTrace();
                    }catch(NoSuchMethodException e){
                        e.printStackTrace();
                    }
                }
            }
            return sid;
        }
        logger.info("Object to convert is null.");
        return null;
    }

    public static String dynamicMethodName(String name, String method) {
        String prop = Character.toUpperCase(name.charAt(0)) + name.substring(1);
        String mname = method + prop;
        return mname;
    }

    public static SolrQuery setQueryFile(Event event,User user){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(event);
        SolrQuery query = new SolrQuery();
        StringBuffer sb = new StringBuffer();
        sb.append("discoverTime:["+sdf.format(jsonObject.getDate("reportTimeBegin"))+" TO " + sdf.format(jsonObject.getDate("reportTimeEnd"))+"]");
        jsonObject.remove("reportTimeBegin");
        jsonObject.remove("reportTimeEnd");

        boolean flag = false;
        if ((event.getIsUrge() != null || event.getEventState() != null)) flag = true;

        query.setQuery(sb.toString());

        if(flag){
            sb.append(" AND currentHandleUserName:" + user.getUsername());
        }else{
            sb.append(" AND belongOrgFullPath:" + event.getBelongOrgFullPath()+"*");
        }
        jsonObject.remove("isUrge");

        Map map = DataUtils.json2Map(jsonObject.toJSONString());




        Iterator entries = map.entrySet().iterator();

        while (entries.hasNext()) {

            Map.Entry entry = (Map.Entry) entries.next();

            sb.append(" AND "+entry.getKey().toString() + ":").append(entry.getValue());

        }



       /* if(jsonObject.containsKey("userId")){
                sb.append(" AND userId:" + event.getUserId());
        }
        if(jsonObject.containsKey("eventState")){
            sb.append(" AND eventState:" + event.getEventState());
        }
        if(jsonObject.containsKey("isUserTag")){
            sb.append(" AND isUserTag:" + event.getIsUserTag());
        }
*/

        query.setQuery("discoverTime:["+sdf.format(jsonObject.getDate("reportTimeBegin"))+" TO " + sdf.format(jsonObject.getDate("reportTimeEnd"))+"]");
         return query;
    }






    public static void main(String... args){
        Event event = new Event();
        event.setId("123");
        event.setCreateTime(new Date());
        event.setCurrentHandleUserName("test");
        /*SolrInputDocument solrInput = entity2SolrInputDocument(event);
        System.out.println(solrInput);*/
        try {
            Map map = getSearchProperty(event);
            logger.info(map);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public static SolrInputDocument jsonToSolrInputDocuemnt(SolrEvent solrEvent) {
        JSONObject json = (JSONObject) JSON.toJSON(solrEvent);
        return solrInputDocJSON(json);
    }

    public static SolrInputDocument jsonToSolrInputDocuemnt(SolrScanningEvent solrEvent) {
        JSONObject json = (JSONObject) JSON.toJSON(solrEvent);
        return solrInputDocJSON(json);
    }

    public static SolrInputDocument solrInputDocJSON(JSONObject json) {
        SolrInputDocument doc = new SolrInputDocument();
        for (String s : json.keySet()) {
            doc.addField(s,json.get(s));
        }
        return doc;
    }
}

你可能感兴趣的:(java后台)