Skip to content

Commit

Permalink
#22168 Correct the generated REST URLs from Content Search 'Show Quer…
Browse files Browse the repository at this point in the history
…y' (#22590)
  • Loading branch information
freddyDOTCMS committed Jul 22, 2022
1 parent 1d539c1 commit 45f1d89
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import com.dotcms.contenttype.model.type.PageContentType;
import com.dotcms.enterprise.FormAJAXProxy;
import com.dotcms.keyvalue.model.KeyValue;
import com.dotcms.repackage.com.google.common.base.Preconditions;
import com.dotcms.repackage.org.directwebremoting.WebContextFactory;
import com.dotcms.util.LogTime;
import com.dotmarketing.beans.Host;
Expand Down Expand Up @@ -130,6 +131,8 @@
*/
public class ContentletAjax {

private static String VELOCITY_CODE_TEMPLATE = "#foreach($con in $dotcontent.pull(\"%s\",10,\"%s\"))<br/>%s<br/>#end";

private static final String CONTENT_TYPES_INODE_SEPARATOR = ",";

private java.text.DateFormat modDateFormat = java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.SHORT,
Expand Down Expand Up @@ -578,6 +581,7 @@ public List searchContentletsByUser(List<BaseContentType> types, String structur
Map<String, Object> lastSearchMap = new HashMap<String, Object>();

List<String> relatedIdentifiers = new ArrayList();
List<RelationshipFieldData> relationshipFields = new ArrayList();
final StringBuilder relatedQueryByChild = new StringBuilder();

if (UtilMethods.isSet(sess)) {
Expand Down Expand Up @@ -692,6 +696,7 @@ public List searchContentletsByUser(List<BaseContentType> types, String structur
Collectors.toList());
}

relationshipFields.add(new RelationshipFieldData(fieldName, fieldValue));
continue;
}
}
Expand Down Expand Up @@ -970,18 +975,17 @@ else if( fieldbcontentname.startsWith("date") ){

luceneQuery.append(" +working:true");
final String luceneQueryToShow= luceneQuery.toString().replaceAll("\\s+", " ");
//filter related content
if (!relatedIdentifiers.isEmpty()) {
luceneQuery.append(" +identifier:(")
.append(String.join(" OR ", relatedIdentifiers)).append(") ");
}

//Executing the query
long before = System.currentTimeMillis();
PaginatedArrayList <ContentletSearch> hits = new PaginatedArrayList <>();
long totalHits=0;
try{
hits =(PaginatedArrayList)conAPI.searchIndex(luceneQuery.toString(), perPage, offset, finalSort, currentUser, false);
final String luceneQueryTOElasticSearch = relatedIdentifiers.isEmpty() ?
luceneQuery.toString() :
appendRelatedIdentifierToQuery(luceneQuery.toString(), relatedIdentifiers);

hits =(PaginatedArrayList)conAPI.searchIndex(luceneQueryTOElasticSearch, perPage, offset, finalSort, currentUser, false);

totalHits = hits.getTotalResults();
}catch (Exception pe) {
Expand Down Expand Up @@ -1055,7 +1059,14 @@ else if( fieldbcontentname.startsWith("date") ){
.replaceAll("\\+working:[a-zA-Z]*","").replaceAll("\\s+", " ").trim();

counters.put("luceneQueryRaw", luceneQueryToShow);
counters.put("luceneQueryFrontend", luceneQueryToShow2.replace("\"","\\${esc.quote}"));

final String luceneQueryFormatted = luceneQueryToShow2.replace("\"","\\${esc.quote}");
final String velocityCode = String.format(VELOCITY_CODE_TEMPLATE,
luceneQueryFormatted,
finalSort,
UtilMethods.isSet(relationshipFields) ? getRelationshipVelocityCode(relationshipFields) : "...");

counters.put("velocityCode", velocityCode);
counters.put("relatedQueryByChild",
relatedQueryByChild.length() > 0 ? relatedQueryByChild.toString() : null);
counters.put("sortByUF", finalSort);
Expand Down Expand Up @@ -1087,6 +1098,40 @@ else if( fieldbcontentname.startsWith("date") ){
return results;
}

private String appendRelatedIdentifierToQuery(final String luceneQuery,
final List<String> relatedIdentifiers) {

Preconditions.checkArgument(UtilMethods.isSet(relatedIdentifiers), "relatedIdentifiers can not be empty or null");
final StringBuffer result = new StringBuffer(luceneQuery);

return result.append(" +identifier:(")
.append(String.join(" OR ", relatedIdentifiers)).append(") ")
.toString();
}

private String getRelationshipVelocityCode(final List<RelationshipFieldData> relationshipFields) {
final String setCodeTemplate = "<span style='margin-left: 20px'>"
+ "#set( $related_%s = $dotcontent.pullRelatedField( \"$con.identifier\", \"%s\", \"+identifier:%s\") )"
+ "</span>";
final String conditionCodeTemplate = "!$related_%s.isEmpty()";
final String velocityCodeTemplate = "<span style='margin-left: 20px'>#if (%s)</span><br>"
+ "<span style='margin-left: 40px'>...</span><br>"
+ "<span style='margin-left: 20px'>#end</span>";

final String setCode = relationshipFields.stream()
.map(relationshipField -> String.format(setCodeTemplate,
relationshipField.fieldName.replaceAll("\\.", StringPool.BLANK),
relationshipField.fieldName,
relationshipField.fieldValue))
.collect(Collectors.joining("\n"));

final String conditionCode = relationshipFields.stream()
.map(relationshipField -> String.format(conditionCodeTemplate, relationshipField.fieldName.replaceAll("\\.", StringPool.BLANK)))
.collect(Collectors.joining(" && "));

return setCode + "<br>" + String.format(velocityCodeTemplate, conditionCode);
}

private void addContentMapsToResults(String structureInode, int perPage, User currentUser,
Map<String, Field> fieldsMapping, PaginatedArrayList<ContentletSearch> hits,
List<Object> results, List<String> expiredInodes, final boolean exporting) {
Expand Down Expand Up @@ -2613,5 +2658,14 @@ private List<Map<String, String>> findAllLangContentlets(final String contentlet
return builder.build();
}

private class RelationshipFieldData {
String fieldName;
String fieldValue;

public RelationshipFieldData(String fieldName, String fieldValue) {
this.fieldName = fieldName;
this.fieldValue = fieldValue;
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -2554,10 +2554,7 @@ final String calendarEventInode = null!=calendarEventSt ? calendarEventSt.inode(
function fillQuery (counters) {
<%
String restBaseUrl="http://"+
APILocator.getHostAPI().find((String)session.getAttribute(com.dotmarketing.util.WebKeys.CMS_SELECTED_HOST_ID), user, false).getHostname()+
((request.getLocalPort()!=80) ? ":"+request.getLocalPort() : "")+
"/api/content/render/false";
String restBaseUrl= "/api/content/render/false";
String restBasePostUrl="http://"+
APILocator.getHostAPI().find((String)session.getAttribute(com.dotmarketing.util.WebKeys.CMS_SELECTED_HOST_ID), user, false).getHostname()+
Expand All @@ -2570,7 +2567,7 @@ final String calendarEventInode = null!=calendarEventSt ? calendarEventSt.inode(
var encodedQueryRaw = queryRaw.replace(/'/g, "%27").replace(/"/g, "%22");
var queryfield=document.getElementById("luceneQuery");
queryfield.value=queryRaw;
var queryFrontend = counters["luceneQueryFrontend"];
var velocityCode = counters["velocityCode"];
var relatedQueryByChild = counters["relatedQueryByChild"];
var sortBy = counters["sortByUF"];
var div = document.getElementById("queryResults");
Expand All @@ -2587,7 +2584,7 @@ final String calendarEventInode = null!=calendarEventSt ? calendarEventSt.inode(
div.innerHTML = "<div class='contentViewDialog' style=\"white-space: pre;\">" +
"<div class='contentViewTitle'><%= LanguageUtil.get(pageContext, "frontend-query") %></div>"+
"<div class='contentViewQuery'><code>#foreach($con in $dotcontent.pull(\"" + queryFrontend + "\",10,\"" + sortBy + "\"))<br/>...<br/>#end</code></div>";
"<div class='contentViewQuery'><code>" + velocityCode + "</code></div>";
if (relatedQueryByChild == null){
div.innerHTML += "<div class='contentViewTitle'><%= LanguageUtil.get(pageContext, "The-actual-query-") %></div>"+
Expand Down Expand Up @@ -2623,13 +2620,6 @@ final String calendarEventInode = null!=calendarEventSt ? calendarEventSt.inode(
"<div class='contentViewTitle'><%= LanguageUtil.get(pageContext, "rest-api-call-urlencoded") %></div>"+
"<div class='contentViewQuery'><code>"+apicall_urlencode+"</code></div>"+
"<div class='contentViewQuery' style='padding:20px;padding-top:10px;color:#333;'>REST API: " +
"<span class='dot-api-link' " +
"onClick=\"queryContentJSONPost('<%= restBasePostUrl %>', '" + encodedQueryRaw + "', '" + sortBy + "')\">API</span></a>"+
"</div>"+
"<b><%= LanguageUtil.get(pageContext, "Ordered-by") %>:</b> " + sortBy +
"<ul><li><%= LanguageUtil.get(pageContext, "message.contentlet.hint2") %> " +
"</li><li><%= LanguageUtil.get(pageContext, "message.contentlet.hint3") %> " +
Expand Down

0 comments on commit 45f1d89

Please sign in to comment.