spring 封装solr工具类解析

符号 阅读:219 2021-03-31 18:15:10 评论:0

 

第一步:项目依赖:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
	<modelVersion>4.0.0</modelVersion> 
	<parent> 
		<groupId>com.digipower</groupId> 
		<artifactId>digipower-ucas-core</artifactId> 
		<version>0.0.1-SNAPSHOT</version> 
	</parent> 
	<artifactId>digipower-ucas-core-solr</artifactId> 
 
 
	<!-- 集中定义管理依赖版本号 --> 
	<properties> 
		<solr-solrj.version>7.4.0</solr-solrj.version> 
	</properties> 
 
	<dependencies> 
		<dependency> 
			<groupId>com.digipower</groupId> 
			<artifactId>digipower-ucas-core-common</artifactId> 
			<version>0.0.1-SNAPSHOT</version> 
		</dependency> 
		<!--solr 依赖jar包 --> 
		<dependency> 
			<groupId>org.apache.solr</groupId> 
			<artifactId>solr-solrj</artifactId> 
			<version>${solr-solrj.version}</version> 
		</dependency> 
	</dependencies> 
</project>

第二步:solr 封装核心功能代码:

核心代码:

package com.**.ucas.solr.util; 
 
import java.io.IOException; 
import java.lang.reflect.Field; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.List; 
import java.util.Map; 
import org.apache.commons.lang3.StringUtils; 
import org.apache.solr.client.solrj.SolrQuery; 
import org.apache.solr.client.solrj.SolrServerException; 
import org.apache.solr.client.solrj.impl.HttpSolrClient; 
import org.apache.solr.client.solrj.response.QueryResponse; 
import org.apache.solr.client.solrj.response.UpdateResponse; 
import org.apache.solr.common.SolrDocument; 
import org.apache.solr.common.SolrDocumentList; 
import org.apache.solr.common.SolrInputDocument; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import com.**.ucas.common.exception.SolrIndexException; 
import com.**.ucas.common.reflect.ReflectionUtils; 
import com.**.ucas.solr.page.SolrPage; 
 
/** 
 *  
 * @ClassName: SolrUtil 
 * @Description: solr 工具类 
 * @author: **** -zzg 
 * @date: 2019年4月24日 下午5:12:53 
 *  
 * @Copyright: 2019 www.digipower.cn 注意:本内容仅限于深圳市****科技开发有限公司内部使用,禁止用于其他的商业目的 
 */ 
public class SolrUtil<T> { 
	// 日志集成 
	private final static Logger logger = LoggerFactory.getLogger(SolrUtil.class); 
	 
	// 排序类型 
	public static final String DESC = "desc"; 
	public static final String ASC = "asc"; 
	 
	// 页面最大值 
	private static final int MAX = 10000; 
	 
	// 文档主键值 
	private static final String SID = "sid";  
	 
	 
 
	private static HttpSolrClient solrClient = null; 
 
	public SolrUtil(String url) { 
		if (solrClient == null) { 
			HttpSolrClient.Builder builder = new HttpSolrClient.Builder(url); 
			solrClient = builder.withConnectionTimeout(10000).withSocketTimeout(60000).build(); 
		} 
	} 
	 
	/** 
     * 功能描述:新增索引(新增和修改) 
     * @param BaseSolrEntity solr 基础实体对象 
     */ 
    public void createIndex(T entity) { 
    	Field[] fields = ReflectionUtils.getAllFields(entity.getClass()); 
    	ArrayList<Field> list = new ArrayList<Field>(Arrays.asList(fields)); 
		 
    	SolrInputDocument doc = new SolrInputDocument(); 
		for (Field field : fields) { 
			doc.addField(field.getName(), ReflectionUtils.invokeGetterMethod(entity, field.getName())); 
		} 
 
		try { 
			solrClient.add(doc); 
			solrClient.commit(); 
		} catch (Exception e) { 
			logger.error(e.getMessage(), e); 
			throw new SolrIndexException(e.getMessage()); 
		} 
    } 
     
