001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.messageboards.util;
016    
017    import com.liferay.portal.kernel.search.Document;
018    import com.liferay.portal.kernel.search.Hits;
019    import com.liferay.portal.kernel.util.GetterUtil;
020    import com.liferay.portal.kernel.util.Time;
021    
022    import java.util.ArrayList;
023    import java.util.HashSet;
024    import java.util.List;
025    import java.util.Set;
026    
027    /**
028     * @author Brian Wing Shun Chan
029     */
030    public class ThreadHits {
031    
032            public void recordHits(Hits hits, int start, int end) throws Exception {
033                    Set<Long> threadIds = new HashSet<Long>();
034    
035                    List<Document> docs = new ArrayList<Document>();
036                    List<Float> scores = new ArrayList<Float>();
037    
038                    for (int i = 0; i < hits.getLength(); i++) {
039                            Document doc = hits.doc(i);
040    
041                            Long threadId = GetterUtil.getLong(doc.get("threadId"));
042    
043                            if (!threadIds.contains(threadId)) {
044                                    threadIds.add(threadId);
045    
046                                    docs.add(hits.doc(i));
047                                    scores.add(hits.score(i));
048                            }
049                    }
050    
051                    int length = docs.size();
052    
053                    hits.setLength(length);
054    
055                    if (end > length) {
056                            end = length;
057                    }
058    
059                    docs = docs.subList(start, end);
060    
061                    hits.setDocs(docs.toArray(new Document[docs.size()]));
062                    hits.setScores(scores.toArray(new Float[docs.size()]));
063    
064                    hits.setSearchTime(
065                            (float)(System.currentTimeMillis() - hits.getStart()) /
066                                    Time.SECOND);
067            }
068    
069    }