001/* 002 * Copyright 2016 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.ametys.cms.search.query; 017 018import java.util.ArrayList; 019import java.util.Arrays; 020import java.util.Collection; 021import java.util.List; 022 023import org.ametys.cms.content.indexing.solr.SolrFieldHelper; 024 025/** 026 * Represents a {@link Query} on a joined document. 027 */ 028public class JoinQuery implements Query 029{ 030 031 /** The field path. */ 032 protected Query _subQuery; 033 034 /** The join paths */ 035 protected List<String> _joinPaths; 036 037 /** 038 * Build a join query. 039 * @param subQuery The sub query. 040 * @param joinPaths The field's join paths 041 */ 042 public JoinQuery(Query subQuery, String... joinPaths) 043 { 044 _subQuery = subQuery; 045 _joinPaths = Arrays.asList(joinPaths); 046 } 047 048 /** 049 * Build a join query. 050 * @param subQuery The sub query. 051 * @param joinPaths The field's join paths 052 */ 053 public JoinQuery(Query subQuery, Collection<String> joinPaths) 054 { 055 _subQuery = subQuery; 056 _joinPaths = new ArrayList<>(joinPaths); 057 } 058 059 @Override 060 public String build() throws QuerySyntaxException 061 { 062 StringBuilder queryString = new StringBuilder(); 063 064 queryString.append("{!ametys join="); 065 boolean first = true; 066 for (String path : _joinPaths) 067 { 068 if (!first) 069 { 070 queryString.append("->"); 071 } 072 first = false; 073 queryString.append(SolrFieldHelper.getJoinFieldName(path)); 074 } 075 076 queryString.append(" q=\"") 077 .append(_subQuery.build().replace("\"", "\\\"")) 078 .append("\"}"); 079 080 return queryString.toString(); 081 } 082 083}