    /** 
     *  
     * @Title: createIndex    
     * @Description: 批量新增索引    
     * @param: @param list       
     * @return: void       
     * @throws 
     */ 
    public void createIndex(List<T> list){ 
    	if(list == null || list.size() <= 0){ 
    		logger.error("集合为空或集合不存在"); 
    		throw new SolrIndexException("集合为空或集合不存在"); 
    	} 
    	for(T entity : list){ 
    		this.createIndex(entity); 
    	} 
    } 
     
    /** 
     *  
     * @Title: deleteIndex    
     * @Description: 根据id批量删除指定索引 
     * @param: @param id       
     * @return: void       
     * @throws 
     */ 
    public int deleteIndex(List<String> ids){ 
    	int status = 0; 
    	if(ids == null || ids.size() <= 0){ 
    		return status; 
    	} 
    	try { 
    		UpdateResponse response = solrClient.deleteById(ids); 
    		status = response.getStatus(); 
			solrClient.commit(); 
		} catch (SolrServerException | IOException e) { 
			// TODO Auto-generated catch block 
			logger.error(e.getMessage(), e); 
			throw new SolrIndexException(e.getMessage()); 
		} 
    	return status; 
    } 
     
    /** 
     *  
     * @Title: deleteIndex    
     * @Description: 根据query批量删除关联索引 
     * @param: @param query       
     * @return: void       
     * @throws 
     */ 
    public int deleteIndex(String query){ 
    	int status= 0; 
    	if(StringUtils.isEmpty(query)){ 
    		return status; 
    	} 
    	try { 
    		UpdateResponse response = solrClient.deleteByQuery(query); 
    		status = response.getStatus(); 
    		solrClient.commit(); 
		} catch (SolrServerException | IOException e) { 
			// TODO Auto-generated catch block 
			logger.error(e.getMessage(), e); 
			throw new SolrIndexException(e.getMessage()); 
		} 
    	return status; 
    } 
     
    /** 
     * @throws IOException  
     * @throws SolrServerException  
     *  
     * @Title: search    
     * @Description: solr 检索查询  
     * @param:        
     * @return: void       
     * @throws 
     */ 
    public List<T> search(String query,  Class<?> entity, String sort, String order, Integer start, Integer row) throws Exception{ 
    	List<T> container = new ArrayList<T>(); 
    	 
    	SolrQuery solrQuery = new SolrQuery(); 
    	// 设置查询条件 
    	solrQuery.setQuery(query); 
    	// 设置查询属性 
    	StringBuilder builder = new StringBuilder(); 
    	Field[] fields = ReflectionUtils.getAllFields(entity.getClass()); 
    	for (Field field : fields) { 
    		builder.append(field.getName()).append(","); 
		} 
    	String field = builder.toString(); 
    	field = field.substring(0, field.length() -1); 
    	solrQuery.setFields(field); 
    	// 设置排序 
    	if(!StringUtils.isEmpty(sort)){ 
    		if(SolrUtil.DESC.equalsIgnoreCase(order)){ 
    			solrQuery.setSort(sort, SolrQuery.ORDER.desc);    			 
    		} 
    		if(SolrUtil.ASC.equalsIgnoreCase(order)){ 
    			solrQuery.setSort(sort, SolrQuery.ORDER.asc); 
    		} 
    	} 
    	// 设置查询页码和记录数 
    	if (start < 0) { 
    		start = 0; 
        } 
        if (start > MAX) { 
        	start = MAX; 
        } 
    	solrQuery.setStart(start); 
    	solrQuery.setRows(row < 0 ? 0 : row); 
    	 
    	 
    	// solr 检索 
    	QueryResponse response = solrClient.query(solrQuery); 
    	SolrDocumentList docs = response.getResults(); 
		if(null == docs || docs.size() == 0) { 
			return null; 
		} 
		for(SolrDocument doc : docs){ 
			T obj =  (T) entity.newInstance(); 
			ArrayList<Field> searchFields  = new ArrayList<Field>(Arrays.asList(ReflectionUtils.getAllFields(obj.getClass()))); 
			for (Field searchField : searchFields) { 
				String propertyName = searchField.getName(); 
				String propertyValue = (String) doc.getFieldValue(propertyName); 
				Class<?> propertyClass = searchField.getType(); 
				if(propertyClass.equals(Integer.class)) { 
					Integer value = Integer.valueOf(propertyValue); 
					ReflectionUtils.invokeSetterMethod(obj, propertyName, value); 
				} else { 
					ReflectionUtils.invokeSetterMethod(obj, propertyName, propertyValue); 
				} 
			} 
			container.add(obj); 
		} 
		return container; 
    } 
     
