List of usage examples for org.apache.solr.client.solrj.response QueryResponse getHighlighting
public Map<String, Map<String, List<String>>> getHighlighting()
From source file:com.doculibre.constellio.utils.NamedListUtils.java
License:Open Source License
public static NamedList<Object> toNamedList(Record record, SolrDocument document, ConstellioUser user, QueryResponse response, List<String> limitedResponseFields) { Locale locale = user.getLocale(); NamedList<Object> nl = new NamedList<Object>(); addField(nl, limitedResponseFields, "authmethod", record.getAuthmethod()); addField(nl, limitedResponseFields, "boost", record.getBoost()); addField(nl, limitedResponseFields, "connectorInstance", record.getConnectorInstance().getName()); for (RecordMeta rm : record.getContentMetas()) { ConnectorInstanceMeta cim = rm.getConnectorInstanceMeta(); String key = cim.getName(); addField(nl, limitedResponseFields, key, rm.getContent()); }/*from ww w .j ava 2 s. c o m*/ addField(nl, limitedResponseFields, "displayTitle", record.getDisplayTitle()); addField(nl, limitedResponseFields, "displayUrl", record.getDisplayUrl()); for (RecordMeta rm : record.getExternalMetas()) { ConnectorInstanceMeta cim = rm.getConnectorInstanceMeta(); String key = cim.getName(); addField(nl, limitedResponseFields, key, rm.getContent()); } List<String> freeTextTags = new ArrayList<String>(); for (FreeTextTag tag : record.getFreeTextTags(false)) { freeTextTags.add(tag.getFreeText()); } addField(nl, limitedResponseFields, "freeTextTags", freeTextTags); List<String> thesaurusTags = new ArrayList<String>(); for (SkosConcept concept : record.getSkosConcepts(false)) { thesaurusTags.add(concept.getPrefLabel(locale)); } addField(nl, limitedResponseFields, "thesaurusTags", thesaurusTags); addField(nl, limitedResponseFields, "id", record.getId()); addField(nl, limitedResponseFields, "lang", record.getLang()); addField(nl, limitedResponseFields, "lastAutomaticTagging", record.getLastAutomaticTagging()); addField(nl, limitedResponseFields, "lastFetched", record.getLastFetched()); addField(nl, limitedResponseFields, "lastIndexed", record.getLastIndexed()); addField(nl, limitedResponseFields, "lastModified", record.getLastModified()); addField(nl, limitedResponseFields, "mimeType", record.getMimetype()); String recordURL = record.getUrl(); addField(nl, limitedResponseFields, "url", recordURL); Map<String, Map<String, List<String>>> highlighting = response.getHighlighting(); Map<String, List<String>> fieldsHighlighting = highlighting.get(recordURL); for (String field : fieldsHighlighting.keySet()) { List<String> list = fieldsHighlighting.get(field); addField(nl, limitedResponseFields, field + "_highlight", list); } return nl; }
From source file:com.doculibre.constellio.wicket.panels.results.DefaultSearchResultPanel.java
License:Open Source License
public DefaultSearchResultPanel(String id, SolrDocument doc, final SearchResultsDataProvider dataProvider) { super(id);/*w ww . j a v a2 s . c o m*/ RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices(); RecordServices recordServices = ConstellioSpringUtils.getRecordServices(); SearchInterfaceConfigServices searchInterfaceConfigServices = ConstellioSpringUtils .getSearchInterfaceConfigServices(); String collectionName = dataProvider.getSimpleSearch().getCollectionName(); RecordCollection collection = collectionServices.get(collectionName); Record record = recordServices.get(doc); if (record != null) { SearchInterfaceConfig searchInterfaceConfig = searchInterfaceConfigServices.get(); IndexField uniqueKeyField = collection.getUniqueKeyIndexField(); IndexField defaultSearchField = collection.getDefaultSearchIndexField(); IndexField urlField = collection.getUrlIndexField(); IndexField titleField = collection.getTitleIndexField(); if (urlField == null) { urlField = uniqueKeyField; } if (titleField == null) { titleField = urlField; } final String recordURL = record.getUrl(); final String displayURL; if (record.getDisplayUrl().startsWith("/get?file=")) { HttpServletRequest req = ((WebRequest) getRequest()).getHttpServletRequest(); displayURL = ContextUrlUtils.getContextUrl(req) + record.getDisplayUrl(); } else { displayURL = record.getDisplayUrl(); } String title = record.getDisplayTitle(); final String protocol = StringUtils.substringBefore(displayURL, ":"); boolean linkEnabled = isLinkEnabled(protocol); // rcupration des champs highlight partir de la cl unique // du document, dans le cas de Nutch c'est l'URL QueryResponse response = dataProvider.getQueryResponse(); Map<String, Map<String, List<String>>> highlighting = response.getHighlighting(); Map<String, List<String>> fieldsHighlighting = highlighting.get(recordURL); String titleHighlight = getTitleFromHighlight(titleField.getName(), fieldsHighlighting); if (titleHighlight != null) { title = titleHighlight; } String excerpt = null; String description = getDescription(record); String summary = getSummary(record); if (StringUtils.isNotBlank(description) && searchInterfaceConfig.isDescriptionAsExcerpt()) { excerpt = description; } else { excerpt = getExcerptFromHighlight(defaultSearchField.getName(), fieldsHighlighting); if (excerpt == null) { excerpt = description; } } toggleSummaryLink = new WebMarkupContainer("toggleSummaryLink"); add(toggleSummaryLink); toggleSummaryLink.setVisible(StringUtils.isNotBlank(summary)); toggleSummaryLink.add(new AttributeModifier("onclick", new LoadableDetachableModel() { @Override protected Object load() { return "toggleSearchResultSummary('" + summaryLabel.getMarkupId() + "')"; } })); summaryLabel = new Label("summary", summary); add(summaryLabel); summaryLabel.setOutputMarkupId(true); summaryLabel.setVisible(StringUtils.isNotBlank(summary)); ExternalLink titleLink; if (displayURL.startsWith("file://")) { HttpServletRequest req = ((WebRequest) getRequest()).getHttpServletRequest(); String newDisplayURL = ContextUrlUtils.getContextUrl(req) + "app/getSmbFile?" + SmbServletPage.RECORD_ID + "=" + record.getId() + "&" + SmbServletPage.COLLECTION + "=" + collectionName; titleLink = new ExternalLink("titleLink", newDisplayURL); } else { titleLink = new ExternalLink("titleLink", displayURL); } final RecordModel recordModel = new RecordModel(record); AttributeModifier computeClickAttributeModifier = new AttributeModifier("onmousedown", true, new LoadableDetachableModel() { @Override protected Object load() { Record record = recordModel.getObject(); SimpleSearch simpleSearch = dataProvider.getSimpleSearch(); WebRequest webRequest = (WebRequest) RequestCycle.get().getRequest(); HttpServletRequest httpRequest = webRequest.getHttpServletRequest(); return ComputeSearchResultClickServlet.getCallbackJavascript(httpRequest, simpleSearch, record); } }); titleLink.add(computeClickAttributeModifier); titleLink.setEnabled(linkEnabled); boolean resultsInNewWindow; PageParameters params = RequestCycle.get().getPageParameters(); if (params != null && params.getString(POPUP_LINK) != null) { resultsInNewWindow = params.getBoolean(POPUP_LINK); } else { resultsInNewWindow = searchInterfaceConfig.isResultsInNewWindow(); } titleLink.add(new SimpleAttributeModifier("target", resultsInNewWindow ? "_blank" : "_self")); // Add title title = StringUtils.remove(title, "\n"); title = StringUtils.remove(title, "\r"); if (StringUtils.isEmpty(title)) { title = StringUtils.defaultString(displayURL); title = StringUtils.substringAfterLast(title, "/"); title = StringUtils.substringBefore(title, "?"); try { title = URLDecoder.decode(title, "UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (title.length() > 120) { title = title.substring(0, 120) + " ..."; } } Label titleLabel = new Label("title", title); titleLink.add(titleLabel.setEscapeModelStrings(false)); add(titleLink); Label excerptLabel = new Label("excerpt", excerpt); add(excerptLabel.setEscapeModelStrings(false)); // add(new ExternalLink("url", url, // url).add(computeClickAttributeModifier).setEnabled(linkEnabled)); if (displayURL.startsWith("file://")) { // Creates a Windows path for file URLs String urlLabel = StringUtils.substringAfter(displayURL, "file:"); urlLabel = StringUtils.stripStart(urlLabel, "/"); urlLabel = "\\\\" + StringUtils.replace(urlLabel, "/", "\\"); try { urlLabel = URLDecoder.decode(urlLabel, "UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } add(new Label("url", urlLabel)); } else { add(new Label("url", displayURL)); } final ReloadableEntityModel<RecordCollection> collectionModel = new ReloadableEntityModel<RecordCollection>( collection); add(new ListView("searchResultFields", new LoadableDetachableModel() { @Override protected Object load() { RecordCollection collection = collectionModel.getObject(); return collection.getSearchResultFields(); } /** * Detaches from the current request. Implement this method with * custom behavior, such as setting the model object to null. */ protected void onDetach() { recordModel.detach(); collectionModel.detach(); } }) { @Override protected void populateItem(ListItem item) { SearchResultField searchResultField = (SearchResultField) item.getModelObject(); IndexFieldServices indexFieldServices = ConstellioSpringUtils.getIndexFieldServices(); Record record = recordModel.getObject(); IndexField indexField = searchResultField.getIndexField(); Locale locale = getLocale(); String indexFieldTitle = indexField.getTitle(locale); if (StringUtils.isBlank(indexFieldTitle)) { indexFieldTitle = indexField.getName(); } StringBuffer fieldValueSb = new StringBuffer(); List<Object> fieldValues = indexFieldServices.extractFieldValues(record, indexField); Map<String, String> defaultLabelledValues = indexFieldServices .getDefaultLabelledValues(indexField, locale); for (Object fieldValue : fieldValues) { if (fieldValueSb.length() > 0) { fieldValueSb.append("\n"); } String fieldValueLabel = indexField.getLabelledValue("" + fieldValue, locale); if (fieldValueLabel == null) { fieldValueLabel = defaultLabelledValues.get("" + fieldValue); } if (fieldValueLabel == null) { fieldValueLabel = "" + fieldValue; } fieldValueSb.append(fieldValueLabel); } item.add(new Label("indexField", indexFieldTitle)); item.add(new MultiLineLabel("indexFieldValue", fieldValueSb.toString())); item.setVisible(fieldValueSb.length() > 0); } @SuppressWarnings("unchecked") @Override public boolean isVisible() { boolean visible = super.isVisible(); if (visible) { List<SearchResultField> searchResultFields = (List<SearchResultField>) getModelObject(); visible = !searchResultFields.isEmpty(); } return visible; } }); // md5 ConstellioSession session = ConstellioSession.get(); ConstellioUser user = session.getUser(); // TODO Provide access to unauthenticated users ? String md5 = ""; if (user != null) { IntelliGIDServiceInfo intelligidServiceInfo = ConstellioSpringUtils.getIntelliGIDServiceInfo(); if (intelligidServiceInfo != null) { Collection<Object> md5Coll = doc.getFieldValues(IndexField.MD5); if (md5Coll != null) { for (Object md5Obj : md5Coll) { try { String md5Str = new String(Hex.encodeHex(Base64.decodeBase64(md5Obj.toString()))); InputStream is = HttpClientHelper .get(intelligidServiceInfo.getIntelligidUrl() + "/connector/checksum", "md5=" + URLEncoder.encode(md5Str, "ISO-8859-1"), "username=" + URLEncoder.encode(user.getUsername(), "ISO-8859-1"), "password=" + URLEncoder.encode(Base64.encodeBase64String( ConstellioSession.get().getPassword().getBytes())), "ISO-8859-1"); try { Document xmlDocument = new SAXReader().read(is); Element root = xmlDocument.getRootElement(); for (Iterator<Element> it = root.elementIterator("fichier"); it.hasNext();) { Element fichier = it.next(); String url = fichier.attributeValue("url"); md5 += "<a href=\"" + url + "\">" + url + "</a> "; } } finally { IOUtils.closeQuietly(is); } } catch (Exception e) { e.printStackTrace(); } } } } } Label md5Label = new Label("md5", md5) { public boolean isVisible() { boolean visible = super.isVisible(); if (visible) { visible = StringUtils.isNotBlank(this.getModelObjectAsString()); } return visible; } }; md5Label.setEscapeModelStrings(false); add(md5Label); add(new ElevatePanel("elevatePanel", record, dataProvider.getSimpleSearch())); } else { setVisible(false); } }
From source file:com.doculibre.constellio.wicket.panels.results.MailSearchResultPanel.java
License:Open Source License
public MailSearchResultPanel(String id, final SolrDocument doc, final SearchResultsDataProvider dataProvider) { super(id);/*from ww w .ja v a 2 s . c o m*/ RecordServices recordServices = ConstellioSpringUtils.getRecordServices(); RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices(); final Long recordId = new Long(doc.getFieldValue(IndexField.RECORD_ID_FIELD).toString()); final String collectionName = dataProvider.getSimpleSearch().getCollectionName(); RecordCollection collection = collectionServices.get(collectionName); Record record = recordServices.get(recordId, collection); final IModel subjectModel = new LoadableDetachableModel() { @Override protected Object load() { RecordServices recordServices = ConstellioSpringUtils.getRecordServices(); Record record = recordServices.get(doc); String subject = record.getDisplayTitle(); if (StringUtils.isBlank(subject)) { subject = getLocalizer().getString("noSubject", MailSearchResultPanel.this); } if (subject.length() > 60) { subject = subject.substring(0, 60) + " ..."; } return subject; } }; // List<byte[]> attachmentContents = new ArrayList<byte[]>(); // String messageContent = null; // for (RawContent raw : rawContents) { // byte[] bytes = raw.getContent(); // if (messageContent == null) { // messageContent = new String(bytes); // } else { // attachmentContents.add(bytes); // } // System.out.println("partial content :" + new String(bytes)); // } // System.out.println("content 1 :" + messageContent); // Description du document dans extrait: QueryResponse response = dataProvider.getQueryResponse(); Map<String, Map<String, List<String>>> highlighting = response.getHighlighting(); final String recordURL = record.getUrl(); Map<String, List<String>> fieldsHighlighting = highlighting.get(recordURL); ConnectorInstance connectorInstance = record.getConnectorInstance(); IndexField defaultSearchField = collection.getDefaultSearchIndexField(); String excerpt = getExcerptFromHighlight(defaultSearchField.getName(), fieldsHighlighting); final ModalWindow detailsMailModal = new ModalWindow("detailsMailModal"); detailsMailModal.setPageCreator(new PageCreator() { @Override public Page createPage() { return new BaseConstellioPage(); } }); add(detailsMailModal); detailsMailModal.setCssClassName(ModalWindow.CSS_CLASS_GRAY); detailsMailModal.setCookieName("detailsMailModal"); IModel modalTitleModel = subjectModel; detailsMailModal.setTitle(modalTitleModel); final String displayURL = (String) doc.getFieldValue(collection.getUrlIndexField().getName()); emailModel = new LoadableDetachableModel() { @Override protected Object load() { RecordServices recordServices = ConstellioSpringUtils.getRecordServices(); Record record = recordServices.get(doc); List<String> attachmentNames = record.getMetaContents(MailConnectorConstants.META_ATTACHMENTNAME); List<String> attachmentTypes = record.getMetaContents(MailConnectorConstants.META_ATTACHMENTTYPE); List<String> recipients = record.getMetaContents(MailConnectorConstants.META_RECIPIENTS); List<String> flags = record.getMetaContents(MailConnectorConstants.META_FLAGS); List<String> froms = record.getMetaContents(MailConnectorConstants.META_SENDER); // FIXME Hardcoded List<String> contentEncoding = record.getMetaContents("Content-Encoding"); List<String> receivedDateList = record.getMetaContents(MailConnectorConstants.META_RECEIVEDDATE); // FIXME voir avec Vincent : exemple qui ne marche pas jobboom car mail contient que du html RawContentServices rawContentServices = ConstellioSpringUtils.getRawContentServices(); List<RawContent> rawContents = rawContentServices.getRawContents(record); ParsedContent parsedContents = record.getParsedContent(); Email email; if (rawContents.size() != 0) { byte[] content = rawContents.get(0).getContent(); String tmpFilePath = ClasspathUtils.getCollectionsRootDir() + File.separator + "tmp.eml"; try { email = MailMessageUtils.toEmail(content, tmpFilePath); } catch (Exception e) { System.out.println("Error in reading content of mail"); // le contenu n'a pas bien t lu correctement email = new Email(); email.setMessageContentText(parsedContents.getContent()); } } else { // le contenu n'a pas bien t lu correctement email = new Email(); email.setMessageContentText(parsedContents.getContent()); } email.setFlags(flags); // email.setMessageContentHtml(messageContentHtml); if (!receivedDateList.isEmpty()) { email.setReceivedDate(receivedDateList.get(0)); } email.setRecipients(recipients); email.setSubject((String) subjectModel.getObject()); email.setFroms(froms); // email.setLanguage(language); if (!contentEncoding.isEmpty()) { email.setContentEncoding(contentEncoding.get(0)); } return email; } }; final RecordModel recordModel = new RecordModel(record); AjaxLink detailsMailLink = new AjaxLink("detailsMailLink") { @Override public void onClick(AjaxRequestTarget target) { Email email = (Email) emailModel.getObject(); detailsMailModal.setContent(new MailDetailsPanel(detailsMailModal.getContentId(), email)); detailsMailModal.show(target); } @Override protected IAjaxCallDecorator getAjaxCallDecorator() { return new AjaxCallDecorator() { @Override public CharSequence decorateScript(CharSequence script) { Record record = recordModel.getObject(); SimpleSearch simpleSearch = dataProvider.getSimpleSearch(); WebRequest webRequest = (WebRequest) RequestCycle.get().getRequest(); HttpServletRequest httpRequest = webRequest.getHttpServletRequest(); return script + ";" + ComputeSearchResultClickServlet.getCallbackJavascript(httpRequest, simpleSearch, record); } }; } }; add(detailsMailLink); IModel recipientsLabelModel = new LoadableDetachableModel() { @Override protected Object load() { RecordServices recordServices = ConstellioSpringUtils.getRecordServices(); Record record = recordServices.get(doc); List<String> recipients = record.getMetaContents(MailConnectorConstants.META_RECIPIENTS); return getLocalizer().getString("to", MailSearchResultPanel.this) + " : " + recipients; } }; IModel receivedDateLabelModel = new LoadableDetachableModel() { @Override protected Object load() { RecordServices recordServices = ConstellioSpringUtils.getRecordServices(); Record record = recordServices.get(doc); List<String> receivedDateList = record.getMetaContents(MailConnectorConstants.META_RECEIVEDDATE); String receivedDate; if (!receivedDateList.isEmpty()) { receivedDate = receivedDateList.get(0); } else { receivedDate = ""; } return getLocalizer().getString("date", MailSearchResultPanel.this) + " : " + receivedDate; } }; Label subjectLabel = new Label("subject", subjectModel); detailsMailLink.add(subjectLabel.setEscapeModelStrings(false)); Label excerptLbl = new Label("messageContent", excerpt); add(excerptLbl.setEscapeModelStrings(false)); add(new Label("recipient", recipientsLabelModel) { @Override public boolean isVisible() { boolean visible = super.isVisible(); if (visible) { RecordCollectionServices collectionServices = ConstellioSpringUtils .getRecordCollectionServices(); RecordServices recordServices = ConstellioSpringUtils.getRecordServices(); RecordCollection collection = collectionServices.get(collectionName); Record record = recordServices.get(recordId, collection); List<String> recipients = record.getMetaContents(MailConnectorConstants.META_RECIPIENTS); visible = !recipients.isEmpty(); } return visible; } }); // add(new Label("from", getLocalizer().getString("from", this) + " : " + froms)); add(new Label("date", receivedDateLabelModel)); add(new WebMarkupContainer("hasAttachmentsImg") { @Override public boolean isVisible() { boolean visible = super.isVisible(); if (visible) { RecordServices recordServices = ConstellioSpringUtils.getRecordServices(); Record record = recordServices.get(doc); List<String> attachmentNames = record .getMetaContents(MailConnectorConstants.META_ATTACHMENTNAME); visible = !attachmentNames.isEmpty(); } return visible; } }); final ReloadableEntityModel<RecordCollection> collectionModel = new ReloadableEntityModel<RecordCollection>( collection); add(new ListView("searchResultFields", new LoadableDetachableModel() { @Override protected Object load() { RecordCollection collection = collectionModel.getObject(); return collection.getSearchResultFields(); } /** * Detaches from the current request. Implement this method with custom behavior, such as * setting the model object to null. */ protected void onDetach() { recordModel.detach(); collectionModel.detach(); } }) { @Override protected void populateItem(ListItem item) { SearchResultField searchResultField = (SearchResultField) item.getModelObject(); IndexFieldServices indexFieldServices = ConstellioSpringUtils.getIndexFieldServices(); Record record = recordModel.getObject(); IndexField indexField = searchResultField.getIndexField(); Locale locale = getLocale(); String indexFieldTitle = indexField.getTitle(locale); if (StringUtils.isBlank(indexFieldTitle)) { indexFieldTitle = indexField.getName(); } StringBuffer fieldValueSb = new StringBuffer(); List<Object> fieldValues = indexFieldServices.extractFieldValues(record, indexField); Map<String, String> defaultLabelledValues = indexFieldServices.getDefaultLabelledValues(indexField, locale); for (Object fieldValue : fieldValues) { if (fieldValueSb.length() > 0) { fieldValueSb.append("\n"); } String fieldValueLabel = indexField.getLabelledValue("" + fieldValue, locale); if (fieldValueLabel == null) { fieldValueLabel = defaultLabelledValues.get("" + fieldValue); } if (fieldValueLabel == null) { fieldValueLabel = "" + fieldValue; } fieldValueSb.append(fieldValueLabel); } item.add(new Label("indexField", indexFieldTitle)); item.add(new MultiLineLabel("indexFieldValue", fieldValueSb.toString())); item.setVisible(fieldValueSb.length() > 0); } @SuppressWarnings("unchecked") @Override public boolean isVisible() { boolean visible = super.isVisible(); if (visible) { List<SearchResultField> searchResultFields = (List<SearchResultField>) getModelObject(); visible = !searchResultFields.isEmpty(); } return visible; } }); add(new ElevatePanel("elevatePanel", record, dataProvider.getSimpleSearch())); }
From source file:com.doculibre.constellio.wicket.panels.results.PopupSearchResultPanel.java
License:Open Source License
public PopupSearchResultPanel(String id, SolrDocument doc, final SearchResultsDataProvider dataProvider) { super(id);//from w ww . j ava 2s . c om RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices(); String solrServerName = dataProvider.getSimpleSearch().getCollectionName(); RecordCollection collection = collectionServices.get(solrServerName); IndexField uniqueKeyField = collection.getUniqueKeyIndexField(); IndexField defaultSearchField = collection.getDefaultSearchIndexField(); IndexField urlField = collection.getUrlIndexField(); IndexField titleField = collection.getTitleIndexField(); // title String documentID = (String) getFieldValue(doc, uniqueKeyField.getName()); String documentTitle = (String) getFieldValue(doc, titleField.getName()); if (StringUtils.isBlank(documentTitle)) { if (urlField == null) { documentTitle = (String) getFieldValue(doc, uniqueKeyField.getName()); } else { documentTitle = (String) getFieldValue(doc, urlField.getName()); } } if (documentTitle.length() > 120) { documentTitle = documentTitle.substring(0, 120) + " ..."; } // content RecordServices recordServices = ConstellioSpringUtils.getRecordServices(); Record record = recordServices.get(doc); RawContentServices rawContentServices = ConstellioSpringUtils.getRawContentServices(); List<RawContent> rawContents = rawContentServices.getRawContents(record); StringBuilder content = new StringBuilder(); for (RawContent raw : rawContents) { byte[] bytes = raw.getContent(); content.append(new String(bytes)); } String documentContent = content.toString(); // date String documentLastModified = getFieldValue(doc, IndexField.LAST_MODIFIED_FIELD); // Description du document dans extrait: QueryResponse response = dataProvider.getQueryResponse(); Map<String, Map<String, List<String>>> highlighting = response.getHighlighting(); final String recordURL = record.getUrl(); Map<String, List<String>> fieldsHighlighting = highlighting.get(recordURL); String extrait = getExcerptFromHighlight(defaultSearchField.getName(), fieldsHighlighting); final ModalWindow detailsDocumentModal = new ModalWindow("detailsDocumentModal"); add(detailsDocumentModal); detailsDocumentModal.setCssClassName(ModalWindow.CSS_CLASS_GRAY); detailsDocumentModal.setContent( new PopupDetailsPanel(detailsDocumentModal.getContentId(), documentContent, documentLastModified)); detailsDocumentModal.setCookieName("detailsDocumentModal"); String modalTitle = documentTitle; detailsDocumentModal.setTitle(modalTitle); AjaxLink detailsDocumentLink = new AjaxLink("detailsDocumentLink") { @Override public void onClick(AjaxRequestTarget target) { detailsDocumentModal.show(target); } }; add(detailsDocumentLink); final RecordModel recordModel = new RecordModel(record); AttributeAppender computeClickAttributeModifier = new AttributeAppender("onclick", true, new LoadableDetachableModel() { @Override protected Object load() { Record record = recordModel.getObject(); SimpleSearch simpleSearch = dataProvider.getSimpleSearch(); WebRequest webRequest = (WebRequest) RequestCycle.get().getRequest(); HttpServletRequest httpRequest = webRequest.getHttpServletRequest(); return ComputeSearchResultClickServlet.getCallbackJavascript(httpRequest, simpleSearch, record); } @Override protected void onDetach() { recordModel.detach(); super.onDetach(); } }, ";") { @Override protected String newValue(String currentValue, String appendValue) { return appendValue + currentValue; } }; detailsDocumentLink.add(computeClickAttributeModifier); Label subjectLabel = new Label("subject", documentTitle); detailsDocumentLink.add(subjectLabel.setEscapeModelStrings(false)); Label extraitLbl = new Label("documentContent", extrait); add(extraitLbl.setEscapeModelStrings(false)); add(new Label("date", "Date : " + documentLastModified)); add(new ElevatePanel("elevatePanel", record, dataProvider.getSimpleSearch())); }
From source file:com.frank.search.solr.core.ResultHelper.java
License:Apache License
static <T> List<HighlightEntry<T>> convertAndAddHighlightQueryResponseToResultPage(QueryResponse response, SolrResultPage<T> page) {//from w w w . java2 s. com if (response == null || MapUtils.isEmpty(response.getHighlighting()) || page == null) { return Collections.emptyList(); } List<HighlightEntry<T>> mappedHighlights = new ArrayList<HighlightEntry<T>>(page.getSize()); Map<String, Map<String, List<String>>> highlighting = response.getHighlighting(); for (T item : page) { HighlightEntry<T> highlightEntry = processHighlightingForPageEntry(highlighting, item); mappedHighlights.add(highlightEntry); } page.setHighlighted(mappedHighlights); return mappedHighlights; }
From source file:com.ibm.watson.apis.conversation_enhanced.retrieve_and_rank.Client.java
License:Open Source License
/** * This method uses the Query object to send the user's query (the * <code>input</code> param) to the retrieve and rank service * //from w w w.j a v a 2s. c o m * @param input The user's query to be sent to the retrieve and rank service * @return A list of DocumentPayload objects, each representing a single document the retrieve and * rank service believes is a possible answer to the user's query * @throws SolrServerException * @throws IOException */ public List<DocumentPayload> getDocuments(String input) throws Exception { List<DocumentPayload> documents = new ArrayList<DocumentPayload>(); QueryResponse output = new Query().query(input); documents = createPayload(input, new Gson().toJson(output.getResults()), new Gson().toJson(output.getHighlighting())); return documents; }
From source file:com.liferay.portal.search.solr.internal.SolrIndexSearcher.java
License:Open Source License
protected Hits processResponse(QueryResponse queryResponse, SearchContext searchContext, Query query) { long startTime = System.currentTimeMillis(); SolrDocumentList solrDocumentList = queryResponse.getResults(); updateFacetCollectors(queryResponse, searchContext); Hits hits = new HitsImpl(); List<Document> documents = new ArrayList<>(); Set<String> queryTerms = new HashSet<>(); List<Float> scores = new ArrayList<>(); QueryConfig queryConfig = query.getQueryConfig(); Map<String, Map<String, List<String>>> highlights = queryResponse.getHighlighting(); for (SolrDocument solrDocument : solrDocumentList) { Document document = processSolrDocument(solrDocument, queryConfig); documents.add(document);/*from w w w . j a v a2 s . c om*/ addSnippets(solrDocument, document, queryConfig, queryTerms, highlights); float score = GetterUtil.getFloat(String.valueOf(solrDocument.getFieldValue("score"))); scores.add(score); } hits.setDocs(documents.toArray(new Document[documents.size()])); hits.setLength((int) solrDocumentList.getNumFound()); hits.setQuery(query); hits.setQueryTerms(queryTerms.toArray(new String[queryTerms.size()])); hits.setScores(ArrayUtil.toFloatArray(scores)); hits.setSearchTime(queryResponse.getQTime()); hits.setStart(startTime); return hits; }
From source file:com.liferay.portal.search.solr.SolrIndexSearcher.java
License:Open Source License
protected Hits processQueryResponse(QueryResponse queryResponse, SearchContext searchContext, Query query) throws Exception { long startTime = System.currentTimeMillis(); SolrDocumentList solrDocumentList = queryResponse.getResults(); updateFacetCollectors(queryResponse, searchContext); Hits hits = new HitsImpl(); List<Document> documents = new ArrayList<Document>(); Set<String> queryTerms = new HashSet<String>(); List<Float> scores = new ArrayList<Float>(); QueryConfig queryConfig = query.getQueryConfig(); Map<String, Map<String, List<String>>> highlights = queryResponse.getHighlighting(); for (SolrDocument solrDocument : solrDocumentList) { Document document = processSolrDocument(solrDocument); documents.add(document);//from w ww . j a v a 2s. com addSnippets(solrDocument, document, queryConfig, queryTerms, highlights); float score = GetterUtil.getFloat(String.valueOf(solrDocument.getFieldValue("score"))); scores.add(score); } hits.setDocs(documents.toArray(new Document[documents.size()])); hits.setLength((int) solrDocumentList.getNumFound()); hits.setQuery(query); hits.setQueryTerms(queryTerms.toArray(new String[queryTerms.size()])); hits.setScores(ArrayUtil.toFloatArray(scores)); hits.setSearchTime(queryResponse.getQTime()); hits.setStart(startTime); return hits; }
From source file:com.liferay.portal.search.solr.SolrIndexSearcherImpl.java
License:Open Source License
protected Hits subset(SolrQuery solrQuery, Query query, QueryConfig queryConfig, QueryResponse queryResponse, boolean allResults) throws Exception { long startTime = System.currentTimeMillis(); Hits hits = new HitsImpl(); SolrDocumentList solrDocumentList = queryResponse.getResults(); long total = solrDocumentList.getNumFound(); if (allResults && (total > 0)) { solrQuery.setRows((int) total); queryResponse = _solrServer.query(solrQuery); return subset(solrQuery, query, queryConfig, queryResponse, false); }//from w w w. j ava 2 s. c o m float maxScore = 1; if (queryConfig.isScoreEnabled()) { maxScore = solrDocumentList.getMaxScore(); } int subsetTotal = solrDocumentList.size(); Document[] documents = new DocumentImpl[subsetTotal]; String[] snippets = new String[subsetTotal]; float[] scores = new float[subsetTotal]; int j = 0; Set<String> queryTerms = new HashSet<String>(); Map<String, Map<String, List<String>>> highlights = queryResponse.getHighlighting(); for (SolrDocument solrDocument : solrDocumentList) { Document document = new DocumentImpl(); Collection<String> names = solrDocument.getFieldNames(); for (String name : names) { Collection<Object> fieldValues = solrDocument.getFieldValues(name); Field field = new Field(name, ArrayUtil.toStringArray(fieldValues.toArray(new Object[fieldValues.size()]))); document.add(field); } float score = 1; if (queryConfig.isScoreEnabled()) { score = GetterUtil.getFloat(String.valueOf(solrDocument.getFieldValue("score"))); } documents[j] = document; if (queryConfig.isHighlightEnabled()) { snippets[j] = getSnippet(solrDocument, queryTerms, highlights); } else { snippets[j] = StringPool.BLANK; } scores[j] = score / maxScore; j++; } float searchTime = (float) (System.currentTimeMillis() - startTime) / Time.SECOND; hits.setDocs(documents); hits.setLength((int) total); hits.setQuery(query); hits.setQueryTerms(queryTerms.toArray(new String[queryTerms.size()])); hits.setScores(scores); hits.setSearchTime(searchTime); hits.setSnippets(snippets); hits.setStart(startTime); return hits; }
From source file:com.mycompany.solr_web_application.Simple_Query_Solr.java
public static void main(String[] args) { try {/* www . j a v a 2 s .c om*/ String url = null; HttpSolrServer server = null; url = "http://localhost:8983/solr/wiki"; server = new HttpSolrServer(url); server.setMaxRetries(1); server.setConnectionTimeout(20000); server.setParser(new XMLResponseParser()); server.setSoTimeout(10000); server.setDefaultMaxConnectionsPerHost(100); server.setMaxTotalConnections(100); server.setFollowRedirects(false); server.setAllowCompression(true); SolrQuery query = new SolrQuery(); query.setQuery("india"); query.setQuery("india"); query.setFields(new String[] { "id", "name", "contents" }); query.setHighlight(true); //set other params as needed query.setParam("hl.fl", "name,contents"); query.setParam("hl.simple.pre", "<em>"); query.setParam("hl.simple.post", "</em>"); query.setParam("hl.fragsize", "100"); QueryResponse queryResponse = server.query(query); //System.out.println(queryResponse); //response = server.query(solrQuery); Iterator<SolrDocument> iter = queryResponse.getResults().iterator(); while (iter.hasNext()) { SolrDocument resultDoc = iter.next(); String id = (String) resultDoc.getFieldValue("id"); //System.out.println(id); //String id = (String) resultDoc.getFieldValue("id"); //id is the uniqueKey field if (queryResponse.getHighlighting().get(id) != null) { List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get("name"); List<String> highlightSnippets1 = queryResponse.getHighlighting().get(id).get("contents"); // System.out.println("name "+highlightSnippets); // System.out.println("content "+highlightSnippets1); } } //String jsonString = JSONUtil.toJSON(queryResponse); //ResponseWrapper data = new Gson().fromJson(jsonString, ResponseWrapper.class); System.out.println("Highlighting data " + queryResponse.getHighlighting()); } catch (Exception e) { e.printStackTrace(); } }