@Repository("adminDao")
public class AdminDaoImpl extends BaseDaoImpl<Admin> {

	public Admin isAdmin(String username, String password) {
		String hql = "FROM Admin WHERE username = ? AND password= ?";
		Admin admin = (Admin) getSession().createQuery(hql).setString(0, username)
				.setString(1, DataUtils.md5(password)).uniqueResult();
		return admin;
	}

	public Admin findAdminByUsername(String username) {
		String hql = "FROM Admin a where a.username = ?";
		return (Admin) this.uniqueResult(hql, username);
	}

} @Repository("commentDao")
public class CommentDaoImpl extends BaseDaoImpl<Comment> {

	public List<Comment> getViewNewsAllComment(Integer newsId) {
		String hql = "FROM Comment c WHERE c.news.id = ?";
		return this.findEntityByHQL(hql, newsId);
	}

	public void deleteCommentByNewsId(Integer id) {
		String hql = "FROM Comment c WHERE c.news.id = ?";
		List<Comment> comments = this.findEntityByHQL(hql, id);
		if (comments != null) {
			for (Comment comment : comments) {
				this.deleteEntity(comment);
			}
		}
	}

	public void deleteAllCommentByUserId(Integer id) {
		String hql = "FROM Comment c WHERE c.user.id = ?";
		List<Comment> list = this.findEntityByHQL(hql, id);
		if (list != null) {
			for (Comment comment : list) {
				this.deleteEntity(comment);
			}
		}
	}

} @Repository("newsDao")
public class NewsDaoImpl extends BaseDaoImpl<News> {

	public List<News> getAllNewsByNewsType(Integer typeId) {
		String hql = "FROM News n WHERE n.newsType.id = ?";
		return this.findEntityByHQL(hql, typeId);
	}

	public Page<News> listAllNotPassedNewsPage(int pageNo, int pageSize) {
		String hql = "FROM News n WHERE n.state.id != 1 ORDER BY n.createTime desc";
		String hql2 = "SELECT count(*) FROM News n WHERE n.state.id != 1";
		return this.listPage(hql, hql2, pageNo, pageSize);
	}

	public Page<News> listAllNewsPage(int pageNo, int pageSize) {
		String hql = "FROM News n ORDER BY n.createTime desc";
		String hql2 = "SELECT count(*) FROM News";
		return this.listPage(hql, hql2, pageNo, pageSize);
	}

	public Page<News> getNews(Integer id, int pageNo, int pageSize) {
		String hql = "FROM News n WHERE n.newsType.id = " + id
				+ " and n.state.id = 1 ORDER BY n.createTime DESC";
		String hql2 = "SELECT count(*) FROM News n WHERE n.newsType.id = " + id
				+ " and n.state.id = 1";
		return this.listPage(hql, hql2, pageNo, pageSize);
	}

	public List<News> geHotNews() {
		String hql = "FROM News n WHERE n.state.id = 1 ORDER BY n.count DESC, n.createTime DESC";
		return this.findLimitEntityByHQL(hql, 0, 10);
	}

	public List<News> getRecentNews(int id, int maxResult) {
		String hql = "FROM News n where n.newsType.id = ? and n.state.id = 1 ORDER BY n.createTime DESC";
		return this.findLimitEntityByHQL(hql, 0, maxResult, id);
	}
} @Repository("stateDao")
public class StateDaoImpl extends BaseDaoImpl<State> {

} @Repository("visitorCounterDao")
public class VisitorCounterDaoImpl extends BaseDaoImpl<VisitorCounter> {

	public void deleteCounterByNewsId(Integer id) {
		String hql = "FROM VisitorCounter v where v.news.id = ?";
		List<VisitorCounter> counters = this.findEntityByHQL(hql, id);
		if (counters != null) {
			for (VisitorCounter visitorCounter : counters) {
				this.deleteEntity(visitorCounter);
			}
		}
	}