    /** 
     *  
     * @Title: searchPage    
     * @Description: solr 分页检索  
     * @param: @param query 
     * @param: @param entity 
     * @param: @param sort 
     * @param: @param order 
     * @param: @param solrPage 
     * @param: @return 
     * @param: @throws Exception       
     * @return: SolrPage<T>       
     * @throws 
     */ 
    public SolrPage<T> searchPage(String query,  Class<?> entity, String sort, String order,SolrPage<T> solrPage) throws Exception{ 
    	List<T> container = new ArrayList<T>(); 
    	SolrQuery solrQuery = new SolrQuery(); 
    	// 设置查询条件 
    	solrQuery.setQuery(query); 
    	// 设置查询属性 
    	StringBuilder builder = new StringBuilder(); 
    	Field[] fields = ReflectionUtils.getAllFields(entity.getClass()); 
    	for (Field field : fields) { 
    		builder.append(field.getName()).append(","); 
		} 
    	String field = builder.toString(); 
    	field = field.substring(0, field.length() -1); 
    	solrQuery.setFields(field); 
    	// 设置排序 
    	if(!StringUtils.isEmpty(sort)){ 
    		if(SolrUtil.DESC.equalsIgnoreCase(order)){ 
    			solrQuery.setSort(sort, SolrQuery.ORDER.desc);    			 
    		} 
    		if(SolrUtil.ASC.equalsIgnoreCase(order)){ 
    			solrQuery.setSort(sort, SolrQuery.ORDER.asc); 
    		} 
    	} 
    	// 设置查询页码和记录数 
    	int row = solrPage.getPageSize(); 
    	int size = solrPage.getCurrentPage(); 
    	if (size < 0) { 
    		size = 0; 
        } 
        if (size > MAX) { 
        	size = MAX; 
        } 
    	solrQuery.setStart(size); 
    	solrQuery.setRows(row < 0 ? 0 : row); 
    	 
    	 
    	// solr 检索 
    	QueryResponse response = solrClient.query(solrQuery); 
    	SolrDocumentList docs = response.getResults(); 
		if(null == docs || docs.size() == 0) { 
			return null; 
		} 
		for(SolrDocument doc : docs){ 
			T obj =  (T) entity.newInstance(); 
			ArrayList<Field> searchFields  = new ArrayList<Field>(Arrays.asList(ReflectionUtils.getAllFields(obj.getClass()))); 
			for (Field searchField : searchFields) { 
				String propertyName = searchField.getName(); 
				String propertyValue = (String) doc.getFieldValue(propertyName); 
				Class<?> propertyClass = searchField.getType(); 
				if(propertyClass.equals(Integer.class)) { 
					Integer value = Integer.valueOf(propertyValue); 
					ReflectionUtils.invokeSetterMethod(obj, propertyName, value); 
				} else { 
					ReflectionUtils.invokeSetterMethod(obj, propertyName, propertyValue); 
				} 
			} 
			container.add(obj); 
		} 
		return new SolrPage(solrQuery.getStart(),solrQuery.getRows(),(int)docs.getNumFound(), container); 
    } 
     
