List of usage examples for org.apache.solr.handler.component ResponseBuilder setQueryString
public void setQueryString(String qstr)
From source file:lux.solr.AppServerComponent.java
License:Mozilla Public License
@Override public void prepare(ResponseBuilder rb) throws IOException { SolrQueryRequest req = rb.req;/* w w w .j av a 2 s . co m*/ SolrParams params = req.getParams(); if (rb.getQueryString() == null) { queryPath = rb.req.getParams().get(LUX_XQUERY); if (!StringUtils.isBlank(queryPath)) { String baseUri; String contextBase = (String) params.get("lux.serverBaseUri"); if (params.get("lux.baseUri") != null) { baseUri = (String) params.get("lux.baseUri"); } else if (params.get("lux.serverBaseUri") != null) { baseUri = contextBase; } else { baseUri = ""; } if (File.separatorChar == '\\') { baseUri = baseUri.replace('\\', '/'); } if (!baseUri.endsWith("/")) { // add trailing slash baseUri = baseUri + '/'; } if (baseUri.startsWith("/") || (File.separatorChar == '\\' && baseUri.matches("^[A-Za-z]:/.*$"))) { baseUri = "file://" + baseUri; } //System.out.println ("BASE URI = " + baseUri); String resourceBase = null; if (baseUri.startsWith(RESOURCE_SCHEME)) { resourceBase = baseUri.substring(RESOURCE_SCHEME.length()); } else if (baseUri.startsWith(CONTEXT_SCHEME)) { baseUri = contextBase + baseUri.substring(CONTEXT_SCHEME.length()); } String contents = null; if (resourceBase != null) { InputStream in = AppServerComponent.class.getResourceAsStream(resourceBase + queryPath); queryPath = baseUri + queryPath; if (in == null) { throw new SolrException(ErrorCode.NOT_FOUND, queryPath + " not found"); } else { try { contents = IOUtils.toString(in); } catch (IOException e) { LoggerFactory.getLogger(AppServerComponent.class) .error("An error occurred while reading " + queryPath, e); } IOUtils.closeQuietly(in); } } else { // url provided with scheme queryPath = baseUri + queryPath; URL url = new URL(queryPath); String scheme = url.getProtocol(); if (scheme.equals("lux")) { // TODO implement lux: uri resolution throw new SolrException(ErrorCode.NOT_FOUND, queryPath + " not found (actually lux: scheme is not implemented)"); } else { InputStream in = null; try { if (url.getProtocol().equals("file")) { File f = new File(url.getPath()); if (!f.exists()) { throw new SolrException(ErrorCode.NOT_FOUND, f + " not found"); } if (f.isDirectory() || !f.canRead()) { throw new SolrException(ErrorCode.FORBIDDEN, "access to " + f + " denied by rule"); } in = new FileInputStream(f); } else { // in = url.openStream(); LoggerFactory.getLogger(AppServerComponent.class) .error("URL scheme not supported: " + url.getProtocol()); } contents = IOUtils.toString(in); } catch (IOException e) { LoggerFactory.getLogger(AppServerComponent.class) .error("An error occurred while reading " + url, e); } if (in != null) { IOUtils.closeQuietly(in); } } } rb.setQueryString(contents); } } super.prepare(rb); }
From source file:lux.solr.XQueryComponent.java
License:Mozilla Public License
@Override public void prepare(ResponseBuilder rb) throws IOException { if (searchHandler == null) { // bleah -- we need a link to the search handler to pass down in to the bowels of // XQuery evaluation so we can recurse when we come to a search call. To get that, // we can only traverse the core registry, but due to order of initialization, the // handler won't have been linked to this component until after all the inform() calls // are done. // A possible alternative here would be to write our own search handler that extends // the Solr one and adds itself to the ResponseBuilder... findSearchHandler();//from ww w .j ava 2 s .c o m } SolrQueryRequest req = rb.req; SolrParams params = req.getParams(); if (rb.getQueryString() == null) { rb.setQueryString(params.get(CommonParams.Q)); } String contentType = params.get("lux.contentType"); // TODO: make this a local variable in or near #addResult, not an instance variable: it's not threadsafe serializer = solrIndexConfig.checkoutSerializer(); if (contentType != null) { if (contentType.equals("text/html")) { serializer.setOutputProperty(Serializer.Property.METHOD, "html"); } else if (contentType.equals("text/xml")) { serializer.setOutputProperty(Serializer.Property.METHOD, "xml"); } } else { serializer.setOutputProperty(Serializer.Property.METHOD, getDefaultSerialization()); } if (queryPath == null) { // allow subclasses to override... queryPath = rb.req.getParams().get(LUX_XQUERY); } resultByteSize = 0; }
From source file:net.sr_sl.solr.ssq.SsqQueryComponent.java
License:Apache License
/** * Modify the query parameters//ww w . ja v a2 s. c om */ private boolean modifyQueryRequest(ResponseBuilder rb) throws IOException { SolrQueryRequest req = rb.req; SolrParams params = req.getParams(); // check whether server side queries is active for this request if (!params.getBool(SSQ_PREFIX, false)) return false; // get parameters to use String ssqQuery = params.get(SSQ_PREFIX.concat(SSQ_DELIM).concat(SSQ_QUERY)); String ssqParam = params.get(SSQ_PREFIX.concat(SSQ_DELIM).concat(SSQ_PARAM), SSQ_PARAM_DFT); // when ssqQuery or ssqParam is not set, don't modify if (ssqQuery == null || ssqQuery.isEmpty() || ssqParam.isEmpty()) return false; // Get original value for ssqParam and return when already set String ssqParamVal = params.get(ssqParam); if (ssqParamVal != null && !ssqParamVal.isEmpty()) return false; // Get original query string value String origQueryString = rb.getQueryString(); String origQVal = req.getOriginalParams().get(CommonParams.Q); // Retrieve value to use as query-term; when empty, use q.alt String qVal = origQVal; if (qVal == null || qVal.isEmpty()) { String alt_q = params.get(DisMaxParams.ALTQ); if (alt_q != null && !alt_q.isEmpty()) { qVal = alt_q; } } // Get value for ssqQuery String ssqQueryVal = params .get(SSQ_PREFIX.concat(SSQ_DELIM).concat(SSQ_QUERY).concat(SSQ_DELIM).concat(ssqQuery)); // When value not found, assume that ssqQuery is the query to execute // per default if (ssqQueryVal == null || ssqQueryVal.isEmpty()) ssqQueryVal = ssqQuery; // Perform replacement ModifiableSolrParams mparams = new ModifiableSolrParams(); // Set flag to indicate that replacement is performed mparams.set(SSQ_PREFIX.concat(SSQ_APPLIED_SUFFIX), Boolean.toString(true)); // Store original querystring when <> q if (origQVal != null && !origQVal.equals(origQueryString)) mparams.set(SSQ_PREFIX.concat(SSQ_DELIM).concat(SSQ_QUERYSTRING).concat(SSQ_APPLIED_SUFFIX), origQueryString); // Perform the switch (qVal --> ssqParam) mparams.set(ssqParam, qVal); mparams.set(SSQ_PREFIX.concat(SSQ_DELIM).concat(SSQ_QUERY).concat(SSQ_APPLIED_SUFFIX), ssqQueryVal); // set the extra parameters req.setParams(SolrParams.wrapAppended(req.getParams(), mparams)); // set queryString to query rb.setQueryString(ssqQueryVal); return true; }
From source file:net.sr_sl.solr.ssq.SsqQueryComponent.java
License:Apache License
/** * Restore the query parameters Restore queryString and reset original q (to * ensure further components will be processed correctly) */// ww w . j a v a2 s . co m private boolean restoreQueryRequest(ResponseBuilder rb) { SolrQueryRequest req = rb.req; SolrParams params = req.getParams(); // check whether server side queries is active for this request if (!params.getBool(SSQ_PREFIX, false)) return false; // check whether values where replaced if (!params.getBool(SSQ_PREFIX.concat(SSQ_APPLIED_SUFFIX), false)) return false; // retrieve original queryString and q String queryString = params .get(SSQ_PREFIX.concat(SSQ_DELIM).concat(SSQ_QUERYSTRING).concat(SSQ_APPLIED_SUFFIX)); boolean useStoredQueryString = (queryString != null && queryString.isEmpty()); // remove flag that was possibly set to store original queryString if (!useStoredQueryString) { ModifiableSolrParams mparams = new ModifiableSolrParams(params); mparams.remove(SSQ_PREFIX.concat(SSQ_DELIM).concat(SSQ_QUERYSTRING).concat(SSQ_APPLIED_SUFFIX)); req.setParams(mparams); } else { queryString = req.getOriginalParams().get(CommonParams.Q); } // set queryString to original query rb.setQueryString(queryString); return true; }
From source file:opennlp.tools.similarity.apps.solr.IterativeQueryComponent.java
License:Apache License
private ResponseBuilder substituteField(ResponseBuilder rb, String newFieldName) { SolrParams params = rb.req.getParams(); String query = params.get("q"); String currField = StringUtils.substringBetween(" " + query, " ", ":"); if (currField != null && newFieldName != null) query = query.replace(currField, newFieldName); NamedList values = params.toNamedList(); values.remove("q"); values.add("q", query); params = SolrParams.toSolrParams(values); rb.req.setParams(params);/*from w ww . j av a 2 s . c om*/ rb.setQueryString(query); String defType = params.get(QueryParsing.DEFTYPE, QParserPlugin.DEFAULT_QTYPE); // get it from the response builder to give a different component a chance // to set it. String queryString = rb.getQueryString(); if (queryString == null) { // this is the normal way it's set. queryString = params.get(CommonParams.Q); rb.setQueryString(queryString); } QParser parser = null; try { parser = QParser.getParser(rb.getQueryString(), defType, rb.req); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Query q = null; try { q = parser.getQuery(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if (q == null) { // normalize a null query to a query that matches nothing q = new BooleanQuery(); } rb.setQuery(q); try { rb.setSortSpec(parser.getSort(true)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } rb.setQparser(parser); /* try { rb.setScoreDoc(parser.getPaging()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } */ String[] fqs = rb.req.getParams().getParams(CommonParams.FQ); if (fqs != null && fqs.length != 0) { List<Query> filters = rb.getFilters(); if (filters == null) { filters = new ArrayList<Query>(fqs.length); } for (String fq : fqs) { if (fq != null && fq.trim().length() != 0) { QParser fqp = null; try { fqp = QParser.getParser(fq, null, rb.req); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } try { filters.add(fqp.getQuery()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // only set the filters if they are not empty otherwise // fq=&someotherParam= will trigger all docs filter for every request // if filter cache is disabled if (!filters.isEmpty()) { rb.setFilters(filters); } } return rb; }
From source file:org.alfresco.solr.component.spellcheck.AlfrescoSpellCheckCollator.java
License:Open Source License
public List<AlfrescoSpellCheckCollation> collate(SpellingResult result, String originalQuery, ResponseBuilder ultimateResponse) { List<AlfrescoSpellCheckCollation> collations = new ArrayList<>(); QueryComponent queryComponent = null; if (ultimateResponse.components != null) { for (SearchComponent sc : ultimateResponse.components) { if (sc instanceof QueryComponent) { queryComponent = (QueryComponent) sc; break; }/*from ww w. ja va 2 s. c om*/ } } boolean verifyCandidateWithQuery = true; int maxTries = maxCollationTries; int maxNumberToIterate = maxTries; if (maxTries < 1) { maxTries = 1; maxNumberToIterate = maxCollations; verifyCandidateWithQuery = false; } if (queryComponent == null && verifyCandidateWithQuery) { LOG.info( "Could not find an instance of QueryComponent. Disabling collation verification against the index."); maxTries = 1; verifyCandidateWithQuery = false; } docCollectionLimit = docCollectionLimit > 0 ? docCollectionLimit : 0; int maxDocId = -1; if (verifyCandidateWithQuery && docCollectionLimit > 0) { IndexReader reader = ultimateResponse.req.getSearcher().getIndexReader(); maxDocId = reader.maxDoc(); } JSONObject alfrescoJSON = (JSONObject) ultimateResponse.req.getContext().get(AbstractQParser.ALFRESCO_JSON); String originalAftsQuery = alfrescoJSON != null ? alfrescoJSON.getString("query") : ultimateResponse.getQueryString(); int tryNo = 0; int collNo = 0; PossibilityIterator possibilityIter = new PossibilityIterator(result.getSuggestions(), maxNumberToIterate, maxCollationEvaluations, suggestionsMayOverlap); while (tryNo < maxTries && collNo < maxCollations && possibilityIter.hasNext()) { PossibilityIterator.RankedSpellPossibility possibility = possibilityIter.next(); String collationQueryStr = getCollation(originalQuery, possibility.corrections); int hits = 0; String aftsQuery = null; if (verifyCandidateWithQuery) { tryNo++; SolrQueryRequest req = ultimateResponse.req; SolrParams origParams = req.getParams(); ModifiableSolrParams params = new ModifiableSolrParams(origParams); Iterator<String> origParamIterator = origParams.getParameterNamesIterator(); int pl = SpellingParams.SPELLCHECK_COLLATE_PARAM_OVERRIDE.length(); while (origParamIterator.hasNext()) { String origParamName = origParamIterator.next(); if (origParamName.startsWith(SpellingParams.SPELLCHECK_COLLATE_PARAM_OVERRIDE) && origParamName.length() > pl) { String[] val = origParams.getParams(origParamName); if (val.length == 1 && val[0].length() == 0) { params.set(origParamName.substring(pl), (String[]) null); } else { params.set(origParamName.substring(pl), val); } } } // we don't set the 'q' param, as we'll pass the query via JSON. // params.set(CommonParams.Q, collationQueryStr); params.remove(CommonParams.START); params.set(CommonParams.ROWS, "" + docCollectionLimit); // we don't want any stored fields params.set(CommonParams.FL, "id"); // we'll sort by doc id to ensure no scoring is done. params.set(CommonParams.SORT, "_docid_ asc"); // If a dismax query, don't add unnecessary clauses for scoring params.remove(DisMaxParams.TIE); params.remove(DisMaxParams.PF); params.remove(DisMaxParams.PF2); params.remove(DisMaxParams.PF3); params.remove(DisMaxParams.BQ); params.remove(DisMaxParams.BF); // Collate testing does not support Grouping (see SOLR-2577) params.remove(GroupParams.GROUP); boolean useQStr = true; if (alfrescoJSON != null) { try { aftsQuery = originalAftsQuery.replaceAll(Pattern.quote(originalQuery), Matcher.quoteReplacement(collationQueryStr)); alfrescoJSON.put("query", aftsQuery); req.getContext().put(AbstractQParser.ALFRESCO_JSON, alfrescoJSON); useQStr = false; } catch (JSONException e) { LOG.warn("Exception trying to get/set the query from/to ALFRESCO_JSON.]" + e); } } else { aftsQuery = collationQueryStr; } req.setParams(params); // creating a request here... make sure to close it! ResponseBuilder checkResponse = new ResponseBuilder(req, new SolrQueryResponse(), Arrays.<SearchComponent>asList(queryComponent)); checkResponse.setQparser(ultimateResponse.getQparser()); checkResponse.setFilters(ultimateResponse.getFilters()); checkResponse.components = Arrays.<SearchComponent>asList(queryComponent); if (useQStr) { checkResponse.setQueryString(collationQueryStr); } try { queryComponent.prepare(checkResponse); if (docCollectionLimit > 0) { int f = checkResponse.getFieldFlags(); checkResponse.setFieldFlags(f |= SolrIndexSearcher.TERMINATE_EARLY); } queryComponent.process(checkResponse); hits = (Integer) checkResponse.rsp.getToLog().get("hits"); } catch (EarlyTerminatingCollectorException etce) { assert (docCollectionLimit > 0); assert 0 < etce.getNumberScanned(); assert 0 < etce.getNumberCollected(); if (etce.getNumberScanned() == maxDocId) { hits = etce.getNumberCollected(); } else { hits = (int) (((float) (maxDocId * etce.getNumberCollected())) / (float) etce.getNumberScanned()); } } catch (Exception e) { LOG.warn( "Exception trying to re-query to check if a spell check possibility would return any hits." + e); } finally { checkResponse.req.close(); } } if (hits > 0 || !verifyCandidateWithQuery) { collNo++; AlfrescoSpellCheckCollation collation = new AlfrescoSpellCheckCollation(); collation.setCollationQuery(aftsQuery); collation.setCollationQueryString(collationQueryStr); collation.setHits(hits); collation.setInternalRank( suggestionsMayOverlap ? ((possibility.rank * 1000) + possibility.index) : possibility.rank); NamedList<String> misspellingsAndCorrections = new NamedList<>(); for (SpellCheckCorrection corr : possibility.corrections) { misspellingsAndCorrections.add(corr.getOriginal().toString(), corr.getCorrection()); } collation.setMisspellingsAndCorrections(misspellingsAndCorrections); collations.add(collation); } if (LOG.isDebugEnabled()) { LOG.debug("Collation: " + aftsQuery + (verifyCandidateWithQuery ? (" will return " + hits + " hits.") : "")); } } return collations; }
From source file:org.opencms.search.solr.CmsSolrIndex.java
License:Open Source License
/** * Performs the actual search.<p>//from w ww. j av a 2 s .co m * * @param cms the current OpenCms context * @param ignoreMaxRows <code>true</code> to return all all requested rows, <code>false</code> to use max rows * @param query the OpenCms Solr query * @param response the servlet response to write the query result to, may also be <code>null</code> * @param ignoreSearchExclude if set to false, only contents with search_exclude unset or "false" will be found - typical for the the non-gallery case * @param filter the resource filter to use * * @return the found documents * * @throws CmsSearchException if something goes wrong * * @see #search(CmsObject, CmsSolrQuery, boolean) */ @SuppressWarnings("unchecked") public CmsSolrResultList search(CmsObject cms, final CmsSolrQuery query, boolean ignoreMaxRows, ServletResponse response, boolean ignoreSearchExclude, CmsResourceFilter filter) throws CmsSearchException { // check if the user is allowed to access this index checkOfflineAccess(cms); if (!ignoreSearchExclude) { query.addFilterQuery(CmsSearchField.FIELD_SEARCH_EXCLUDE + ":\"false\""); } int previousPriority = Thread.currentThread().getPriority(); long startTime = System.currentTimeMillis(); // remember the initial query SolrQuery initQuery = query.clone(); query.setHighlight(false); LocalSolrQueryRequest solrQueryRequest = null; try { // initialize the search context CmsObject searchCms = OpenCms.initCmsObject(cms); // change thread priority in order to reduce search impact on overall system performance if (getPriority() > 0) { Thread.currentThread().setPriority(getPriority()); } // the lists storing the found documents that will be returned List<CmsSearchResource> resourceDocumentList = new ArrayList<CmsSearchResource>(); SolrDocumentList solrDocumentList = new SolrDocumentList(); // Initialize rows, offset, end and the current page. int rows = query.getRows() != null ? query.getRows().intValue() : CmsSolrQuery.DEFAULT_ROWS.intValue(); if (!ignoreMaxRows && (rows > ROWS_MAX)) { rows = ROWS_MAX; } int start = query.getStart() != null ? query.getStart().intValue() : 0; int end = start + rows; int page = 0; if (rows > 0) { page = Math.round(start / rows) + 1; } // set the start to '0' and expand the rows before performing the query query.setStart(new Integer(0)); query.setRows(new Integer((5 * rows * page) + start)); // perform the Solr query and remember the original Solr response QueryResponse queryResponse = m_solr.query(query); long solrTime = System.currentTimeMillis() - startTime; // initialize the counts long hitCount = queryResponse.getResults().getNumFound(); start = -1; end = -1; if ((rows > 0) && (page > 0) && (hitCount > 0)) { // calculate the final size of the search result start = rows * (page - 1); end = start + rows; // ensure that both i and n are inside the range of foundDocuments.size() start = new Long((start > hitCount) ? hitCount : start).intValue(); end = new Long((end > hitCount) ? hitCount : end).intValue(); } else { // return all found documents in the search result start = 0; end = new Long(hitCount).intValue(); } long visibleHitCount = hitCount; float maxScore = 0; // If we're using a postprocessor, (re-)initialize it before using it if (m_postProcessor != null) { m_postProcessor.init(); } // process found documents List<CmsSearchResource> allDocs = new ArrayList<CmsSearchResource>(); int cnt = 0; for (int i = 0; (i < queryResponse.getResults().size()) && (cnt < end); i++) { try { SolrDocument doc = queryResponse.getResults().get(i); CmsSolrDocument searchDoc = new CmsSolrDocument(doc); if (needsPermissionCheck(searchDoc)) { // only if the document is an OpenCms internal resource perform the permission check CmsResource resource = filter == null ? getResource(searchCms, searchDoc) : getResource(searchCms, searchDoc, filter); if (resource != null) { // permission check performed successfully: the user has read permissions! if (cnt >= start) { if (m_postProcessor != null) { doc = m_postProcessor.process(searchCms, resource, (SolrInputDocument) searchDoc.getDocument()); } resourceDocumentList.add(new CmsSearchResource(resource, searchDoc)); if (null != doc) { solrDocumentList.add(doc); } maxScore = maxScore < searchDoc.getScore() ? searchDoc.getScore() : maxScore; } allDocs.add(new CmsSearchResource(resource, searchDoc)); cnt++; } else { visibleHitCount--; } } else { // if permission check is not required for this index, // add a pseudo resource together with document to the results resourceDocumentList.add(new CmsSearchResource(PSEUDO_RES, searchDoc)); solrDocumentList.add(doc); maxScore = maxScore < searchDoc.getScore() ? searchDoc.getScore() : maxScore; cnt++; } } catch (Exception e) { // should not happen, but if it does we want to go on with the next result nevertheless LOG.warn(Messages.get().getBundle().key(Messages.LOG_SOLR_ERR_RESULT_ITERATION_FAILED_0), e); } } // the last documents were all secret so let's take the last found docs if (resourceDocumentList.isEmpty() && (allDocs.size() > 0)) { page = Math.round(allDocs.size() / rows) + 1; int showCount = allDocs.size() % rows; showCount = showCount == 0 ? rows : showCount; start = allDocs.size() - new Long(showCount).intValue(); end = allDocs.size(); if (allDocs.size() > start) { resourceDocumentList = allDocs.subList(start, end); for (CmsSearchResource r : resourceDocumentList) { maxScore = maxScore < r.getDocument().getScore() ? r.getDocument().getScore() : maxScore; solrDocumentList.add(((CmsSolrDocument) r.getDocument()).getSolrDocument()); } } } long processTime = System.currentTimeMillis() - startTime - solrTime; // create and return the result solrDocumentList.setStart(start); solrDocumentList.setMaxScore(new Float(maxScore)); solrDocumentList.setNumFound(visibleHitCount); queryResponse.getResponse().setVal(queryResponse.getResponse().indexOf(QUERY_RESPONSE_NAME, 0), solrDocumentList); queryResponse.getResponseHeader().setVal(queryResponse.getResponseHeader().indexOf(QUERY_TIME_NAME, 0), new Integer(new Long(System.currentTimeMillis() - startTime).intValue())); long highlightEndTime = System.currentTimeMillis(); SolrCore core = m_solr instanceof EmbeddedSolrServer ? ((EmbeddedSolrServer) m_solr).getCoreContainer().getCore(getCoreName()) : null; CmsSolrResultList result = null; try { SearchComponent highlightComponenet = null; if (core != null) { highlightComponenet = core.getSearchComponent("highlight"); solrQueryRequest = new LocalSolrQueryRequest(core, queryResponse.getResponseHeader()); } SolrQueryResponse solrQueryResponse = null; if (solrQueryRequest != null) { // create and initialize the solr response solrQueryResponse = new SolrQueryResponse(); solrQueryResponse.setAllValues(queryResponse.getResponse()); int paramsIndex = queryResponse.getResponseHeader().indexOf(HEADER_PARAMS_NAME, 0); NamedList<Object> header = null; Object o = queryResponse.getResponseHeader().getVal(paramsIndex); if (o instanceof NamedList) { header = (NamedList<Object>) o; header.setVal(header.indexOf(CommonParams.ROWS, 0), new Integer(rows)); header.setVal(header.indexOf(CommonParams.START, 0), new Long(start)); } // set the OpenCms Solr query as parameters to the request solrQueryRequest.setParams(initQuery); // perform the highlighting if ((header != null) && (initQuery.getHighlight()) && (highlightComponenet != null)) { header.add(HighlightParams.HIGHLIGHT, "on"); if ((initQuery.getHighlightFields() != null) && (initQuery.getHighlightFields().length > 0)) { header.add(HighlightParams.FIELDS, CmsStringUtil.arrayAsString(initQuery.getHighlightFields(), ",")); } String formatter = initQuery.getParams(HighlightParams.FORMATTER) != null ? initQuery.getParams(HighlightParams.FORMATTER)[0] : null; if (formatter != null) { header.add(HighlightParams.FORMATTER, formatter); } if (initQuery.getHighlightFragsize() != 100) { header.add(HighlightParams.FRAGSIZE, new Integer(initQuery.getHighlightFragsize())); } if (initQuery.getHighlightRequireFieldMatch()) { header.add(HighlightParams.FIELD_MATCH, new Boolean(initQuery.getHighlightRequireFieldMatch())); } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(initQuery.getHighlightSimplePost())) { header.add(HighlightParams.SIMPLE_POST, initQuery.getHighlightSimplePost()); } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(initQuery.getHighlightSimplePre())) { header.add(HighlightParams.SIMPLE_PRE, initQuery.getHighlightSimplePre()); } if (initQuery.getHighlightSnippets() != 1) { header.add(HighlightParams.SNIPPETS, new Integer(initQuery.getHighlightSnippets())); } ResponseBuilder rb = new ResponseBuilder(solrQueryRequest, solrQueryResponse, Collections.singletonList(highlightComponenet)); try { rb.doHighlights = true; DocListAndSet res = new DocListAndSet(); SchemaField idField = OpenCms.getSearchManager().getSolrServerConfiguration() .getSolrSchema().getUniqueKeyField(); int[] luceneIds = new int[rows]; int docs = 0; for (SolrDocument doc : solrDocumentList) { String idString = (String) doc.getFirstValue(CmsSearchField.FIELD_ID); int id = solrQueryRequest.getSearcher().getFirstMatch( new Term(idField.getName(), idField.getType().toInternal(idString))); luceneIds[docs++] = id; } res.docList = new DocSlice(0, docs, luceneIds, null, docs, 0); rb.setResults(res); rb.setQuery(QParser.getParser(initQuery.getQuery(), null, solrQueryRequest).getQuery()); rb.setQueryString(initQuery.getQuery()); highlightComponenet.prepare(rb); highlightComponenet.process(rb); highlightComponenet.finishStage(rb); } catch (Exception e) { LOG.error(e.getMessage() + " in query: " + initQuery, new Exception(e)); } // Make highlighting also available via the CmsSolrResultList queryResponse.setResponse(solrQueryResponse.getValues()); highlightEndTime = System.currentTimeMillis(); } } result = new CmsSolrResultList(initQuery, queryResponse, solrDocumentList, resourceDocumentList, start, new Integer(rows), end, page, visibleHitCount, new Float(maxScore), startTime, highlightEndTime); if (LOG.isDebugEnabled()) { Object[] logParams = new Object[] { new Long(System.currentTimeMillis() - startTime), new Long(result.getNumFound()), new Long(solrTime), new Long(processTime), new Long(result.getHighlightEndTime() != 0 ? result.getHighlightEndTime() - startTime : 0) }; LOG.debug(query.toString() + "\n" + Messages.get().getBundle().key(Messages.LOG_SOLR_SEARCH_EXECUTED_5, logParams)); } if (response != null) { writeResp(response, solrQueryRequest, solrQueryResponse); } } finally { if (solrQueryRequest != null) { solrQueryRequest.close(); } if (core != null) { core.close(); } } return result; } catch (Exception e) { throw new CmsSearchException(Messages.get().container(Messages.LOG_SOLR_ERR_SEARCH_EXECUTION_FAILD_1, CmsEncoder.decode(query.toString()), e), e); } finally { if (solrQueryRequest != null) { solrQueryRequest.close(); } // re-set thread to previous priority Thread.currentThread().setPriority(previousPriority); } }