	public void deleteCounterByUserId(Integer id) {
		String hql = "FROM VisitorCounter v where v.user.id = ?";
		List<VisitorCounter> counters = this.findEntityByHQL(hql, id);
		if (counters != null) {
			for (VisitorCounter visitorCounter : counters) {
				this.deleteEntity(visitorCounter);
			}
		}
	}

} public class News extends BaseEntity {

	private static final long serialVersionUID = 6136633977314509659L;
	// 标题
	private String title;
	// 关键词
	private String keyword;
	// 缩略图，用于轮播器
	private String thumbnail;
	// 作者
	private String author;
	// 来源
	private String source;
	// 正文
	private String content;
	// 创建时间
	private Date createTime = new Date();
	// 创建者
	private Admin admin;
	// 新闻栏目
	private NewsType newsType;
	// 状态
	private State state;
	// 访问次数
	private Integer count;

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public NewsType getNewsType() {
		return newsType;
	}

	public void setNewsType(NewsType newsType) {
		this.newsType = newsType;
	}

	public State getState() {
		return state;
	}

	public void setState(State state) {
		this.state = state;
	}

	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	public String getKeyword() {
		return keyword;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public Admin getAdmin() {
		return admin;
	}

	public void setAdmin(Admin admin) {
		this.admin = admin;
	}

	public Integer getCount() {
		return count;
	}

	public void setCount(Integer count) {
		this.count = count;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getSource() {
		return source;
	}

	public void setSource(String source) {
		this.source = source;
	}

	public String getThumbnail() {
		return thumbnail;
	}

	public void setThumbnail(String thumbnail) {
		this.thumbnail = thumbnail;
	}
} public class Page<T> extends BaseEntity {

	private static final long serialVersionUID = -5688752889754349099L;
	// µ±Ç°Ò³
	private int currentPage;
	// Ã¿Ò³¸ö¸öÊý
	private int pageSize;
	// ×ÜÌõÊý
	private int totalCount;
	// ×ÜÒ³Êý
	private int pageCount;
	// ÊµÌåÀà
	private List<T> list;

	public Page() {

	}

	public Page(int currentPage, int pageSize, int totalCount, List<T> list) {
		super();
		this.currentPage = currentPage;
		this.pageSize = pageSize;
		this.totalCount = totalCount;
		this.list = list;
	}

	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	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 <= 0 ? 10 : pageSize;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public List<T> getList() {
		return list;
	}

	public void setList(List<T> list) {
		this.list = list;
	}

} public class State extends BaseEntity{

	private static final long serialVersionUID = 5861527337652310418L;
	private String stateName;

	public String getStateName() {
		return stateName;
	}

	public void setStateName(String stateName) {
		this.stateName = stateName;
	}

} public class Admin extends BaseEntity {

	private static final long serialVersionUID = -2754043214810493011L;
	// ÓÃ»§Ãû
	private String username;
	// ÃÜÂë
	private String password;
	// Email
	private String email;
	// ÊÇ·ñÆôÓÃ
	private boolean enabled;
	// Á¬ÐøµÇÂ¼Ê§°Ü´ÎÊý
	private Integer loginFailureCount;
	// Ëø¶¨ÈÕÆÚ
	private Date lockedTime;
	// ×îºóµÇÂ¼ÈÕÆÚ
	private Date loginTime;
	// ×îºóµÇÂ¼IP
	private String ipAddress;
	// ´´½¨Ê±¼ä
	private Date createTime = new Date();
	// ÓµÓÐµÄÈ¨ÏÞ
	private Set<Role> roles = new HashSet<Role>();
	// È¨ÏÞ×ÜºÍ
	private long[] rightSum;

	public Integer getLoginFailureCount() {
		return loginFailureCount;
	}

	public void setLoginFailureCount(Integer loginFailureCount) {
		this.loginFailureCount = loginFailureCount;
	}

	public Date getLockedTime() {
		return lockedTime;
	}

	public void setLockedTime(Date lockedTime) {
		this.lockedTime = lockedTime;
	}

	public Date getLoginTime() {
		return loginTime;
	}

	public void setLoginTime(Date loginTime) {
		this.loginTime = loginTime;
	}

	public String getIpAddress() {
		return ipAddress;
	}

	public void setIpAddress(String ipAddress) {
		this.ipAddress = ipAddress;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	public long[] getRightSum() {
		return rightSum;
	}

	public void setRightSum(long[] rightSum) {
		this.rightSum = rightSum;
	}

	/**
	 * ÅÐ¶ÏÓÃ»§ÊÇ·ñ¾ßÓÐÖ¸¶¨È¨ÏÞ
	 */
	public boolean hasRight(Right r) {
		int pos = r.getRightPos();
		long code = r.getRightCode();
		return !((rightSum[pos] & code) == 0);
	}

	public Set<Role> getRoles() {
		return roles;
	}

	public void setRoles(Set<Role> roles) {
		this.roles = roles;
	}

	/**
	 * ¼ÆËãÓÃ»§È¨ÏÞ×ÜºÍ
	 */
	public void calculateRightSum() {
		int pos = 0;
		long code = 0;
		for (Role role : roles) {
			for (Right r : role.getRights()) {
				pos = r.getRightPos();
				code = r.getRightCode();
				rightSum[pos] = rightSum[pos] | code;
			}
		}
		// ÊÍ·Å×ÊÔ´
		roles = null;
	}

} public interface NewsService extends BaseService<News> {

	public News getViewNews(Integer id);

	public void deleteNews(Integer id);

	public void saveNews(News model, Integer adminId);

	public Page<News> listAllNewsPage(int pageNo, int pageSize);

	public Page<News> listAllNotPassedNewsPage(int pageNo, int pageSize);

	public Page<News> getNews(Integer id, int pageNo, int pageSize);

	public List<News> getHotNews();

	public List<News> getRecentNews(int id, int MaxResult);

	public void createNewsIndex(News model);

} @SuppressWarnings("deprecation")
public final class SearchIndexUtils {

	public static SearchIndexUtils Instance() {
		return new SearchIndexUtils();
	}

	private SearchIndexUtils() {

	}

	public int pageSize = WebConstant.PAGE_SIZE - 5;
	public int pageNo;

	/**
	 * ´´½¨Ë÷Òý
	 */
	public static void createIndex(News news) {

		Directory directory = null;
		Analyzer analyzer = null;
		IndexWriterConfig indexWriterConfig = null;
		IndexWriter indexWriter = null;
		Document document = null;
		Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			directory = FSDirectory.open(WebConstant.FILE_PATH);
			analyzer = new StandardAnalyzer();
			indexWriterConfig = new IndexWriterConfig(analyzer);
			indexWriter = new IndexWriter(directory, indexWriterConfig);
			document = new Document();
			document.add(new Field("id", news.getId() + "", Store.YES,
					Index.NO, TermVector.NO));
			document.add(new Field("title", news.getTitle(), Store.YES,
					Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS));
			document.add(new Field("content", news.getContent(), Store.YES,
					Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS));
			document.add(new Field("createTime", format.format(news
					.getCreateTime()), Field.Store.YES, Index.NO, TermVector.NO));
			indexWriter.addDocument(document);
			indexWriter.close();
		} catch (IOException e) {
			System.out.println("´´½¨Ë÷Òý³ö´í");
			e.printStackTrace();
		}
	}

	/**
	 * ËÑË÷Ë÷Òý
	 */
	public Page<News> searchIndex(String searchWhich, String keyword,
			boolean flag) {
		Directory directory = null;
		IndexReader reader = null;
		IndexSearcher searcher = null;
		Analyzer analyzer = null;
		TopDocs topDocs = null;
		int count = 0;
		ScoreDoc[] scoreDocs = null;
		int index = 0;
		Document document = null;
		Query query = null;
		QueryParser parser = null;
		TermQuery termQuery = null;
		Page<News> page = null;
		List<News> allNews = new ArrayList<News>();
		Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			directory = FSDirectory.open(WebConstant.FILE_PATH);
			reader = DirectoryReader.open(directory);
			searcher = new IndexSearcher(reader);
			if (flag) {
				termQuery = new TermQuery(new Term(searchWhich, keyword));
				SortField sortField = new SortField("createTime", Type.SCORE,
						false);
				topDocs = searcher.search(termQuery, 100, new Sort(sortField));
			} else {
				analyzer = new StandardAnalyzer();
				parser = new QueryParser(searchWhich, analyzer);
				query = parser.parse(keyword);
				SortField sortField = new SortField("createTime", Type.SCORE,
						false);
				topDocs = searcher.search(query, 100, new Sort(sortField));
			}
			count = topDocs.totalHits;
			System.out.println("ËÑË÷½á¹û×ÜÊý : " + count);
			scoreDocs = topDocs.scoreDocs;
			// ²éÑ¯ÆðÊ¼¼ÇÂ¼Î»ÖÃ
			int begin = pageSize * (pageNo - 1);
			// ²éÑ¯ÖÕÖ¹¼ÇÂ¼Î»ÖÃ
			int end = Math.min(begin + pageSize, scoreDocs.length);
			for (int i = begin; i < end; i++) {
				News news = new News();
				index = scoreDocs[i].doc;
				document = searcher.doc(index);
				String id = document.get("id");
				String title = document.get("title");
				String content = document.get("content");
				String createTime = document.get("createTime");
				SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter(
						"<b><font color='red'>", "</font></b>");
				// ¸ßÁÁ¶ÔÏó
				Highlighter highlighter = new Highlighter(simpleHTMLFormatter,
						new QueryScorer(query));
				if (searchWhich.equals("title")) {
					String bestFragment = highlighter.getBestFragment(analyzer,
							searchWhich, title);
					// »ñµÃ¸ßÁÁºóµÄ±êÌâÄÚÈÝ
					news.setTitle(bestFragment);
					// Èç¹ûÄÚÈÝ²»×ã150¸ö×Ö£¬È«²¿ÉèÖÃ
					if (content.length() < 150) {
						news.setContent(content);
					} else {
						// Èç¹ûÄÚÈÝ¶àÓÚ150¸ö×Ö£¬Ö»È¡³öÇ°Ãæ150¸ö×Ö
						news.setContent(StringUtils.getDescString(content, 150)
								+ "...");
					}
				} else {
					// Èç¹û²éÑ¯µÄÊÇÄÚÈÝ×Ö¶Î
					String bestFragment = highlighter.getBestFragment(analyzer,
							searchWhich, content);
					// È¡µÃ¸ßÁÁÄÚÈÝ²¢ÉèÖÃ
					news.setContent(bestFragment + "...");
					// ÉèÖÃ±êÌâ£¬È«²¿ÉèÖÃ
					news.setTitle(title);
				}
				news.setId(Integer.parseInt(id));
				news.setCreateTime((Date) format.parseObject(createTime));
				allNews.add(news);
			}
			reader.close();
			page = new Page<News>(pageNo, pageSize, count, allNews);
			if (count == 0) {
				page.setPageCount(1);
			} else {
				if (count % pageSize == 0) {
					page.setPageCount(count / pageSize);
				} else {
					page.setPageCount(count / pageSize + 1);
				}
			}
		} catch (IOException | ParseException | InvalidTokenOffsetsException
				| java.text.ParseException e) {
			System.out.println("ËÑË÷Ë÷Òý³ö´í");
			e.printStackTrace();
		}
		return page;
	}
}
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import com.cjlu.newspublish.daos.impl.AdminDaoImpl;
import com.cjlu.newspublish.daos.impl.CommentDaoImpl;
import com.cjlu.newspublish.daos.impl.NewsDaoImpl;
import com.cjlu.newspublish.daos.impl.StateDaoImpl;
import com.cjlu.newspublish.daos.impl.VisitorCounterDaoImpl;
import com.cjlu.newspublish.models.News;
import com.cjlu.newspublish.models.Page;
import com.cjlu.newspublish.models.State;
import com.cjlu.newspublish.models.security.Admin;
import com.cjlu.newspublish.services.NewsService;
import com.cjlu.newspublish.utils.SearchIndexUtils;
package com.cjlu.newspublish.services.impl;




@Service("newsService")
public class NewsServiceImpl extends BaseServiceImpl<News> implements
		NewsService {

	@Autowired
	private NewsDaoImpl newsDao;
	@Autowired
	private CommentDaoImpl commentDao;
	@Autowired
	private AdminDaoImpl adminDao;
	@Autowired
	private VisitorCounterDaoImpl visitorCounterDao;