    /** 
     *  
     * @Title: searchPageHighlight    
     * @Description: solr 高亮分页查询    
     * @param: @return       
     * @return: SolrPage<T>       
     * @throws 
     */ 
    public SolrPage<T> searchPageHighlight(String query,  Class<?> entity, String sort, String order,SolrPage<T> solrPage, String highLight) throws Exception{ 
    	List<T> container = new ArrayList<T>(); 
    	SolrQuery solrQuery = new SolrQuery(); 
    	// 设置查询条件 
    	solrQuery.setQuery(query); 
    	// 设置查询属性 
    	StringBuilder builder = new StringBuilder(); 
    	Field[] fields = ReflectionUtils.getAllFields(entity.getClass()); 
    	for (Field field : fields) { 
    		builder.append(field.getName()).append(","); 
		} 
    	String field = builder.toString(); 
    	field = field.substring(0, field.length() -1); 
    	solrQuery.setFields(field); 
    	// 设置排序 
    	if(!StringUtils.isEmpty(sort)){ 
    		if(SolrUtil.DESC.equalsIgnoreCase(order)){ 
    			solrQuery.setSort(sort, SolrQuery.ORDER.desc);    			 
    		} 
    		if(SolrUtil.ASC.equalsIgnoreCase(order)){ 
    			solrQuery.setSort(sort, SolrQuery.ORDER.asc); 
    		} 
    	} 
    	// 设置查询页码和记录数 
    	int row = solrPage.getPageSize(); 
    	int size = solrPage.getCurrentPage(); 
    	if (size < 0) { 
    		size = 0; 
        } 
        if (size > MAX) { 
        	size = MAX; 
        } 
    	solrQuery.setStart(size); 
    	solrQuery.setRows(row < 0 ? 0 : row); 
    	 
    	// 高亮查询 
    	if(!StringUtils.isEmpty(highLight.trim())){ 
    		// 开启高亮提示 
    		solrQuery.setHighlight(true); 
    		// 设置高亮字段 
    		solrQuery.addHighlightField(highLight.trim()); 
    		// 设置高亮前缀 
    		solrQuery.setHighlightSimplePre("<font color='red'>"); 
    		// 设置高亮后缀 
    		solrQuery.setHighlightSimplePost("</font>"); 
    		 
    	} 
    	 
    	 
    	// solr 检索 
    	QueryResponse response = solrClient.query(solrQuery); 
    	SolrDocumentList docs = response.getResults(); 
		if(null == docs || docs.size() == 0) { 
			return null; 
		} 
		 
		// 获取高亮结果 
		Map<String, Map<String, List<String>>> highLightMap = null; 
		if(!StringUtils.isEmpty(highLight.trim())){ 
			highLightMap = response.getHighlighting(); 
		} 
		Map<String, List<String>> map = null; 
		 
		for(SolrDocument doc : docs){ 
			T obj =  (T) entity.newInstance(); 
			ArrayList<Field> searchFields  = new ArrayList<Field>(Arrays.asList(ReflectionUtils.getAllFields(obj.getClass()))); 
			for (Field searchField : searchFields) { 
				String propertyName = searchField.getName(); 
				String propertyValue = (String) doc.getFieldValue(propertyName); 
				Class<?> propertyClass = searchField.getType(); 
				// 高亮字段存在 
				if(!StringUtils.isEmpty(highLight.trim())){ 
					// 判断反射字段是否与高亮字段相等 
					if(propertyName.equalsIgnoreCase(highLight.trim()) && highLightMap != null){ 
						// 反射字段类型为Integer 不高亮显示 
						if(propertyClass.equals(Integer.class)) { 
							Integer value = Integer.valueOf(propertyValue); 
							ReflectionUtils.invokeSetterMethod(obj, propertyName, value); 
						// 放射字段类型为其他时,高亮显示 
						} else { 
							map = highLightMap.get(doc.getFieldValue(SID)); 
							String value = map.get(propertyName).get(0); 
							ReflectionUtils.invokeSetterMethod(obj, propertyName, value); 
						}	 
					// 判断反射字段是否与高亮字段不相等	 
					} else { 
						if(propertyClass.equals(Integer.class)) { 
							Integer value = Integer.valueOf(propertyValue); 
							ReflectionUtils.invokeSetterMethod(obj, propertyName, value); 
						} else { 
							ReflectionUtils.invokeSetterMethod(obj, propertyName, propertyValue); 
						}		 
					} 
				// 高亮字段不存在 
				} else { 
					if(propertyClass.equals(Integer.class)) { 
						Integer value = Integer.valueOf(propertyValue); 
						ReflectionUtils.invokeSetterMethod(obj, propertyName, value); 
					} else { 
						ReflectionUtils.invokeSetterMethod(obj, propertyName, propertyValue); 
					}					 
				} 
				 
				 
			} 
			container.add(obj); 
		} 
    	return new SolrPage(solrQuery.getStart(),solrQuery.getRows(),(int)docs.getNumFound(), container); 
    } 
} 

