Skip to content

Instantly share code, notes, and snippets.

@SergioLarios
Created April 26, 2017 09:58
Show Gist options
  • Save SergioLarios/50e4e8de1490ea5179d772ad1013cc4c to your computer and use it in GitHub Desktop.
Save SergioLarios/50e4e8de1490ea5179d772ad1013cc4c to your computer and use it in GitHub Desktop.
package com.vass.index;
import com.liferay.portal.kernel.language.LanguageUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.search.BooleanClause;
import com.liferay.portal.kernel.search.BooleanClauseFactoryUtil;
import com.liferay.portal.kernel.search.BooleanClauseOccur;
import com.liferay.portal.kernel.search.BooleanQuery;
import com.liferay.portal.kernel.search.BooleanQueryFactoryUtil;
import com.liferay.portal.kernel.search.Document;
import com.liferay.portal.kernel.search.Hits;
import com.liferay.portal.kernel.search.Indexer;
import com.liferay.portal.kernel.search.IndexerRegistryUtil;
import com.liferay.portal.kernel.search.QueryConfig;
import com.liferay.portal.kernel.search.SearchContext;
import com.liferay.portal.kernel.search.Sort;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.workflow.WorkflowConstants;
import com.liferay.portlet.asset.model.AssetCategory;
import com.liferay.portlet.asset.service.AssetCategoryLocalServiceUtil;
import com.liferay.portlet.dynamicdatamapping.util.DDMIndexerUtil;
import com.liferay.portlet.journal.NoSuchArticleException;
import com.liferay.portlet.journal.model.JournalArticle;
import com.liferay.portlet.journal.service.JournalArticleLocalServiceUtil;
import com.vass.contents.ContentParserUtils;
import com.vass.contents.StructureUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
public class SearchUtils {
private static Log _log = LogFactoryUtil.getLog(SearchUtils.class);
/* ************************
* *** Public methods *****
* ********************** */
// Custom serach
public static SearchPagi customSearch(SearchParams prms) throws Exception {
return search(generateSc(prms).getSearchContext(), prms);
}
public static SearchParams generateSc(SearchParams prms) {
if (Validator.isNotNull(prms.getSearchContext())) {
return prms;
}
SearchContext sc = new SearchContext();
sc.setCompanyId(prms.getCompanyId());
sc.setGroupIds(new long[] { prms.getGroupId() });
sc.setLocale(prms.getLocale());
sc.setUserId(prms.getUserId());
QueryConfig queryConfig = new QueryConfig();
queryConfig.setLocale(prms.getLocale());
sc.setQueryConfig(queryConfig);
if (Validator.isNull(prms.getStart()) && Validator.isNull(prms.getEnd())) {
if (Validator.isNull(prms.getPage()) && Validator.isNull(prms.getDelta())) {
prms.setStart(0);
prms.setEnd(10);
prms.setPage(0);
prms.setDelta(10);
}
else {
prms.setStart(prms.getPage() * prms.getDelta());
prms.setEnd(prms.getPage() * prms.getDelta() + prms.getPage() -1);
}
}
else if (Validator.isNull(prms.getDelta()) && Validator.isNull(prms.getPage())){
prms.setDelta(prms.getEnd() - prms.getStart() +1);
prms.setPage(prms.getStart() / prms.getDelta());
}
if (prms.getStart() > NO_PAGI && prms.getEnd() > NO_PAGI) {
sc.setAttribute(PAGI_TYPE, MORE);
sc.setStart(prms.getStart());
sc.setEnd(prms.getEnd());
}
prms.setSearchContext(sc);
return prms;
}
// Search for mobile
public static SearchPagi search(long userId, TimeZone timezone, Locale locale,
long groupdId, long companyId, List<Long> structuresId, String query, int start, int end,
int delta, int page, String langId) throws Exception{
SearchParams prms = new SearchParams(userId, timezone, locale, groupdId, companyId,
structuresId, query, start, end, delta, page, langId);
return search(generateSc(prms).getSearchContext(), prms);
}
// Category search
public static List<AssetCategory> searchCategoriesByName(long companyId, long groupId, List<Long> vocabularyIds,
Locale locale, String query) throws Exception {
// Setting query metadata
List<AssetCategory> result = new ArrayList<>();
QueryConfig queryConfig = new QueryConfig();
queryConfig.setLocale(locale);
SearchContext sc = new SearchContext();
sc.setCompanyId(companyId);
sc.setGroupIds(new long[] { groupId });
sc.setLocale(locale);
sc.setQueryConfig(queryConfig);
Indexer indexer = IndexerRegistryUtil.getIndexer(AssetCategory.class.getName());
// Setting search fields
BooleanQuery booleanQuery = null;
List<BooleanQuery> bqs = new ArrayList<>();
booleanQuery = BooleanQueryFactoryUtil.create(sc);
booleanQuery.addTerm(AC_TITLE, query, false);
bqs.add(booleanQuery);
booleanQuery = BooleanQueryFactoryUtil.create(sc);
booleanQuery.addTerm(AC_TITLE + StringPool.UNDERLINE + LanguageUtil.getLanguageId(locale), query, false);
bqs.add(booleanQuery);
// Search
BooleanQuery innerBooleanQuery = BooleanQueryFactoryUtil.create(sc);
for (BooleanQuery bq : bqs) {
innerBooleanQuery.add(bq, BooleanClauseOccur.SHOULD);
}
BooleanClause booleanClauseGeneral = BooleanClauseFactoryUtil.create(sc, innerBooleanQuery,
BooleanClauseOccur.MUST.getName());
sc.setBooleanClauses(new BooleanClause[] { booleanClauseGeneral });
sc.setAndSearch(false);
// Conversion to asset category
Hits hits = indexer.search(sc);
for (Document doc : hits.getDocs()) {
long catId = GetterUtil.getLong(doc.getField(AC_ID).getValue());
result.add(AssetCategoryLocalServiceUtil.getAssetCategory(catId));
}
return result;
}
public static int getPage(int start, int delta) {
return (start > 0) ? start / delta : 0;
}
/* ************************
* *** Private methods ****
* ********************** */
private static SearchPagi search(SearchContext sc, SearchParams prms) throws Exception {
Indexer indexer = IndexerRegistryUtil.getIndexer(JournalArticle.class.getName());
List<BooleanClause> finalClauses = new ArrayList<>();
List<BooleanQuery> bqs = new ArrayList<>();
// Search terms
if (!Validator.isBlank(prms.getQuery())){
for (Long structureId : prms.getStrcIds()) {
List<String> ifn = ContentParserUtils.getStructureFieldNames(structureId);
for (String fieldName : ifn) {
String structureFieldName = DDMIndexerUtil.encodeName(structureId, fieldName,
prms.getLocale());
BooleanQuery booleanQuery = BooleanQueryFactoryUtil.create(sc);
booleanQuery.addTerm(structureFieldName, prms.getQuery(), false);
bqs.add(booleanQuery);
}
}
}
if (Validator.isNotNull(prms.getCategoryNames())) {
for (String catStr : prms.getCategoryNames()) {
BooleanQuery booleanQuery = BooleanQueryFactoryUtil.create(sc);
booleanQuery.addTerm(JA_CATEGORY_TITLE, catStr);
bqs.add(booleanQuery);
}
}
if (Validator.isNotNull(prms.getTagNames())) {
for (String tagName : prms.getTagNames()) {
BooleanQuery booleanQuery = BooleanQueryFactoryUtil.create(sc);
booleanQuery.addTerm(JA_TAG_NAME, tagName);
bqs.add(booleanQuery);
}
}
if (bqs.size()>0){
BooleanQuery innerBooleanQuery = BooleanQueryFactoryUtil.create(sc);
for (BooleanQuery booleanQuery : bqs) {
innerBooleanQuery.add(booleanQuery, BooleanClauseOccur.SHOULD);
}
BooleanClause booleanClauseGeneral = BooleanClauseFactoryUtil.create(sc, innerBooleanQuery,
BooleanClauseOccur.MUST.getName());
finalClauses.add(booleanClauseGeneral);
}
// Must have any of category ids
if (Validator.isNotNull(prms.getCategoyList()) && prms.getCategoyList().size() > 0) {
List<BooleanQuery> catIdBq = new ArrayList<>();
for (Long catId : prms.getCategoyList()) {
BooleanQuery booleanQuery = BooleanQueryFactoryUtil.create(sc);
booleanQuery.addTerm(JA_CATEGORY_ID, catId);
catIdBq.add(booleanQuery);
}
BooleanQuery innerBooleanCatIdQuery = BooleanQueryFactoryUtil.create(sc);
for (BooleanQuery booleanQuery : catIdBq) {
innerBooleanCatIdQuery.add(booleanQuery, BooleanClauseOccur.SHOULD);
}
BooleanClause booleanClauseCatId= BooleanClauseFactoryUtil.create(sc,
innerBooleanCatIdQuery, BooleanClauseOccur.MUST.getName());
finalClauses.add(booleanClauseCatId);
}
// Additional querys
if (Validator.isNotNull(prms.getBooleanQrs()) && prms.getBooleanQrs().size() > 0) {
for (BooleanQuery booleanQuery : prms.getBooleanQrs()) {
finalClauses.add(BooleanClauseFactoryUtil.create(sc, booleanQuery,
BooleanClauseOccur.MUST.getName()));
}
}
// Force structures
List<BooleanQuery> bqsts = new ArrayList<>();
for (Long strId : prms.getStrcIds()) {
String strKey = StructureUtils.getStructureKey(strId);
if (Validator.isNotNull(strKey)) {
BooleanQuery booleanQuery = BooleanQueryFactoryUtil.create(sc);
booleanQuery.addTerm(JA_DDM_STRC_KEY, strKey);
bqsts.add(booleanQuery);
}
}
BooleanQuery strcaQuery = BooleanQueryFactoryUtil.create(sc);
for (BooleanQuery booleanQuery : bqsts) {
strcaQuery.add(booleanQuery, BooleanClauseOccur.SHOULD);
}
BooleanClause booleanStrcsClause = BooleanClauseFactoryUtil.create(sc, strcaQuery,
BooleanClauseOccur.MUST.getName());
finalClauses.add(booleanStrcsClause);
// ArticleId Excludes
if (Validator.isNotNull(prms.getArticleIdsExclude()) && prms.getArticleIdsExclude().size() > 0) {
for (String articleId : prms.getArticleIdsExclude()) {
BooleanQuery exBq = BooleanQueryFactoryUtil.create(sc);
exBq.addExactTerm(ARTICLE_ID, articleId);
finalClauses.add( BooleanClauseFactoryUtil.create(sc, exBq,
BooleanClauseOccur.MUST_NOT.getName()));
}
}
// Workflow status : Approved
BooleanQuery wsApproved = BooleanQueryFactoryUtil.create(sc);
wsApproved.addExactTerm(STATUS, WorkflowConstants.STATUS_APPROVED);
finalClauses.add( BooleanClauseFactoryUtil.create(sc, wsApproved,
BooleanClauseOccur.MUST.getName()));
// Final query
sc.setBooleanClauses(finalClauses.toArray( new BooleanClause[] {}));
sc.setAndSearch(false);
if (Validator.isNotNull(prms.getSort())) {
sc.setSorts(prms.getSort().toArray(new Sort[] {}));
}
Hits hits = indexer.search(sc);
List<JournalArticle> jas = new ArrayList<>();
for (Document doc : hits.getDocs()) {
try {
String artId = doc.getField(ARTICLE_ID).getValue();
long scopeGroupId = GetterUtil.getLong(doc.getField(SCOPE_GROUP_ID).getValue());
jas.add(JournalArticleLocalServiceUtil.getLatestArticle(scopeGroupId, artId));
} catch (NoSuchArticleException e) {
_log.error(e.getMessage());
}
}
int total = hits.getLength();
int end = prms.getEnd();
int totalPages = 0;
if (prms.getStart() > total) {
jas = new ArrayList<>();
}
else {
if (end > total) {
end = total;
}
}
if (total > prms.getDelta()) {
totalPages = (int) Math.ceil((double) total / prms.getDelta());
}
SearchPagi result = new SearchPagi(jas, total, prms.getDelta(),
prms.getStart(), end, prms.getPage(), totalPages, totalPages > 0);
return result;
}
/* ************************
* ****** Constants *******
*********************** */
private static final String PAGI_TYPE = "paginationType";
private static final String MORE = "more";
private static final String ARTICLE_ID = "articleId";
private static final String STATUS = "status";
private static final String SCOPE_GROUP_ID = "scopeGroupId";
private static final String AC_TITLE = "title";
private static final String JA_CATEGORY_TITLE = "assetCategoryTitles";
private static final String JA_CATEGORY_ID = "assetCategoryIds";
private static final String JA_TAG_NAME = "assetTagNames";
private static final String JA_DDM_STRC_KEY = "ddmStructureKey";
private static final String AC_ID = "assetCategoryId";
private static final int NO_PAGI = -2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment