View Javadoc
1   /*
2    * This file is part of ***  M y C o R e  ***
3    * See http://www.mycore.de/ for details.
4    *
5    * MyCoRe is free software: you can redistribute it and/or modify
6    * it under the terms of the GNU General Public License as published by
7    * the Free Software Foundation, either version 3 of the License, or
8    * (at your option) any later version.
9    *
10   * MyCoRe is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with MyCoRe.  If not, see <http://www.gnu.org/licenses/>.
17   */
18  
19  package org.mycore.solr.search;
20  
21  import static org.mycore.solr.MCRSolrConstants.SOLR_QUERY_PATH;
22  import static org.mycore.solr.MCRSolrConstants.SOLR_QUERY_XML_PROTOCOL_VERSION;
23  
24  import java.io.IOException;
25  import java.io.InputStream;
26  import java.net.MalformedURLException;
27  import java.net.URL;
28  import java.net.URLEncoder;
29  import java.nio.charset.StandardCharsets;
30  import java.text.MessageFormat;
31  import java.util.Locale;
32  import java.util.Optional;
33  
34  import org.apache.logging.log4j.LogManager;
35  import org.apache.logging.log4j.Logger;
36  import org.apache.solr.client.solrj.SolrQuery.ORDER;
37  import org.apache.solr.client.solrj.impl.HttpSolrClient;
38  
39  /**
40   * Convenience class for holding the parameters for the solr search url.
41   *
42   * @author shermann
43   */
44  public class MCRSolrURL {
45      private static final Logger LOGGER = LogManager.getLogger(MCRSolrURL.class);
46  
47      public static final String FIXED_URL_PART = new MessageFormat("?version={0}", Locale.ROOT)
48          .format(new Object[] { SOLR_QUERY_XML_PROTOCOL_VERSION });
49  
50      private HttpSolrClient solrClient;
51  
52      private String urlQuery, q, sortOptions, wt;
53  
54      private int start, rows;
55  
56      boolean returnScore;
57  
58      private Optional<String> requestHandler;
59  
60      private MCRSolrURL() {
61          requestHandler = Optional.empty();
62      }
63  
64      /**
65       * @param solrClient the solr server connection to use
66       */
67      public MCRSolrURL(HttpSolrClient solrClient) {
68          this();
69          this.solrClient = solrClient;
70          start = 0;
71          rows = 10;
72          q = null;
73          wt = null;
74          sortOptions = "";
75          returnScore = false;
76      }
77  
78      /**
79       * Creates a new solr url using your own url query. Be aware that you cannot
80       * use the MCRSolrURL setter methods to edit your request. Only the urlQuery is
81       * used.
82       *
83       * @param solrClient the solr server connection to use
84       * @param urlQuery e.g. q=allMeta:Hello&amp;rows=20&amp;defType=edismax
85       */
86      public MCRSolrURL(HttpSolrClient solrClient, String urlQuery) {
87          this();
88          this.solrClient = solrClient;
89          this.urlQuery = urlQuery;
90      }
91  
92      /**
93       * @param solrClient the solr server connection to use
94       * @param returnScore specify whether to return the score with results;
95       */
96      public MCRSolrURL(HttpSolrClient solrClient, boolean returnScore) {
97          this(solrClient);
98          this.returnScore = returnScore;
99      }
100 
101     /**
102      * @return a ready to invoke {@link URL} object or null
103      */
104     public URL getUrl() {
105         try {
106             if (this.urlQuery == null) {
107                 return new URL(
108                     solrClient.getBaseURL() + getRequestHandler() + FIXED_URL_PART + "&q=" + URLEncoder
109                         .encode(q, StandardCharsets.UTF_8)
110                         + "&start=" + start
111                         + "&rows=" + rows + "&sort=" + URLEncoder.encode(sortOptions, StandardCharsets.UTF_8)
112                         + (returnScore ? "&fl=*,score" : "")
113                         + (wt != null ? "&wt=" + wt : ""));
114             } else {
115                 return new URL(solrClient.getBaseURL() + getRequestHandler() + FIXED_URL_PART + "&" + urlQuery);
116             }
117         } catch (Exception urlException) {
118             LOGGER.error("Error building solr url", urlException);
119         }
120 
121         return null;
122     }
123 
124     /**
125      * Invoke this method to get a {@link URL} referring to the luke interface of a solr server. 
126      * Under this URL one can find useful information about the solr schema. 
127      *
128      * @return a {@link URL} refering to the luke interface or null
129      */
130     public URL getLukeURL() {
131         try {
132             return new URL(solrClient.getBaseURL() + "/admin/luke");
133         } catch (MalformedURLException e) {
134             LOGGER.error("Error building solr luke url", e);
135         }
136         return null;
137     }
138 
139     /**
140      * An abbreviation for getUrl().openStream();
141      */
142     public InputStream openStream() throws IOException {
143         URL url = this.getUrl();
144         LOGGER.info(url.toString());
145         return url.openStream();
146     }
147 
148     /**
149      * Adds a sort option to the solr url.
150      *
151      * @param sortBy the name of the field to sort by
152      * @param order the sort order, one can use {@link ORDER#asc} or {@link ORDER#desc}
153      */
154     public void addSortOption(String sortBy, String order) {
155         if (sortOptions.length() > 0) {
156             sortOptions += ",";
157         }
158         sortOptions += sortBy + " " + (order != null ? order : "desc");
159     }
160 
161     /**
162      * Adds a sort option to the solr url
163      *
164      * @param sort the sort option e.g. 'maintitle desc'
165      */
166     public void addSortOption(String sort) {
167         if (sort == null || sort.equals("")) {
168             return;
169         }
170         if (sortOptions.length() > 0) {
171             sortOptions += ",";
172         }
173         sortOptions += sort;
174     }
175 
176     /**
177      * Sets the unencoded query parameter.
178      */
179     public void setQueryParamter(String query) {
180         this.q = query;
181     }
182 
183     /**
184      * @return the query parameter
185      */
186     public String getQueryParamter() {
187         return this.q;
188     }
189 
190     /**
191      * @return the start parameter
192      */
193     public int getStart() {
194         return start;
195     }
196 
197     /**
198      * @return the rows parameter
199      */
200     public int getRows() {
201         return rows;
202     }
203 
204     /**
205      * Sets the start parameter.
206      */
207     public void setStart(int start) {
208         this.start = start;
209 
210     }
211 
212     /**
213      * Sets the rows parameter.
214      */
215     public void setRows(int rows) {
216         this.rows = rows;
217     }
218 
219     public void setReturnScore(boolean yesOrNo) {
220         this.returnScore = yesOrNo;
221     }
222 
223     /**
224      * The wt (writer type) parameter is used by Solr to determine which QueryResponseWriter should be
225      * used to process the request. Valid values are any of the names specified by &lt;queryResponseWriter... /&gt;
226      * declarations in solrconfig.xml. The default value is "standard" (xml).
227      */
228     public void setWriterType(String wt) {
229         this.wt = wt;
230     }
231 
232     /**
233      * @return true if the score is returned with the results, false otherwise
234      */
235     public boolean returnsScore() {
236         return this.returnScore;
237     }
238 
239     /**
240      * Sets the solr request handler.
241      *
242      * @param requestHandler the name of the request handler to set e.g. /foo
243      * */
244     public void setRequestHandler(String requestHandler) {
245         this.requestHandler = Optional.ofNullable(requestHandler);
246     }
247 
248     /**
249      * Returns the current request handler.
250      *
251      * @return the solr request handler
252      * */
253     public String getRequestHandler() {
254         return this.requestHandler.orElse(SOLR_QUERY_PATH);
255     }
256 }