分页对象:

package com.****.ucas.solr.page; 
 
import java.util.List; 
 
/** 
 *  
 * @ClassName:  SolrPage    
 * @Description: solr 分页对象 
 * @author: **** -zzg 
 * @date:   2019年4月25日 上午10:51:03    
 *      
 * @Copyright: 2019 www.digipower.cn  
 * 注意:本内容仅限于深圳市****科技开发有限公司内部使用,禁止用于其他的商业目的 
 */ 
public class SolrPage<T> { 
	// 指定的或是页面参数 
    private int currentPage; // 当前页 
    private int pageSize; // 每页显示多少条 
 
    // 查询es结果 
    private int recordCount; // 总记录数 
    private List<T> recordList; // 本页的数据列表 
 
    // 计算 
    private int pageCount; // 总页数 
    private int beginPageIndex; // 页码列表的开始索引(包含) 
    private int endPageIndex; // 页码列表的结束索引(包含) 
 
    /** 
     * 只接受前4个必要的属性,会自动的计算出其他3个属性的值 
     * 
     * @param currentPage 
     * @param pageSize 
     * @param recordCount 
     * @param recordList 
     */ 
    public SolrPage(int currentPage, int pageSize, int recordCount, List<T> recordList) { 
        this.currentPage = currentPage; 
        this.pageSize = pageSize; 
        this.recordCount = recordCount; 
        this.recordList = recordList; 
 
        // 计算总页码 
        pageCount = (recordCount + pageSize - 1) / pageSize; 
 
        // 计算 beginPageIndex 和 endPageIndex 
        // >> 总页数不多于10页,则全部显示 
        if (pageCount <= 10) { 
            beginPageIndex = 1; 
            endPageIndex = pageCount; 
        } 
        // >> 总页数多于10页,则显示当前页附近的共10个页码 
        else { 
            // 当前页附近的共10个页码(前4个 + 当前页 + 后5个) 
            beginPageIndex = currentPage - 4; 
            endPageIndex = currentPage + 5; 
            // 当前面的页码不足4个时,则显示前10个页码 
            if (beginPageIndex < 1) { 
                beginPageIndex = 1; 
                endPageIndex = 10; 
            } 
            // 当后面的页码不足5个时,则显示后10个页码 
            if (endPageIndex > pageCount) { 
                endPageIndex = pageCount; 
                beginPageIndex = pageCount - 10 + 1; 
            } 
        } 
    } 
    // get 和   set 方法 
	public int getCurrentPage() { 
		return currentPage; 
	} 
 
	public void setCurrentPage(int currentPage) { 
		this.currentPage = currentPage; 
	} 
 
	public int getPageSize() { 
		return pageSize; 
	} 
 
	public void setPageSize(int pageSize) { 
		this.pageSize = pageSize; 
	} 
 
	public int getRecordCount() { 
		return recordCount; 
	} 
 
	public void setRecordCount(int recordCount) { 
		this.recordCount = recordCount; 
	} 
 
	public List<T> getRecordList() { 
		return recordList; 
	} 
 
	public void setRecordList(List<T> recordList) { 
		this.recordList = recordList; 
	} 
 
	public int getPageCount() { 
		return pageCount; 
	} 
 
	public void setPageCount(int pageCount) { 
		this.pageCount = pageCount; 
	} 
 
	public int getBeginPageIndex() { 
		return beginPageIndex; 
	} 
 
	public void setBeginPageIndex(int beginPageIndex) { 
		this.beginPageIndex = beginPageIndex; 
	} 
 
	public int getEndPageIndex() { 
		return endPageIndex; 
	} 
 
	public void setEndPageIndex(int endPageIndex) { 
		this.endPageIndex = endPageIndex; 
	} 
 
} 

反射工具类:

package com.****.ucas.common.reflect; 
 
import java.lang.reflect.Field; 
import java.lang.reflect.InvocationTargetException; 
import java.lang.reflect.Method; 
import java.lang.reflect.ParameterizedType; 
import java.lang.reflect.Type; 
import java.util.Comparator; 
import java.util.Set; 
import java.util.TreeSet; 
 
import org.apache.commons.lang.StringUtils; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.util.Assert; 
 
/** 
 *  
 * @ClassName: ReflectionUtils 
 * @Description: 反射工具类 
 * @author: **** -zzg 
 * @date: 2019年4月22日 下午4:51:02 
 *  
 * @Copyright: 2019 www.digipower.cn 注意:本内容仅限于深圳市****科技开发有限公司内部使用,禁止用于其他的商业目的 
 */ 
public class ReflectionUtils { 
 
	// 错误日志记录 
	private final static Logger logger = LoggerFactory.getLogger(ReflectionUtils.class); 
 
	/** 
	 * 调用Getter方法. 
	 */ 
	public static Object invokeGetterMethod(Object obj, String propertyName) { 
		String getterMethodName = "get" + StringUtils.capitalize(propertyName); 
		return invokeMethod(obj, getterMethodName, new Class[] {}, new Object[] {}); 
	} 
 
	/** 
	 * 调用Setter方法.使用value的Class来查找Setter方法. 
	 */ 
	public static void invokeSetterMethod(Object obj, String propertyName, Object value) { 
		invokeSetterMethod(obj, propertyName, value, null); 
	} 
 
	/** 
	 * 调用Setter方法. 
	 * 
	 * @param propertyType 
	 *            用于查找Setter方法,为空时使用value的Class替代. 
	 */ 
	public static void invokeSetterMethod(Object obj, String propertyName, Object value, Class<?> propertyType) { 
		Class<?> type = propertyType != null ? propertyType : value.getClass(); 
		String setterMethodName = "set" + StringUtils.capitalize(propertyName); 
		invokeMethod(obj, setterMethodName, new Class[] { type }, new Object[] { value }); 
	} 
 
	/** 
	 * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数. 
	 */ 
	public static Object getFieldValue(final Object obj, final String fieldName) { 
		Field field = getAccessibleField(obj, fieldName); 
 
		if (field == null) { 
			throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]"); 
		} 
 
		Object result = null; 
		try { 
			result = field.get(obj); 
		} catch (IllegalAccessException e) { 
			logger.error("不可能抛出的异常" + e.getMessage()); 
		} 
		return result; 
	} 
 
	/** 
	 * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数. 
	 */ 
	public static void setFieldValue(final Object obj, final String fieldName, final Object value) { 
		Field field = getAccessibleField(obj, fieldName); 
 
		if (field == null) { 
			throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]"); 
		} 
 
		try { 
			field.set(obj, value); 
		} catch (IllegalAccessException e) { 
			logger.error("不可能抛出的异常" + e.getMessage()); 
		} 
	} 
 
	/** 
	 * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问. 
	 * <p> 
	 * 如向上转型到Object仍无法找到, 返回null. 
	 */ 
	public static Field getAccessibleField(final Object obj, final String fieldName) { 
		Assert.notNull(obj, "object不能为空"); 
		Assert.hasText(fieldName, "fieldName"); 
		for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass 
				.getSuperclass()) { 
			try { 
				Field field = superClass.getDeclaredField(fieldName); 
				field.setAccessible(true); 
				return field; 
			} catch (NoSuchFieldException e) {// NOSONAR 
				// Field不在当前类定义,继续向上转型 
			} 
		} 
		return null; 
	} 
 
	/** 
	 * 直接调用对象方法, 无视private/protected修饰符. 用于一次性调用的情况. 
	 */ 
	public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes, 
			final Object[] args) { 
		Method method = getAccessibleMethod(obj, methodName, parameterTypes); 
		if (method == null) { 
			throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]"); 
		} 
 
		try { 
			return method.invoke(obj, args); 
		} catch (Exception e) { 
			throw convertReflectionExceptionToUnchecked(e); 
		} 
	} 
 
	/** 
	 * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. 如向上转型到Object仍无法找到, 返回null. 
	 * <p> 
	 * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... 
	 * args) 
	 */ 
	public static Method getAccessibleMethod(final Object obj, final String methodName, 
			final Class<?>... parameterTypes) { 
		Assert.notNull(obj, "object不能为空"); 
 
		for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass 
				.getSuperclass()) { 
			try { 
				Method method = superClass.getDeclaredMethod(methodName, parameterTypes); 
 
				method.setAccessible(true); 
 
				return method; 
 
			} catch (NoSuchMethodException e) {// NOSONAR 
				// Method不在当前类定义,继续向上转型 
			} 
		} 
		return null; 
	} 
 
	/** 
	 * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. 如无法找到, 返回Object.class. eg. public UserDao 
	 * extends HibernateDao<User> 
	 * 
	 * @param clazz 
	 *            The class to introspect 
	 * @return the first generic declaration, or Object.class if cannot be 
	 *         determined 
	 */ 
	@SuppressWarnings({ "unchecked", "rawtypes" }) 
	public static <T> Class<T> getSuperClassGenricType(final Class clazz) { 
		return getSuperClassGenricType(clazz, 0); 
	} 
 
	/** 
	 * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. 如无法找到, 返回Object.class. 
	 * <p> 
	 * 如public UserDao extends HibernateDao<User,Long> 
	 * 
	 * @param clazz 
	 *            clazz The class to introspect 
	 * @param index 
	 *            the Index of the generic ddeclaration,start from 0. 
	 * @return the index generic declaration, or Object.class if cannot be 
	 *         determined 
	 */ 
	@SuppressWarnings("rawtypes") 
	public static Class getSuperClassGenricType(final Class clazz, final int index) { 
 
		Type genType = clazz.getGenericSuperclass(); 
 
		if (!(genType instanceof ParameterizedType)) { 
			logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType"); 
			return Object.class; 
		} 
 
		Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); 
 
		if (index >= params.length || index < 0) { 
			logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " 
					+ params.length); 
			return Object.class; 
		} 
		if (!(params[index] instanceof Class)) { 
			logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter"); 
			return Object.class; 
		} 
 
		return (Class) params[index]; 
	} 
 
	/** 
	 * 将反射时的checked exception转换为unchecked exception. 
	 */ 
	public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) { 
		if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException 
				|| e instanceof NoSuchMethodException) { 
			return new IllegalArgumentException("Reflection Exception.", e); 
		} else if (e instanceof InvocationTargetException) { 
			return new RuntimeException("Reflection Exception.", ((InvocationTargetException) e).getTargetException()); 
		} else if (e instanceof RuntimeException) { 
			return (RuntimeException) e; 
		} 
		return new RuntimeException("Unexpected Checked Exception.", e); 
	} 
	 
	private static final Comparator<Field> FIELD_COMPARATOR = new Comparator<Field>() { 
        // 只需要去重,并且希望父类的field在返回数组中排在后面,所以比较全部返回1 
        @Override 
        public int compare(Field o1, Field o2) 
        { 
            if (o1.getName().equals(o2.getName())) 
            { 
                return 0; 
            } 
            else 
            { 
                return 1; 
            } 
        } 
    }; 
     
    /** 
     * 获取该类的所有field对象,如果子类重写了父类的field,则只包含子类的field 
     *  
     * @param entityClass 
     * @return 
     */ 
    public static Field[] getAllFields(Class<?> entityClass) 
    { 
        Set<Field> set = new TreeSet<Field>(FIELD_COMPARATOR); 
        while (entityClass != Object.class && entityClass != null) 
        { 
            for (Field each : entityClass.getDeclaredFields()) 
            { 
                set.add(each); 
            } 
            entityClass = entityClass.getSuperclass(); 
        } 
        return set.toArray(new Field[set.size()]); 
         
    } 
 
} 

异常类:

package com.****.ucas.common.exception; 
 
import org.apache.commons.lang.StringUtils; 
 
/** 
 *  
 * @ClassName:  BaseRuntimeException    
 * @Description: 基础异常封装--BaseRuntimeException  
 * @author: **** -zzg 
 * @date:   2019年4月22日 下午2:39:18    
 *      
 * @Copyright: 2019 www.digipower.cn  
 * 注意:本内容仅限于深圳市****科技开发有限公司内部使用,禁止用于其他的商业目的 
 */ 
public class BaseRuntimeException extends RuntimeException { 
	/**    
	 * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)    
	 */    
	private static final long serialVersionUID = 1L; 
	 
	 /** The code. */ 
    private String code; 
 
    /** The params. */ 
    private String[] params; 
 
    /** 
     * Gets the code. 
     *  
     * @return the code 
     */ 
    public String getCode() { 
        return code; 
    } 
 
    /** 
     * Sets the code. 
     *  
     * @param code 
     *            the new code 
     */ 
    public void setCode(String code) { 
        this.code = code; 
    } 
 
    /** 
     * Gets the params. 
     *  
     * @return the params 
     */ 
    public String[] getParams() { 
        return params; 
    } 
 
    /** 
     * Sets the params. 
     *  
     * @param params 
     *            the new params 
     */ 
    public void setParams(String[] params) { 
        this.params = params; 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     */ 
    public BaseRuntimeException() { 
        super(); 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     *  
     * @param message 
     *            the message 
     * @param e 
     *            the e 
     */ 
    public BaseRuntimeException(String message, Exception e) { 
        super(message, e); 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     *  
     * @param message 
     *            the message 
     */ 
    public BaseRuntimeException(String message) { 
        super(message); 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     *  
     * @param e 
     *            the e 
     */ 
    public BaseRuntimeException(Exception e) { 
        super(e); 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     *  
     * @param code 
     *            the code 
     * @param params 
     *            the params 
     */ 
    public BaseRuntimeException(String code, String[] params) { 
        super(code); 
        this.setCode(code); 
        this.setParams(params); 
    } 
 
    /** 
     * Instantiates a new base runtime exception. 
     *  
     * @param code 
     *            the code 
     * @param params 
     *            the params 
     * @param e 
     *            the e 
     */ 
    public BaseRuntimeException(String code, String[] params, Exception e) { 
        super(e); 
        this.setCode(code); 
        this.setParams(params); 
    } 
 
    /* 
     * (non-Javadoc) 
     *  
     * @see java.lang.Throwable#getMessage() 
     */ 
    @Override 
    public String getMessage() { 
        if (code == null || code.length() == 0) { 
            return super.getMessage(); 
        } 
         
        String paramsStr = "NA"; 
        if (params != null) { 
            paramsStr = StringUtils.join(params, ","); 
        } 
        String codeMessage = "code:" + code + ";parameters:" + paramsStr; 
        return codeMessage; 
    } 
 
    /* 
     * (non-Javadoc) 
     *  
     * @see java.lang.Throwable#toString() 
     */ 
    @Override 
    public String toString() { 
        String s = getClass().getName(); 
        String message = this.getMessage(); 
        return (message != null) ? (s + ": " + message) : s; 
    } 
 
} 
package com.****.ucas.common.exception; 
 
public class SolrIndexException extends BaseRuntimeException { 
 
	/**    
	 * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)    
	 */    
	private static final long serialVersionUID = 1L; 
	 
	public SolrIndexException(String message,Exception e){ 
		super(message,e); 
	} 
	 
	public SolrIndexException(String message){ 
		super(message); 
	} 
	 
 
} 
package com.****.ucas.common.exception; 
 
/** 
 *  
 * @ClassName:  SolrSearchException    
 * @Description: solr 检索异常    
 * @author: **** -zzg 
 * @date:   2019年4月25日 上午10:19:45    
 *      
 * @Copyright: 2019 www.digipower.cn  
 * 注意:本内容仅限于深圳市****科技开发有限公司内部使用,禁止用于其他的商业目的 
 */ 
public class SolrSearchException extends BaseRuntimeException { 
 
	/**    
	 * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)    
	 */    
	private static final long serialVersionUID = 1L; 
	 
	public SolrSearchException(String message,Exception e){ 
		super(message,e); 
	} 
	 
	public SolrSearchException(String message){ 
		super(message); 
	} 
 
} 

 

声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

发表评论
搜索
排行榜
KIKK导航

KIKK导航

关注我们