Skip to content

Apache Lucene open-source search software

add missing svn:eol-style

Robert Muir9af1a725691c
diff --git a/lucene/src/java/org/apache/lucene/queryParser/QueryParserBase.java b/lucene/src/java/org/apache/lucene/queryParser/QueryParserBase.java
index 078e2adfb63..41ad00987ed 100644
--- a/lucene/src/java/org/apache/lucene/queryParser/QueryParserBase.java
+++ b/lucene/src/java/org/apache/lucene/queryParser/QueryParserBase.java
@@ -1,1150 +1,1150 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.lucene.queryParser;
-
-import java.io.IOException;
-import java.io.StringReader;
-import java.text.Collator;
-import java.text.DateFormat;
-import java.util.*;
-
-import org.apache.lucene.analysis.Analyzer;
-import org.apache.lucene.analysis.CachingTokenFilter;
-import org.apache.lucene.analysis.TokenStream;
-import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
-import org.apache.lucene.analysis.tokenattributes.TermToBytesRefAttribute;
-import org.apache.lucene.document.DateTools;
-import org.apache.lucene.index.Term;
-import org.apache.lucene.queryParser.QueryParser.Operator;
-import org.apache.lucene.search.*;
-import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.Version;
-
-/** This class is overridden by QueryParser in QueryParser.jj
- * and acts to separate the majority of the Java code from the .jj grammar file.
- */
-public abstract class QueryParserBase {
-
- /** Do not catch this exception in your code, it means you are using methods that you should no longer use. */
- public static class MethodRemovedUseAnother extends Throwable {}
-
- static final int CONJ_NONE = 0;
- static final int CONJ_AND = 1;
- static final int CONJ_OR = 2;
-
- static final int MOD_NONE = 0;
- static final int MOD_NOT = 10;
- static final int MOD_REQ = 11;
-
- // make it possible to call setDefaultOperator() without accessing
- // the nested class:
- /** Alternative form of QueryParser.Operator.AND */
- public static final Operator AND_OPERATOR = Operator.AND;
- /** Alternative form of QueryParser.Operator.OR */
- public static final Operator OR_OPERATOR = Operator.OR;
-
- /** The actual operator that parser uses to combine query terms */
- Operator operator = OR_OPERATOR;
-
- boolean lowercaseExpandedTerms = true;
- MultiTermQuery.RewriteMethod multiTermRewriteMethod = MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT;
- boolean allowLeadingWildcard = false;
- boolean enablePositionIncrements = true;
-
- Analyzer analyzer;
- String field;
- int phraseSlop = 0;
- float fuzzyMinSim = FuzzyQuery.defaultMinSimilarity;
- int fuzzyPrefixLength = FuzzyQuery.defaultPrefixLength;
- Locale locale = Locale.getDefault();
-
- // the default date resolution
- DateTools.Resolution dateResolution = null;
- // maps field names to date resolutions
- Map<String,DateTools.Resolution> fieldToDateResolution = null;
-
- // The collator to use when determining range inclusion,
- // for use when constructing RangeQuerys.
- Collator rangeCollator = null;
-
- boolean autoGeneratePhraseQueries;
-
- // So the generated QueryParser(CharStream) won't error out
- protected QueryParserBase() {
- }
-
- /** Initializes a query parser. Called by the QueryParser constructor
- * @param matchVersion Lucene version to match. See <a href="#version">above</a>.
- * @param f the default field for query terms.
- * @param a used to find terms in the query text.
- */
- public void init(Version matchVersion, String f, Analyzer a) {
- analyzer = a;
- field = f;
- if (matchVersion.onOrAfter(Version.LUCENE_31)) {
- setAutoGeneratePhraseQueries(false);
- } else {
- setAutoGeneratePhraseQueries(true);
- }
- }
-
- // the generated parser will create these in QueryParser
- public abstract void ReInit(CharStream stream);
- public abstract Query TopLevelQuery(String field) throws ParseException;
-
-
- /** Parses a query string, returning a {@link org.apache.lucene.search.Query}.
- * @param query the query string to be parsed.
- * @throws ParseException if the parsing fails
- */
- public Query parse(String query) throws ParseException {
- ReInit(new FastCharStream(new StringReader(query)));
- try {
- // TopLevelQuery is a Query followed by the end-of-input (EOF)
- Query res = TopLevelQuery(field);
- return res!=null ? res : newBooleanQuery(false);
- }
- catch (ParseException tme) {
- // rethrow to include the original query:
- ParseException e = new ParseException("Cannot parse '" +query+ "': " + tme.getMessage());
- e.initCause(tme);
- throw e;
- }
- catch (TokenMgrError tme) {
- ParseException e = new ParseException("Cannot parse '" +query+ "': " + tme.getMessage());
- e.initCause(tme);
- throw e;
- }
- catch (BooleanQuery.TooManyClauses tmc) {
- ParseException e = new ParseException("Cannot parse '" +query+ "': too many boolean clauses");
- e.initCause(tmc);
- throw e;
- }
- }
-
-
- /**
- * @return Returns the analyzer.
- */
- public Analyzer getAnalyzer() {
- return analyzer;
- }
-
- /**
- * @return Returns the default field.
- */
- public String getField() {
- return field;
- }
-
- /**
- * @see #setAutoGeneratePhraseQueries(boolean)
- */
- public final boolean getAutoGeneratePhraseQueries() {
- return autoGeneratePhraseQueries;
- }
-
- /**
- * Set to true if phrase queries will be automatically generated
- * when the analyzer returns more than one term from whitespace
- * delimited text.
- * NOTE: this behavior may not be suitable for all languages.
- * <p>
- * Set to false if phrase queries should only be generated when
- * surrounded by double quotes.
- */
- public final void setAutoGeneratePhraseQueries(boolean value) {
- this.autoGeneratePhraseQueries = value;
- }
-
- /**
- * Get the minimal similarity for fuzzy queries.
- */
- public float getFuzzyMinSim() {
- return fuzzyMinSim;
- }
-
- /**
- * Set the minimum similarity for fuzzy queries.
- * Default is 2f.
- */
- public void setFuzzyMinSim(float fuzzyMinSim) {
- this.fuzzyMinSim = fuzzyMinSim;
- }
-
- /**
- * Get the prefix length for fuzzy queries.
- * @return Returns the fuzzyPrefixLength.
- */
- public int getFuzzyPrefixLength() {
- return fuzzyPrefixLength;
- }
-
- /**
- * Set the prefix length for fuzzy queries. Default is 0.
- * @param fuzzyPrefixLength The fuzzyPrefixLength to set.
- */
- public void setFuzzyPrefixLength(int fuzzyPrefixLength) {
- this.fuzzyPrefixLength = fuzzyPrefixLength;
- }
-
- /**
- * Sets the default slop for phrases. If zero, then exact phrase matches
- * are required. Default value is zero.
- */
- public void setPhraseSlop(int phraseSlop) {
- this.phraseSlop = phraseSlop;
- }
-
- /**
- * Gets the default slop for phrases.
- */
- public int getPhraseSlop() {
- return phraseSlop;
- }
-
-
- /**
- * Set to <code>true</code> to allow leading wildcard characters.
- * <p>
- * When set, <code>*</code> or <code>?</code> are allowed as
- * the first character of a PrefixQuery and WildcardQuery.
- * Note that this can produce very slow
- * queries on big indexes.
- * <p>
- * Default: false.
- */
- public void setAllowLeadingWildcard(boolean allowLeadingWildcard) {
- this.allowLeadingWildcard = allowLeadingWildcard;
- }
-
- /**
- * @see #setAllowLeadingWildcard(boolean)
- */
- public boolean getAllowLeadingWildcard() {
- return allowLeadingWildcard;
- }
-
- /**
- * Set to <code>true</code> to enable position increments in result query.
- * <p>
- * When set, result phrase and multi-phrase queries will
- * be aware of position increments.
- * Useful when e.g. a StopFilter increases the position increment of
- * the token that follows an omitted token.
- * <p>
- * Default: true.
- */
- public void setEnablePositionIncrements(boolean enable) {
- this.enablePositionIncrements = enable;
- }
-
- /**
- * @see #setEnablePositionIncrements(boolean)
- */
- public boolean getEnablePositionIncrements() {
- return enablePositionIncrements;
- }
-
- /**
- * Sets the boolean operator of the QueryParser.
- * In default mode (<code>OR_OPERATOR</code>) terms without any modifiers
- * are considered optional: for example <code>capital of Hungary</code> is equal to
- * <code>capital OR of OR Hungary</code>.<br/>
- * In <code>AND_OPERATOR</code> mode terms are considered to be in conjunction: the
- * above mentioned query is parsed as <code>capital AND of AND Hungary</code>
- */
- public void setDefaultOperator(Operator op) {
- this.operator = op;
- }
-
-
- /**
- * Gets implicit operator setting, which will be either AND_OPERATOR
- * or OR_OPERATOR.
- */
- public Operator getDefaultOperator() {
- return operator;
- }
-
-
- /**
- * Whether terms of wildcard, prefix, fuzzy and range queries are to be automatically
- * lower-cased or not. Default is <code>true</code>.
- */
- public void setLowercaseExpandedTerms(boolean lowercaseExpandedTerms) {
- this.lowercaseExpandedTerms = lowercaseExpandedTerms;
- }
-
-
- /**
- * @see #setLowercaseExpandedTerms(boolean)
- */
- public boolean getLowercaseExpandedTerms() {
- return lowercaseExpandedTerms;
- }
-
- /**
- * By default QueryParser uses {@link org.apache.lucene.search.MultiTermQuery#CONSTANT_SCORE_AUTO_REWRITE_DEFAULT}
- * when creating a PrefixQuery, WildcardQuery or RangeQuery. This implementation is generally preferable because it
- * a) Runs faster b) Does not have the scarcity of terms unduly influence score
- * c) avoids any "TooManyBooleanClauses" exception.
- * However, if your application really needs to use the
- * old-fashioned BooleanQuery expansion rewriting and the above
- * points are not relevant then use this to change
- * the rewrite method.
- */
- public void setMultiTermRewriteMethod(MultiTermQuery.RewriteMethod method) {
- multiTermRewriteMethod = method;
- }
-
-
- /**
- * @see #setMultiTermRewriteMethod
- */
- public MultiTermQuery.RewriteMethod getMultiTermRewriteMethod() {
- return multiTermRewriteMethod;
- }
-
- /**
- * Set locale used by date range parsing.
- */
- public void setLocale(Locale locale) {
- this.locale = locale;
- }
-
- /**
- * Returns current locale, allowing access by subclasses.
- */
- public Locale getLocale() {
- return locale;
- }
-
- /**
- * Sets the default date resolution used by RangeQueries for fields for which no
- * specific date resolutions has been set. Field specific resolutions can be set
- * with {@link #setDateResolution(String, org.apache.lucene.document.DateTools.Resolution)}.
- *
- * @param dateResolution the default date resolution to set
- */
- public void setDateResolution(DateTools.Resolution dateResolution) {
- this.dateResolution = dateResolution;
- }
-
- /**
- * Sets the date resolution used by RangeQueries for a specific field.
- *
- * @param fieldName field for which the date resolution is to be set
- * @param dateResolution date resolution to set
- */
- public void setDateResolution(String fieldName, DateTools.Resolution dateResolution) {
- if (fieldName == null) {
- throw new IllegalArgumentException("Field cannot be null.");
- }
-
- if (fieldToDateResolution == null) {
- // lazily initialize HashMap
- fieldToDateResolution = new HashMap<String,DateTools.Resolution>();
- }
-
- fieldToDateResolution.put(fieldName, dateResolution);
- }
-
- /**
- * Returns the date resolution that is used by RangeQueries for the given field.
- * Returns null, if no default or field specific date resolution has been set
- * for the given field.
- *
- */
- public DateTools.Resolution getDateResolution(String fieldName) {
- if (fieldName == null) {
- throw new IllegalArgumentException("Field cannot be null.");
- }
-
- if (fieldToDateResolution == null) {
- // no field specific date resolutions set; return default date resolution instead
- return this.dateResolution;
- }
-
- DateTools.Resolution resolution = fieldToDateResolution.get(fieldName);
- if (resolution == null) {
- // no date resolutions set for the given field; return default date resolution instead
- resolution = this.dateResolution;
- }
-
- return resolution;
- }
-
- /**
- * Sets the collator used to determine index term inclusion in ranges
- * for RangeQuerys.
- * <p/>
- * <strong>WARNING:</strong> Setting the rangeCollator to a non-null
- * collator using this method will cause every single index Term in the
- * Field referenced by lowerTerm and/or upperTerm to be examined.
- * Depending on the number of index Terms in this Field, the operation could
- * be very slow.
- *
- * @param rc the collator to use when constructing RangeQuerys
- */
- public void setRangeCollator(Collator rc) {
- rangeCollator = rc;
- }
-
- /**
- * @return the collator used to determine index term inclusion in ranges
- * for RangeQuerys.
- */
- public Collator getRangeCollator() {
- return rangeCollator;
- }
-
- protected void addClause(List<BooleanClause> clauses, int conj, int mods, Query q) {
- boolean required, prohibited;
-
- // If this term is introduced by AND, make the preceding term required,
- // unless it's already prohibited
- if (clauses.size() > 0 && conj == CONJ_AND) {
- BooleanClause c = clauses.get(clauses.size()-1);
- if (!c.isProhibited())
- c.setOccur(BooleanClause.Occur.MUST);
- }
-
- if (clauses.size() > 0 && operator == AND_OPERATOR && conj == CONJ_OR) {
- // If this term is introduced by OR, make the preceding term optional,
- // unless it's prohibited (that means we leave -a OR b but +a OR b-->a OR b)
- // notice if the input is a OR b, first term is parsed as required; without
- // this modification a OR b would parsed as +a OR b
- BooleanClause c = clauses.get(clauses.size()-1);
- if (!c.isProhibited())
- c.setOccur(BooleanClause.Occur.SHOULD);
- }
-
- // We might have been passed a null query; the term might have been
- // filtered away by the analyzer.
- if (q == null)
- return;
-
- if (operator == OR_OPERATOR) {
- // We set REQUIRED if we're introduced by AND or +; PROHIBITED if
- // introduced by NOT or -; make sure not to set both.
- prohibited = (mods == MOD_NOT);
- required = (mods == MOD_REQ);
- if (conj == CONJ_AND && !prohibited) {
- required = true;
- }
- } else {
- // We set PROHIBITED if we're introduced by NOT or -; We set REQUIRED
- // if not PROHIBITED and not introduced by OR
- prohibited = (mods == MOD_NOT);
- required = (!prohibited && conj != CONJ_OR);
- }
- if (required && !prohibited)
- clauses.add(newBooleanClause(q, BooleanClause.Occur.MUST));
- else if (!required && !prohibited)
- clauses.add(newBooleanClause(q, BooleanClause.Occur.SHOULD));
- else if (!required && prohibited)
- clauses.add(newBooleanClause(q, BooleanClause.Occur.MUST_NOT));
- else
- throw new RuntimeException("Clause cannot be both required and prohibited");
- }
-
- /**
- * @exception org.apache.lucene.queryParser.ParseException throw in overridden method to disallow
- */
- protected Query getFieldQuery(String field, String queryText, boolean quoted) throws ParseException {
- // Use the analyzer to get all the tokens, and then build a TermQuery,
- // PhraseQuery, or nothing based on the term count
-
- TokenStream source;
- try {
- source = analyzer.reusableTokenStream(field, new StringReader(queryText));
- source.reset();
- } catch (IOException e) {
- source = analyzer.tokenStream(field, new StringReader(queryText));
- }
- CachingTokenFilter buffer = new CachingTokenFilter(source);
- TermToBytesRefAttribute termAtt = null;
- PositionIncrementAttribute posIncrAtt = null;
- int numTokens = 0;
-
- boolean success = false;
- try {
- buffer.reset();
- success = true;
- } catch (IOException e) {
- // success==false if we hit an exception
- }
- if (success) {
- if (buffer.hasAttribute(TermToBytesRefAttribute.class)) {
- termAtt = buffer.getAttribute(TermToBytesRefAttribute.class);
- }
- if (buffer.hasAttribute(PositionIncrementAttribute.class)) {
- posIncrAtt = buffer.getAttribute(PositionIncrementAttribute.class);
- }
- }
-
- int positionCount = 0;
- boolean severalTokensAtSamePosition = false;
-
- boolean hasMoreTokens = false;
- if (termAtt != null) {
- try {
- hasMoreTokens = buffer.incrementToken();
- while (hasMoreTokens) {
- numTokens++;
- int positionIncrement = (posIncrAtt != null) ? posIncrAtt.getPositionIncrement() : 1;
- if (positionIncrement != 0) {
- positionCount += positionIncrement;
- } else {
- severalTokensAtSamePosition = true;
- }
- hasMoreTokens = buffer.incrementToken();
- }
- } catch (IOException e) {
- // ignore
- }
- }
- try {
- // rewind the buffer stream
- buffer.reset();
-
- // close original stream - all tokens buffered
- source.close();
- }
- catch (IOException e) {
- // ignore
- }
-
- if (numTokens == 0)
- return null;
- else if (numTokens == 1) {
- BytesRef term = new BytesRef();
- try {
- boolean hasNext = buffer.incrementToken();
- assert hasNext == true;
- termAtt.toBytesRef(term);
- } catch (IOException e) {
- // safe to ignore, because we know the number of tokens
- }
- return newTermQuery(new Term(field, term));
- } else {
- if (severalTokensAtSamePosition || (!quoted && !autoGeneratePhraseQueries)) {
- if (positionCount == 1 || (!quoted && !autoGeneratePhraseQueries)) {
- // no phrase query:
- BooleanQuery q = newBooleanQuery(positionCount == 1);
-
- BooleanClause.Occur occur = positionCount > 1 && operator == AND_OPERATOR ?
- BooleanClause.Occur.MUST : BooleanClause.Occur.SHOULD;
-
- for (int i = 0; i < numTokens; i++) {
- BytesRef term = new BytesRef();
- try {
- boolean hasNext = buffer.incrementToken();
- assert hasNext == true;
- termAtt.toBytesRef(term);
- } catch (IOException e) {
- // safe to ignore, because we know the number of tokens
- }
-
- Query currentQuery = newTermQuery(
- new Term(field, term));
- q.add(currentQuery, occur);
- }
- return q;
- }
- else {
- // phrase query:
- MultiPhraseQuery mpq = newMultiPhraseQuery();
- mpq.setSlop(phraseSlop);
- List<Term> multiTerms = new ArrayList<Term>();
- int position = -1;
- for (int i = 0; i < numTokens; i++) {
- BytesRef term = new BytesRef();
- int positionIncrement = 1;
- try {
- boolean hasNext = buffer.incrementToken();
- assert hasNext == true;
- termAtt.toBytesRef(term);
- if (posIncrAtt != null) {
- positionIncrement = posIncrAtt.getPositionIncrement();
- }
- } catch (IOException e) {
- // safe to ignore, because we know the number of tokens
- }
-
- if (positionIncrement > 0 && multiTerms.size() > 0) {
- if (enablePositionIncrements) {
- mpq.add(multiTerms.toArray(new Term[0]),position);
- } else {
- mpq.add(multiTerms.toArray(new Term[0]));
- }
- multiTerms.clear();
- }
- position += positionIncrement;
- multiTerms.add(new Term(field, term));
- }
- if (enablePositionIncrements) {
- mpq.add(multiTerms.toArray(new Term[0]),position);
- } else {
- mpq.add(multiTerms.toArray(new Term[0]));
- }
- return mpq;
- }
- }
- else {
- PhraseQuery pq = newPhraseQuery();
- pq.setSlop(phraseSlop);
- int position = -1;
-
-
- for (int i = 0; i < numTokens; i++) {
- BytesRef term = new BytesRef();
- int positionIncrement = 1;
-
- try {
- boolean hasNext = buffer.incrementToken();
- assert hasNext == true;
- termAtt.toBytesRef(term);
- if (posIncrAtt != null) {
- positionIncrement = posIncrAtt.getPositionIncrement();
- }
- } catch (IOException e) {
- // safe to ignore, because we know the number of tokens
- }
-
- if (enablePositionIncrements) {
- position += positionIncrement;
- pq.add(new Term(field, term),position);
- } else {
- pq.add(new Term(field, term));
- }
- }
- return pq;
- }
- }
- }
-
-
-
- /**
- * Base implementation delegates to {@link #getFieldQuery(String,String,boolean)}.
- * This method may be overridden, for example, to return
- * a SpanNearQuery instead of a PhraseQuery.
- *
- * @exception org.apache.lucene.queryParser.ParseException throw in overridden method to disallow
- */
- protected Query getFieldQuery(String field, String queryText, int slop)
- throws ParseException {
- Query query = getFieldQuery(field, queryText, true);
-
- if (query instanceof PhraseQuery) {
- ((PhraseQuery) query).setSlop(slop);
- }
- if (query instanceof MultiPhraseQuery) {
- ((MultiPhraseQuery) query).setSlop(slop);
- }
-
- return query;
- }
-
- /**
- *
- * @exception org.apache.lucene.queryParser.ParseException
- */
- protected Query getRangeQuery(String field,
- String part1,
- String part2,
- boolean startInclusive,
- boolean endInclusive) throws ParseException
- {
- if (lowercaseExpandedTerms) {
- part1 = part1==null ? null : part1.toLowerCase();
- part2 = part2==null ? null : part2.toLowerCase();
- }
-
-
- DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
- df.setLenient(true);
- DateTools.Resolution resolution = getDateResolution(field);
-
- try {
- part1 = DateTools.dateToString(df.parse(part1), resolution);
- } catch (Exception e) { }
-
- try {
- Date d2 = df.parse(part2);
- if (endInclusive) {
- // The user can only specify the date, not the time, so make sure
- // the time is set to the latest possible time of that date to really
- // include all documents:
- Calendar cal = Calendar.getInstance(locale);
- cal.setTime(d2);
- cal.set(Calendar.HOUR_OF_DAY, 23);
- cal.set(Calendar.MINUTE, 59);
- cal.set(Calendar.SECOND, 59);
- cal.set(Calendar.MILLISECOND, 999);
- d2 = cal.getTime();
- }
- part2 = DateTools.dateToString(d2, resolution);
- } catch (Exception e) { }
-
- return newRangeQuery(field, part1, part2, startInclusive, endInclusive);
- }
-
- /**
- * Builds a new BooleanQuery instance
- * @param disableCoord disable coord
- * @return new BooleanQuery instance
- */
- protected BooleanQuery newBooleanQuery(boolean disableCoord) {
- return new BooleanQuery(disableCoord);
- }
-
- /**
- * Builds a new BooleanClause instance
- * @param q sub query
- * @param occur how this clause should occur when matching documents
- * @return new BooleanClause instance
- */
- protected BooleanClause newBooleanClause(Query q, BooleanClause.Occur occur) {
- return new BooleanClause(q, occur);
- }
-
- /**
- * Builds a new TermQuery instance
- * @param term term
- * @return new TermQuery instance
- */
- protected Query newTermQuery(Term term){
- return new TermQuery(term);
- }
-
- /**
- * Builds a new PhraseQuery instance
- * @return new PhraseQuery instance
- */
- protected PhraseQuery newPhraseQuery(){
- return new PhraseQuery();
- }
-
- /**
- * Builds a new MultiPhraseQuery instance
- * @return new MultiPhraseQuery instance
- */
- protected MultiPhraseQuery newMultiPhraseQuery(){
- return new MultiPhraseQuery();
- }
-
- /**
- * Builds a new PrefixQuery instance
- * @param prefix Prefix term
- * @return new PrefixQuery instance
- */
- protected Query newPrefixQuery(Term prefix){
- PrefixQuery query = new PrefixQuery(prefix);
- query.setRewriteMethod(multiTermRewriteMethod);
- return query;
- }
-
- /**
- * Builds a new RegexpQuery instance
- * @param regexp Regexp term
- * @return new RegexpQuery instance
- */
- protected Query newRegexpQuery(Term regexp) {
- RegexpQuery query = new RegexpQuery(regexp);
- query.setRewriteMethod(multiTermRewriteMethod);
- return query;
- }
-
- /**
- * Builds a new FuzzyQuery instance
- * @param term Term
- * @param minimumSimilarity minimum similarity
- * @param prefixLength prefix length
- * @return new FuzzyQuery Instance
- */
- protected Query newFuzzyQuery(Term term, float minimumSimilarity, int prefixLength) {
- // FuzzyQuery doesn't yet allow constant score rewrite
- return new FuzzyQuery(term,minimumSimilarity,prefixLength);
- }
-
- /**
- * Builds a new TermRangeQuery instance
- * @param field Field
- * @param part1 min
- * @param part2 max
- * @param startInclusive true if the start of the range is inclusive
- * @param endInclusive true if the end of the range is inclusive
- * @return new TermRangeQuery instance
- */
- protected Query newRangeQuery(String field, String part1, String part2, boolean startInclusive, boolean endInclusive) {
- final TermRangeQuery query = new TermRangeQuery(field, part1, part2, startInclusive, endInclusive, rangeCollator);
- query.setRewriteMethod(multiTermRewriteMethod);
- return query;
- }
-
- /**
- * Builds a new MatchAllDocsQuery instance
- * @return new MatchAllDocsQuery instance
- */
- protected Query newMatchAllDocsQuery() {
- return new MatchAllDocsQuery();
- }
-
- /**
- * Builds a new WildcardQuery instance
- * @param t wildcard term
- * @return new WildcardQuery instance
- */
- protected Query newWildcardQuery(Term t) {
- WildcardQuery query = new WildcardQuery(t);
- query.setRewriteMethod(multiTermRewriteMethod);
- return query;
- }
-
- /**
- * Factory method for generating query, given a set of clauses.
- * By default creates a boolean query composed of clauses passed in.
- *
- * Can be overridden by extending classes, to modify query being
- * returned.
- *
- * @param clauses List that contains {@link org.apache.lucene.search.BooleanClause} instances
- * to join.
- *
- * @return Resulting {@link org.apache.lucene.search.Query} object.
- * @exception org.apache.lucene.queryParser.ParseException throw in overridden method to disallow
- */
- protected Query getBooleanQuery(List<BooleanClause> clauses) throws ParseException {
- return getBooleanQuery(clauses, false);
- }
-
- /**
- * Factory method for generating query, given a set of clauses.
- * By default creates a boolean query composed of clauses passed in.
- *
- * Can be overridden by extending classes, to modify query being
- * returned.
- *
- * @param clauses List that contains {@link org.apache.lucene.search.BooleanClause} instances
- * to join.
- * @param disableCoord true if coord scoring should be disabled.
- *
- * @return Resulting {@link org.apache.lucene.search.Query} object.
- * @exception org.apache.lucene.queryParser.ParseException throw in overridden method to disallow
- */
- protected Query getBooleanQuery(List<BooleanClause> clauses, boolean disableCoord)
- throws ParseException
- {
- if (clauses.size()==0) {
- return null; // all clause words were filtered away by the analyzer.
- }
- BooleanQuery query = newBooleanQuery(disableCoord);
- for(final BooleanClause clause: clauses) {
- query.add(clause);
- }
- return query;
- }
-
- /**
- * Factory method for generating a query. Called when parser
- * parses an input term token that contains one or more wildcard
- * characters (? and *), but is not a prefix term token (one
- * that has just a single * character at the end)
- *<p>
- * Depending on settings, prefix term may be lower-cased
- * automatically. It will not go through the default Analyzer,
- * however, since normal Analyzers are unlikely to work properly
- * with wildcard templates.
- *<p>
- * Can be overridden by extending classes, to provide custom handling for
- * wildcard queries, which may be necessary due to missing analyzer calls.
- *
- * @param field Name of the field query will use.
- * @param termStr Term token that contains one or more wild card
- * characters (? or *), but is not simple prefix term
- *
- * @return Resulting {@link org.apache.lucene.search.Query} built for the term
- * @exception org.apache.lucene.queryParser.ParseException throw in overridden method to disallow
- */
- protected Query getWildcardQuery(String field, String termStr) throws ParseException
- {
- if ("*".equals(field)) {
- if ("*".equals(termStr)) return newMatchAllDocsQuery();
- }
- if (!allowLeadingWildcard && (termStr.startsWith("*") || termStr.startsWith("?")))
- throw new ParseException("'*' or '?' not allowed as first character in WildcardQuery");
- if (lowercaseExpandedTerms) {
- termStr = termStr.toLowerCase();
- }
- Term t = new Term(field, termStr);
- return newWildcardQuery(t);
- }
-
- /**
- * Factory method for generating a query. Called when parser
- * parses an input term token that contains a regular expression
- * query.
- *<p>
- * Depending on settings, pattern term may be lower-cased
- * automatically. It will not go through the default Analyzer,
- * however, since normal Analyzers are unlikely to work properly
- * with regular expression templates.
- *<p>
- * Can be overridden by extending classes, to provide custom handling for
- * regular expression queries, which may be necessary due to missing analyzer
- * calls.
- *
- * @param field Name of the field query will use.
- * @param termStr Term token that contains a regular expression
- *
- * @return Resulting {@link org.apache.lucene.search.Query} built for the term
- * @exception org.apache.lucene.queryParser.ParseException throw in overridden method to disallow
- */
- protected Query getRegexpQuery(String field, String termStr) throws ParseException
- {
- if (lowercaseExpandedTerms) {
- termStr = termStr.toLowerCase();
- }
- Term t = new Term(field, termStr);
- return newRegexpQuery(t);
- }
-
- /**
- * Factory method for generating a query (similar to
- * {@link #getWildcardQuery}). Called when parser parses an input term
- * token that uses prefix notation; that is, contains a single '*' wildcard
- * character as its last character. Since this is a special case
- * of generic wildcard term, and such a query can be optimized easily,
- * this usually results in a different query object.
- *<p>
- * Depending on settings, a prefix term may be lower-cased
- * automatically. It will not go through the default Analyzer,
- * however, since normal Analyzers are unlikely to work properly
- * with wildcard templates.
- *<p>
- * Can be overridden by extending classes, to provide custom handling for
- * wild card queries, which may be necessary due to missing analyzer calls.
- *
- * @param field Name of the field query will use.
- * @param termStr Term token to use for building term for the query
- * (<b>without</b> trailing '*' character!)
- *
- * @return Resulting {@link org.apache.lucene.search.Query} built for the term
- * @exception org.apache.lucene.queryParser.ParseException throw in overridden method to disallow
- */
- protected Query getPrefixQuery(String field, String termStr) throws ParseException
- {
- if (!allowLeadingWildcard && termStr.startsWith("*"))
- throw new ParseException("'*' not allowed as first character in PrefixQuery");
- if (lowercaseExpandedTerms) {
- termStr = termStr.toLowerCase();
- }
- Term t = new Term(field, termStr);
- return newPrefixQuery(t);
- }
-
- /**
- * Factory method for generating a query (similar to
- * {@link #getWildcardQuery}). Called when parser parses
- * an input term token that has the fuzzy suffix (~) appended.
- *
- * @param field Name of the field query will use.
- * @param termStr Term token to use for building term for the query
- *
- * @return Resulting {@link org.apache.lucene.search.Query} built for the term
- * @exception org.apache.lucene.queryParser.ParseException throw in overridden method to disallow
- */
- protected Query getFuzzyQuery(String field, String termStr, float minSimilarity) throws ParseException
- {
- if (lowercaseExpandedTerms) {
- termStr = termStr.toLowerCase();
- }
- Term t = new Term(field, termStr);
- return newFuzzyQuery(t, minSimilarity, fuzzyPrefixLength);
- }
-
-
- // extracted from the .jj grammar
- Query handleBareTokenQuery(String qfield, Token term, Token fuzzySlop, boolean prefix, boolean wildcard, boolean fuzzy, boolean regexp) throws ParseException {
- Query q;
-
- String termImage=discardEscapeChar(term.image);
- if (wildcard) {
- q = getWildcardQuery(qfield, term.image);
- } else if (prefix) {
- q = getPrefixQuery(qfield,
- discardEscapeChar(term.image.substring
- (0, term.image.length()-1)));
- } else if (regexp) {
- q = getRegexpQuery(qfield, term.image.substring(1, term.image.length()-1));
- } else if (fuzzy) {
- float fms = fuzzyMinSim;
- try {
- fms = Float.valueOf(fuzzySlop.image.substring(1)).floatValue();
- } catch (Exception ignored) { }
- if(fms < 0.0f){
- throw new ParseException("Minimum similarity for a FuzzyQuery has to be between 0.0f and 1.0f !");
- } else if (fms >= 1.0f && fms != (int) fms) {
- throw new ParseException("Fractional edit distances are not allowed!");
- }
- q = getFuzzyQuery(qfield, termImage, fms);
- } else {
- q = getFieldQuery(qfield, termImage, false);
- }
- return q;
- }
-
- // extracted from the .jj grammar
- Query handleQuotedTerm(String qfield, Token term, Token fuzzySlop) throws ParseException {
- int s = phraseSlop; // default
- if (fuzzySlop != null) {
- try {
- s = Float.valueOf(fuzzySlop.image.substring(1)).intValue();
- }
- catch (Exception ignored) { }
- }
- return getFieldQuery(qfield, discardEscapeChar(term.image.substring(1, term.image.length()-1)), s);
- }
-
- // extracted from the .jj grammar
- Query handleBoost(Query q, Token boost) throws ParseException {
- if (boost != null) {
- float f = (float) 1.0;
- try {
- f = Float.valueOf(boost.image).floatValue();
- }
- catch (Exception ignored) {
- /* Should this be handled somehow? (defaults to "no boost", if
- * boost number is invalid)
- */
- }
-
- // avoid boosting null queries, such as those caused by stop words
- if (q != null) {
- q.setBoost(f);
- }
- }
- return q;
- }
-
-
-
- /**
- * Returns a String where the escape char has been
- * removed, or kept only once if there was a double escape.
- *
- * Supports escaped unicode characters, e. g. translates
- * <code>\\u0041</code> to <code>A</code>.
- *
- */
- String discardEscapeChar(String input) throws ParseException {
- // Create char array to hold unescaped char sequence
- char[] output = new char[input.length()];
-
- // The length of the output can be less than the input
- // due to discarded escape chars. This variable holds
- // the actual length of the output
- int length = 0;
-
- // We remember whether the last processed character was
- // an escape character
- boolean lastCharWasEscapeChar = false;
-
- // The multiplier the current unicode digit must be multiplied with.
- // E. g. the first digit must be multiplied with 16^3, the second with 16^2...
- int codePointMultiplier = 0;
-
- // Used to calculate the codepoint of the escaped unicode character
- int codePoint = 0;
-
- for (int i = 0; i < input.length(); i++) {
- char curChar = input.charAt(i);
- if (codePointMultiplier > 0) {
- codePoint += hexToInt(curChar) * codePointMultiplier;
- codePointMultiplier >>>= 4;
- if (codePointMultiplier == 0) {
- output[length++] = (char)codePoint;
- codePoint = 0;
- }
- } else if (lastCharWasEscapeChar) {
- if (curChar == 'u') {
- // found an escaped unicode character
- codePointMultiplier = 16 * 16 * 16;
- } else {
- // this character was escaped
- output[length] = curChar;
- length++;
- }
- lastCharWasEscapeChar = false;
- } else {
- if (curChar == '\\') {
- lastCharWasEscapeChar = true;
- } else {
- output[length] = curChar;
- length++;
- }
- }
- }
-
- if (codePointMultiplier > 0) {
- throw new ParseException("Truncated unicode escape sequence.");
- }
-
- if (lastCharWasEscapeChar) {
- throw new ParseException("Term can not end with escape character.");
- }
-
- return new String(output, 0, length);
- }
-
- /** Returns the numeric value of the hexadecimal character */
- static final int hexToInt(char c) throws ParseException {
- if ('0' <= c && c <= '9') {
- return c - '0';
- } else if ('a' <= c && c <= 'f'){
- return c - 'a' + 10;
- } else if ('A' <= c && c <= 'F') {
- return c - 'A' + 10;
- } else {
- throw new ParseException("None-hex character in unicode escape sequence: " + c);
- }
- }
-
- /**
- * Returns a String where those characters that QueryParser
- * expects to be escaped are escaped by a preceding <code>\</code>.
- */
- public static String escape(String s) {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < s.length(); i++) {
- char c = s.charAt(i);
- // These characters are part of the query syntax and must be escaped
- if (c == '\\' || c == '+' || c == '-' || c == '!' || c == '(' || c == ')' || c == ':'
- || c == '^' || c == '[' || c == ']' || c == '\"' || c == '{' || c == '}' || c == '~'
- || c == '*' || c == '?' || c == '|' || c == '&') {
- sb.append('\\');
- }
- sb.append(c);
- }
- return sb.toString();
- }
-
-}
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.lucene.queryParser;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.text.Collator;
+import java.text.DateFormat;
+import java.util.*;
+
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.analysis.CachingTokenFilter;
+import org.apache.lucene.analysis.TokenStream;
+import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
+import org.apache.lucene.analysis.tokenattributes.TermToBytesRefAttribute;
+import org.apache.lucene.document.DateTools;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.queryParser.QueryParser.Operator;
+import org.apache.lucene.search.*;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.Version;
+
+/** This class is overridden by QueryParser in QueryParser.jj
+ * and acts to separate the majority of the Java code from the .jj grammar file.
+ */
+public abstract class QueryParserBase {
+
+ /** Do not catch this exception in your code, it means you are using methods that you should no longer use. */
+ public static class MethodRemovedUseAnother extends Throwable {}
+
+ static final int CONJ_NONE = 0;
+ static final int CONJ_AND = 1;
+ static final int CONJ_OR = 2;
+
+ static final int MOD_NONE = 0;
+ static final int MOD_NOT = 10;
+ static final int MOD_REQ = 11;
+
+ // make it possible to call setDefaultOperator() without accessing
+ // the nested class:
+ /** Alternative form of QueryParser.Operator.AND */
+ public static final Operator AND_OPERATOR = Operator.AND;
+ /** Alternative form of QueryParser.Operator.OR */
+ public static final Operator OR_OPERATOR = Operator.OR;
+
+ /** The actual operator that parser uses to combine query terms */
+ Operator operator = OR_OPERATOR;
+
+ boolean lowercaseExpandedTerms = true;
+ MultiTermQuery.RewriteMethod multiTermRewriteMethod = MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT;
+ boolean allowLeadingWildcard = false;
+ boolean enablePositionIncrements = true;
+
+ Analyzer analyzer;
+ String field;
+ int phraseSlop = 0;
+ float fuzzyMinSim = FuzzyQuery.defaultMinSimilarity;
+ int fuzzyPrefixLength = FuzzyQuery.defaultPrefixLength;
+ Locale locale = Locale.getDefault();
+
+ // the default date resolution
+ DateTools.Resolution dateResolution = null;
+ // maps field names to date resolutions
+ Map<String,DateTools.Resolution> fieldToDateResolution = null;
+
+ // The collator to use when determining range inclusion,
+ // for use when constructing RangeQuerys.
+ Collator rangeCollator = null;
+
+ boolean autoGeneratePhraseQueries;
+
+ // So the generated QueryParser(CharStream) won't error out
+ protected QueryParserBase() {
+ }
+
+ /** Initializes a query parser. Called by the QueryParser constructor
+ * @param matchVersion Lucene version to match. See <a href="#version">above</a>.
+ * @param f the default field for query terms.
+ * @param a used to find terms in the query text.
+ */
+ public void init(Version matchVersion, String f, Analyzer a) {
+ analyzer = a;
+ field = f;
+ if (matchVersion.onOrAfter(Version.LUCENE_31)) {
+ setAutoGeneratePhraseQueries(false);
+ } else {
+ setAutoGeneratePhraseQueries(true);
+ }
+ }
+
+ // the generated parser will create these in QueryParser
+ public abstract void ReInit(CharStream stream);
+ public abstract Query TopLevelQuery(String field) throws ParseException;
+
+
+ /** Parses a query string, returning a {@link org.apache.lucene.search.Query}.
+ * @param query the query string to be parsed.
+ * @throws ParseException if the parsing fails
+ */
+ public Query parse(String query) throws ParseException {
+ ReInit(new FastCharStream(new StringReader(query)));
+ try {
+ // TopLevelQuery is a Query followed by the end-of-input (EOF)
+ Query res = TopLevelQuery(field);
+ return res!=null ? res : newBooleanQuery(false);
+ }
+ catch (ParseException tme) {
+ // rethrow to include the original query:
+ ParseException e = new ParseException("Cannot parse '" +query+ "': " + tme.getMessage());
+ e.initCause(tme);
+ throw e;
+ }
+ catch (TokenMgrError tme) {
+ ParseException e = new ParseException("Cannot parse '" +query+ "': " + tme.getMessage());
+ e.initCause(tme);
+ throw e;
+ }
+ catch (BooleanQuery.TooManyClauses tmc) {
+ ParseException e = new ParseException("Cannot parse '" +query+ "': too many boolean clauses");
+ e.initCause(tmc);
+ throw e;
+ }
+ }
+
+
+ /**
+ * @return Returns the analyzer.
+ */
+ public Analyzer getAnalyzer() {
+ return analyzer;
+ }
+
+ /**
+ * @return Returns the default field.
+ */
+ public String getField() {
+ return field;
+ }
+
+ /**
+ * @see #setAutoGeneratePhraseQueries(boolean)
+ */
+ public final boolean getAutoGeneratePhraseQueries() {
+ return autoGeneratePhraseQueries;
+ }
+
+ /**
+ * Set to true if phrase queries will be automatically generated
+ * when the analyzer returns more than one term from whitespace
+ * delimited text.
+ * NOTE: this behavior may not be suitable for all languages.
+ * <p>
+ * Set to false if phrase queries should only be generated when
+ * surrounded by double quotes.
+ */
+ public final void setAutoGeneratePhraseQueries(boolean value) {
+ this.autoGeneratePhraseQueries = value;
+ }
+
+ /**
+ * Get the minimal similarity for fuzzy queries.
+ */
+ public float getFuzzyMinSim() {
+ return fuzzyMinSim;
+ }
+
+ /**
+ * Set the minimum similarity for fuzzy queries.
+ * Default is 2f.
+ */
+ public void setFuzzyMinSim(float fuzzyMinSim) {
+ this.fuzzyMinSim = fuzzyMinSim;
+ }
+
+ /**
+ * Get the prefix length for fuzzy queries.
+ * @return Returns the fuzzyPrefixLength.
+ */
+ public int getFuzzyPrefixLength() {
+ return fuzzyPrefixLength;
+ }
+
+ /**
+ * Set the prefix length for fuzzy queries. Default is 0.
+ * @param fuzzyPrefixLength The fuzzyPrefixLength to set.
+ */
+ public void setFuzzyPrefixLength(int fuzzyPrefixLength) {
+ this.fuzzyPrefixLength = fuzzyPrefixLength;
+ }
+
+ /**
+ * Sets the default slop for phrases. If zero, then exact phrase matches
+ * are required. Default value is zero.
+ */
+ public void setPhraseSlop(int phraseSlop) {
+ this.phraseSlop = phraseSlop;
+ }
+
+ /**
+ * Gets the default slop for phrases.
+ */
+ public int getPhraseSlop() {
+ return phraseSlop;
+ }
+
+
+ /**
+ * Set to <code>true</code> to allow leading wildcard characters.
+ * <p>
+ * When set, <code>*</code> or <code>?</code> are allowed as
+ * the first character of a PrefixQuery and WildcardQuery.
+ * Note that this can produce very slow
+ * queries on big indexes.
+ * <p>
+ * Default: false.
+ */
+ public void setAllowLeadingWildcard(boolean allowLeadingWildcard) {
+ this.allowLeadingWildcard = allowLeadingWildcard;
+ }
+
+ /**
+ * @see #setAllowLeadingWildcard(boolean)
+ */
+ public boolean getAllowLeadingWildcard() {
+ return allowLeadingWildcard;
+ }
+
+ /**
+ * Set to <code>true</code> to enable position increments in result query.
+ * <p>
+ * When set, result phrase and multi-phrase queries will
+ * be aware of position increments.
+ * Useful when e.g. a StopFilter increases the position increment of
+ * the token that follows an omitted token.
+ * <p>
+ * Default: true.
+ */
+ public void setEnablePositionIncrements(boolean enable) {
+ this.enablePositionIncrements = enable;
+ }
+
+ /**
+ * @see #setEnablePositionIncrements(boolean)
+ */
+ public boolean getEnablePositionIncrements() {
+ return enablePositionIncrements;
+ }
+
+ /**
+ * Sets the boolean operator of the QueryParser.
+ * In default mode (<code>OR_OPERATOR</code>) terms without any modifiers
+ * are considered optional: for example <code>capital of Hungary</code> is equal to
+ * <code>capital OR of OR Hungary</code>.<br/>
+ * In <code>AND_OPERATOR</code> mode terms are considered to be in conjunction: the
+ * above mentioned query is parsed as <code>capital AND of AND Hungary</code>
+ */
+ public void setDefaultOperator(Operator op) {
+ this.operator = op;
+ }
+
+
+ /**
+ * Gets implicit operator setting, which will be either AND_OPERATOR
+ * or OR_OPERATOR.
+ */
+ public Operator getDefaultOperator() {
+ return operator;
+ }
+
+
+ /**
+ * Whether terms of wildcard, prefix, fuzzy and range queries are to be automatically
+ * lower-cased or not. Default is <code>true</code>.
+ */
+ public void setLowercaseExpandedTerms(boolean lowercaseExpandedTerms) {
+ this.lowercaseExpandedTerms = lowercaseExpandedTerms;
+ }
+
+
+ /**
+ * @see #setLowercaseExpandedTerms(boolean)
+ */
+ public boolean getLowercaseExpandedTerms() {
+ return lowercaseExpandedTerms;
+ }
+
+ /**
+ * By default QueryParser uses {@link org.apache.lucene.search.MultiTermQuery#CONSTANT_SCORE_AUTO_REWRITE_DEFAULT}
+ * when creating a PrefixQuery, WildcardQuery or RangeQuery. This implementation is generally preferable because it
+ * a) Runs faster b) Does not have the scarcity of terms unduly influence score
+ * c) avoids any "TooManyBooleanClauses" exception.
+ * However, if your application really needs to use the
+ * old-fashioned BooleanQuery expansion rewriting and the above
+ * points are not relevant then use this to change
+ * the rewrite method.
+ */
+ public void setMultiTermRewriteMethod(MultiTermQuery.RewriteMethod method) {
+ multiTermRewriteMethod = method;
+ }
+
+
+ /**
+ * @see #setMultiTermRewriteMethod
+ */
+ public MultiTermQuery.RewriteMethod getMultiTermRewriteMethod() {
+ return multiTermRewriteMethod;
+ }
+
+ /**
+ * Set locale used by date range parsing.
+ */
+ public void setLocale(Locale locale) {
+ this.locale = locale;
+ }
+
+ /**
+ * Returns current locale, allowing access by subclasses.
+ */
+ public Locale getLocale() {
+ return locale;
+ }
+
+ /**
+ * Sets the default date resolution used by RangeQueries for fields for which no
+ * specific date resolutions has been set. Field specific resolutions can be set
+ * with {@link #setDateResolution(String, org.apache.lucene.document.DateTools.Resolution)}.
+ *
+ * @param dateResolution the default date resolution to set
+ */
+ public void setDateResolution(DateTools.Resolution dateResolution) {
+ this.dateResolution = dateResolution;
+ }
+
+ /**
+ * Sets the date resolution used by RangeQueries for a specific field.
+ *
+ * @param fieldName field for which the date resolution is to be set
+ * @param dateResolution date resolution to set
+ */
+ public void setDateResolution(String fieldName, DateTools.Resolution dateResolution) {
+ if (fieldName == null) {
+ throw new IllegalArgumentException("Field cannot be null.");
+ }
+
+ if (fieldToDateResolution == null) {
+ // lazily initialize HashMap
+ fieldToDateResolution = new HashMap<String,DateTools.Resolution>();
+ }
+
+ fieldToDateResolution.put(fieldName, dateResolution);
+ }
+
+ /**
+ * Returns the date resolution that is used by RangeQueries for the given field.
+ * Returns null, if no default or field specific date resolution has been set
+ * for the given field.
+ *
+ */
+ public DateTools.Resolution getDateResolution(String fieldName) {
+ if (fieldName == null) {
+ throw new IllegalArgumentException("Field cannot be null.");
+ }
+
+ if (fieldToDateResolution == null) {
+ // no field specific date resolutions set; return default date resolution instead
+ return this.dateResolution;
+ }
+
+ DateTools.Resolution resolution = fieldToDateResolution.get(fieldName);
+ if (resolution == null) {
+ // no date resolutions set for the given field; return default date resolution instead
+ resolution = this.dateResolution;
+ }
+
+ return resolution;
+ }
+
+ /**
+ * Sets the collator used to determine index term inclusion in ranges
+ * for RangeQuerys.
+ * <p/>
+ * <strong>WARNING:</strong> Setting the rangeCollator to a non-null
+ * collator using this method will cause every single index Term in the
+ * Field referenced by lowerTerm and/or upperTerm to be examined.
+ * Depending on the number of index Terms in this Field, the operation could
+ * be very slow.
+ *
+ * @param rc the collator to use when constructing RangeQuerys
+ */
+ public void setRangeCollator(Collator rc) {
+ rangeCollator = rc;
+ }
+
+ /**
+ * @return the collator used to determine index term inclusion in ranges
+ * for RangeQuerys.
+ */
+ public Collator getRangeCollator() {
+ return rangeCollator;
+ }
+
+ protected void addClause(List<BooleanClause> clauses, int conj, int mods, Query q) {
+ boolean required, prohibited;
+
+ // If this term is introduced by AND, make the preceding term required,
+ // unless it's already prohibited
+ if (clauses.size() > 0 && conj == CONJ_AND) {
+ BooleanClause c = clauses.get(clauses.size()-1);
+ if (!c.isProhibited())
+ c.setOccur(BooleanClause.Occur.MUST);
+ }
+
+ if (clauses.size() > 0 && operator == AND_OPERATOR && conj == CONJ_OR) {
+ // If this term is introduced by OR, make the preceding term optional,
+ // unless it's prohibited (that means we leave -a OR b but +a OR b-->a OR b)
+ // notice if the input is a OR b, first term is parsed as required; without
+ // this modification a OR b would parsed as +a OR b
+ BooleanClause c = clauses.get(clauses.size()-1);
+ if (!c.isProhibited())
+ c.setOccur(BooleanClause.Occur.SHOULD);
+ }
+
+ // We might have been passed a null query; the term might have been
+ // filtered away by the analyzer.
+ if (q == null)
+ return;
+
+ if (operator == OR_OPERATOR) {
+ // We set REQUIRED if we're introduced by AND or +; PROHIBITED if
+ // introduced by NOT or -; make sure not to set both.
+ prohibited = (mods == MOD_NOT);
+ required = (mods == MOD_REQ);
+ if (conj == CONJ_AND && !prohibited) {
+ required = true;
+ }
+ } else {
+ // We set PROHIBITED if we're introduced by NOT or -; We set REQUIRED
+ // if not PROHIBITED and not introduced by OR
+ prohibited = (mods == MOD_NOT);
+ required = (!prohibited && conj != CONJ_OR);
+ }
+ if (required && !prohibited)
+ clauses.add(newBooleanClause(q, BooleanClause.Occur.MUST));
+ else if (!required && !prohibited)
+ clauses.add(newBooleanClause(q, BooleanClause.Occur.SHOULD));
+ else if (!required && prohibited)
+ clauses.add(newBooleanClause(q, BooleanClause.Occur.MUST_NOT));
+ else
+ throw new RuntimeException("Clause cannot be both required and prohibited");
+ }
+
+ /**
+ * @exception org.apache.lucene.queryParser.ParseException throw in overridden method to disallow
+ */
+ protected Query getFieldQuery(String field, String queryText, boolean quoted) throws ParseException {
+ // Use the analyzer to get all the tokens, and then build a TermQuery,
+ // PhraseQuery, or nothing based on the term count
+
+ TokenStream source;
+ try {
+ source = analyzer.reusableTokenStream(field, new StringReader(queryText));
+ source.reset();
+ } catch (IOException e) {
+ source = analyzer.tokenStream(field, new StringReader(queryText));
+ }
+ CachingTokenFilter buffer = new CachingTokenFilter(source);
+ TermToBytesRefAttribute termAtt = null;
+ PositionIncrementAttribute posIncrAtt = null;
+ int numTokens = 0;
+
+ boolean success = false;
+ try {
+ buffer.reset();
+ success = true;
+ } catch (IOException e) {
+ // success==false if we hit an exception
+ }
+ if (success) {
+ if (buffer.hasAttribute(TermToBytesRefAttribute.class)) {
+ termAtt = buffer.getAttribute(TermToBytesRefAttribute.class);
+ }
+ if (buffer.hasAttribute(PositionIncrementAttribute.class)) {
+ posIncrAtt = buffer.getAttribute(PositionIncrementAttribute.class);
+ }
+ }
+
+ int positionCount = 0;
+ boolean severalTokensAtSamePosition = false;
+
+ boolean hasMoreTokens = false;
+ if (termAtt != null) {
+ try {
+ hasMoreTokens = buffer.incrementToken();
+ while (hasMoreTokens) {
+ numTokens++;
+ int positionIncrement = (posIncrAtt != null) ? posIncrAtt.getPositionIncrement() : 1;
+ if (positionIncrement != 0) {
+ positionCount += positionIncrement;
+ } else {
+ severalTokensAtSamePosition = true;
+ }
+ hasMoreTokens = buffer.incrementToken();
+ }
+ } catch (IOException e) {
+ // ignore
+ }
+ }
+ try {
+ // rewind the buffer stream
+ buffer.reset();
+
+ // close original stream - all tokens buffered
+ source.close();
+ }
+ catch (IOException e) {
+ // ignore
+ }
+
+ if (numTokens == 0)
+ return null;
+ else if (numTokens == 1) {
+ BytesRef term = new BytesRef();
+ try {
+ boolean hasNext = buffer.incrementToken();
+ assert hasNext == true;
+ termAtt.toBytesRef(term);
+ } catch (IOException e) {
+ // safe to ignore, because we know the number of tokens
+ }
+ return newTermQuery(new Term(field, term));
+ } else {
+ if (severalTokensAtSamePosition || (!quoted && !autoGeneratePhraseQueries)) {
+ if (positionCount == 1 || (!quoted && !autoGeneratePhraseQueries)) {
+ // no phrase query:
+ BooleanQuery q = newBooleanQuery(positionCount == 1);
+
+ BooleanClause.Occur occur = positionCount > 1 && operator == AND_OPERATOR ?
+ BooleanClause.Occur.MUST : BooleanClause.Occur.SHOULD;
+
+ for (int i = 0; i < numTokens; i++) {
+ BytesRef term = new BytesRef();
+ try {
+ boolean hasNext = buffer.incrementToken();
+ assert hasNext == true;
+ termAtt.toBytesRef(term);
+ } catch (IOException e) {
+ // safe to ignore, because we know the number of tokens
+ }
+
+ Query currentQuery = newTermQuery(
+ new Term(field, term));
+ q.add(currentQuery, occur);
+ }
+ return q;
+ }
+ else {
+ // phrase query:
+ MultiPhraseQuery mpq = newMultiPhraseQuery();
+ mpq.setSlop(phraseSlop);
+ List<Term> multiTerms = new ArrayList<Term>();
+ int position = -1;
+ for (int i = 0; i < numTokens; i++) {
+ BytesRef term = new BytesRef();
+ int positionIncrement = 1;
+ try {
+ boolean hasNext = buffer.incrementToken();
+ assert hasNext == true;
+ termAtt.toBytesRef(term);
+ if (posIncrAtt != null) {
+ positionIncrement = posIncrAtt.getPositionIncrement();
+ }
+ } catch (IOException e) {
+ // safe to ignore, because we know the number of tokens
+ }
+
+ if (positionIncrement > 0 && multiTerms.size() > 0) {
+ if (enablePositionIncrements) {
+ mpq.add(multiTerms.toArray(new Term[0]),position);
+ } else {
+ mpq.add(multiTerms.toArray(new Term[0]));
+ }
+ multiTerms.clear();
+ }
+ position += positionIncrement;
+ multiTerms.add(new Term(field, term));
+ }
+ if (enablePositionIncrements) {
+ mpq.add(multiTerms.toArray(new Term[0]),position);
+ } else {
+ mpq.add(multiTerms.toArray(new Term[0]));
+ }
+ return mpq;
+ }
+ }
+ else {
+ PhraseQuery pq = newPhraseQuery();
+ pq.setSlop(phraseSlop);
+ int position = -1;
+
+
+ for (int i = 0; i < numTokens; i++) {
+ BytesRef term = new BytesRef();
+ int positionIncrement = 1;
+
+ try {
+ boolean hasNext = buffer.incrementToken();
+ assert hasNext == true;
+ termAtt.toBytesRef(term);
+ if (posIncrAtt != null) {
+ positionIncrement = posIncrAtt.getPositionIncrement();
+ }
+ } catch (IOException e) {
+ // safe to ignore, because we know the number of tokens
+ }
+
+ if (enablePositionIncrements) {
+ position += positionIncrement;
+ pq.add(new Term(field, term),position);
+ } else {
+ pq.add(new Term(field, term));
+ }
+ }
+ return pq;
+ }
+ }
+ }
+
+
+
+ /**
+ * Base implementation delegates to {@link #getFieldQuery(String,String,boolean)}.
+ * This method may be overridden, for example, to return
+ * a SpanNearQuery instead of a PhraseQuery.
+ *
+ * @exception org.apache.lucene.queryParser.ParseException throw in overridden method to disallow
+ */
+ protected Query getFieldQuery(String field, String queryText, int slop)
+ throws ParseException {
+ Query query = getFieldQuery(field, queryText, true);
+
+ if (query instanceof PhraseQuery) {
+ ((PhraseQuery) query).setSlop(slop);
+ }
+ if (query instanceof MultiPhraseQuery) {
+ ((MultiPhraseQuery) query).setSlop(slop);
+ }
+
+ return query;
+ }
+
+ /**
+ *
+ * @exception org.apache.lucene.queryParser.ParseException
+ */
+ protected Query getRangeQuery(String field,
+ String part1,
+ String part2,
+ boolean startInclusive,
+ boolean endInclusive) throws ParseException
+ {
+ if (lowercaseExpandedTerms) {
+ part1 = part1==null ? null : part1.toLowerCase();
+ part2 = part2==null ? null : part2.toLowerCase();
+ }
+
+
+ DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
+ df.setLenient(true);
+ DateTools.Resolution resolution = getDateResolution(field);
+
+ try {
+ part1 = DateTools.dateToString(df.parse(part1), resolution);
+ } catch (Exception e) { }
+
+ try {
+ Date d2 = df.parse(part2);
+ if (endInclusive) {
+ // The user can only specify the date, not the time, so make sure
+ // the time is set to the latest possible time of that date to really
+ // include all documents:
+ Calendar cal = Calendar.getInstance(locale);
+ cal.setTime(d2);
+ cal.set(Calendar.HOUR_OF_DAY, 23);
+ cal.set(Calendar.MINUTE, 59);
+ cal.set(Calendar.SECOND, 59);
+ cal.set(Calendar.MILLISECOND, 999);
+ d2 = cal.getTime();
+ }
+ part2 = DateTools.dateToString(d2, resolution);
+ } catch (Exception e) { }
+
+ return newRangeQuery(field, part1, part2, startInclusive, endInclusive);
+ }
+
+ /**
+ * Builds a new BooleanQuery instance
+ * @param disableCoord disable coord
+ * @return new BooleanQuery instance
+ */
+ protected BooleanQuery newBooleanQuery(boolean disableCoord) {
+ return new BooleanQuery(disableCoord);
+ }
+
+ /**
+ * Builds a new BooleanClause instance
+ * @param q sub query
+ * @param occur how this clause should occur when matching documents
+ * @return new BooleanClause instance
+ */
+ protected BooleanClause newBooleanClause(Query q, BooleanClause.Occur occur) {
+ return new BooleanClause(q, occur);
+ }
+
+ /**
+ * Builds a new TermQuery instance
+ * @param term term
+ * @return new TermQuery instance
+ */
+ protected Query newTermQuery(Term term){
+ return new TermQuery(term);
+ }
+
+ /**
+ * Builds a new PhraseQuery instance
+ * @return new PhraseQuery instance
+ */
+ protected PhraseQuery newPhraseQuery(){
+ return new PhraseQuery();
+ }
+
+ /**
+ * Builds a new MultiPhraseQuery instance
+ * @return new MultiPhraseQuery instance
+ */
+ protected MultiPhraseQuery newMultiPhraseQuery(){
+ return new MultiPhraseQuery();
+ }
+
+ /**
+ * Builds a new PrefixQuery instance
+ * @param prefix Prefix term
+ * @return new PrefixQuery instance
+ */
+ protected Query newPrefixQuery(Term prefix){
+ PrefixQuery query = new PrefixQuery(prefix);
+ query.setRewriteMethod(multiTermRewriteMethod);
+ return query;
+ }
+
+ /**
+ * Builds a new RegexpQuery instance
+ * @param regexp Regexp term
+ * @return new RegexpQuery instance
+ */
+ protected Query newRegexpQuery(Term regexp) {
+ RegexpQuery query = new RegexpQuery(regexp);
+ query.setRewriteMethod(multiTermRewriteMethod);
+ return query;
+ }
+
+ /**
+ * Builds a new FuzzyQuery instance
+ * @param term Term
+ * @param minimumSimilarity minimum similarity
+ * @param prefixLength prefix length
+ * @return new FuzzyQuery Instance
+ */
+ protected Query newFuzzyQuery(Term term, float minimumSimilarity, int prefixLength) {
+ // FuzzyQuery doesn't yet allow constant score rewrite
+ return new FuzzyQuery(term,minimumSimilarity,prefixLength);
+ }
+
+ /**
+ * Builds a new TermRangeQuery instance
+ * @param field Field
+ * @param part1 min
+ * @param part2 max
+ * @param startInclusive true if the start of the range is inclusive
+ * @param endInclusive true if the end of the range is inclusive
+ * @return new TermRangeQuery instance
+ */
+ protected Query newRangeQuery(String field, String part1, String part2, boolean startInclusive, boolean endInclusive) {
+ final TermRangeQuery query = new TermRangeQuery(field, part1, part2, startInclusive, endInclusive, rangeCollator);
+ query.setRewriteMethod(multiTermRewriteMethod);
+ return query;
+ }
+
+ /**
+ * Builds a new MatchAllDocsQuery instance
+ * @return new MatchAllDocsQuery instance
+ */
+ protected Query newMatchAllDocsQuery() {
+ return new MatchAllDocsQuery();
+ }
+
+ /**
+ * Builds a new WildcardQuery instance
+ * @param t wildcard term
+ * @return new WildcardQuery instance
+ */
+ protected Query newWildcardQuery(Term t) {
+ WildcardQuery query = new WildcardQuery(t);
+ query.setRewriteMethod(multiTermRewriteMethod);
+ return query;
+ }
+
+ /**
+ * Factory method for generating query, given a set of clauses.
+ * By default creates a boolean query composed of clauses passed in.
+ *
+ * Can be overridden by extending classes, to modify query being
+ * returned.
+ *
+ * @param clauses List that contains {@link org.apache.lucene.search.BooleanClause} instances
+ * to join.
+ *
+ * @return Resulting {@link org.apache.lucene.search.Query} object.
+ * @exception org.apache.lucene.queryParser.ParseException throw in overridden method to disallow
+ */
+ protected Query getBooleanQuery(List<BooleanClause> clauses) throws ParseException {
+ return getBooleanQuery(clauses, false);
+ }
+
+ /**
+ * Factory method for generating query, given a set of clauses.
+ * By default creates a boolean query composed of clauses passed in.
+ *
+ * Can be overridden by extending classes, to modify query being
+ * returned.
+ *
+ * @param clauses List that contains {@link org.apache.lucene.search.BooleanClause} instances
+ * to join.
+ * @param disableCoord true if coord scoring should be disabled.
+ *
+ * @return Resulting {@link org.apache.lucene.search.Query} object.
+ * @exception org.apache.lucene.queryParser.ParseException throw in overridden method to disallow
+ */
+ protected Query getBooleanQuery(List<BooleanClause> clauses, boolean disableCoord)
+ throws ParseException
+ {
+ if (clauses.size()==0) {
+ return null; // all clause words were filtered away by the analyzer.
+ }
+ BooleanQuery query = newBooleanQuery(disableCoord);
+ for(final BooleanClause clause: clauses) {
+ query.add(clause);
+ }
+ return query;
+ }
+
+ /**
+ * Factory method for generating a query. Called when parser
+ * parses an input term token that contains one or more wildcard
+ * characters (? and *), but is not a prefix term token (one
+ * that has just a single * character at the end)
+ *<p>
+ * Depending on settings, prefix term may be lower-cased
+ * automatically. It will not go through the default Analyzer,
+ * however, since normal Analyzers are unlikely to work properly
+ * with wildcard templates.
+ *<p>
+ * Can be overridden by extending classes, to provide custom handling for
+ * wildcard queries, which may be necessary due to missing analyzer calls.
+ *
+ * @param field Name of the field query will use.
+ * @param termStr Term token that contains one or more wild card
+ * characters (? or *), but is not simple prefix term
+ *
+ * @return Resulting {@link org.apache.lucene.search.Query} built for the term
+ * @exception org.apache.lucene.queryParser.ParseException throw in overridden method to disallow
+ */
+ protected Query getWildcardQuery(String field, String termStr) throws ParseException
+ {
+ if ("*".equals(field)) {
+ if ("*".equals(termStr)) return newMatchAllDocsQuery();
+ }
+ if (!allowLeadingWildcard && (termStr.startsWith("*") || termStr.startsWith("?")))
+ throw new ParseException("'*' or '?' not allowed as first character in WildcardQuery");
+ if (lowercaseExpandedTerms) {
+ termStr = termStr.toLowerCase();
+ }
+ Term t = new Term(field, termStr);
+ return newWildcardQuery(t);
+ }
+
+ /**
+ * Factory method for generating a query. Called when parser
+ * parses an input term token that contains a regular expression
+ * query.
+ *<p>
+ * Depending on settings, pattern term may be lower-cased
+ * automatically. It will not go through the default Analyzer,
+ * however, since normal Analyzers are unlikely to work properly
+ * with regular expression templates.
+ *<p>
+ * Can be overridden by extending classes, to provide custom handling for
+ * regular expression queries, which may be necessary due to missing analyzer
+ * calls.
+ *
+ * @param field Name of the field query will use.
+ * @param termStr Term token that contains a regular expression
+ *
+ * @return Resulting {@link org.apache.lucene.search.Query} built for the term
+ * @exception org.apache.lucene.queryParser.ParseException throw in overridden method to disallow
+ */
+ protected Query getRegexpQuery(String field, String termStr) throws ParseException
+ {
+ if (lowercaseExpandedTerms) {
+ termStr = termStr.toLowerCase();
+ }
+ Term t = new Term(field, termStr);
+ return newRegexpQuery(t);
+ }
+
+ /**
+ * Factory method for generating a query (similar to
+ * {@link #getWildcardQuery}). Called when parser parses an input term
+ * token that uses prefix notation; that is, contains a single '*' wildcard
+ * character as its last character. Since this is a special case
+ * of generic wildcard term, and such a query can be optimized easily,
+ * this usually results in a different query object.
+ *<p>
+ * Depending on settings, a prefix term may be lower-cased
+ * automatically. It will not go through the default Analyzer,
+ * however, since normal Analyzers are unlikely to work properly
+ * with wildcard templates.
+ *<p>
+ * Can be overridden by extending classes, to provide custom handling for
+ * wild card queries, which may be necessary due to missing analyzer calls.
+ *
+ * @param field Name of the field query will use.
+ * @param termStr Term token to use for building term for the query
+ * (<b>without</b> trailing '*' character!)
+ *
+ * @return Resulting {@link org.apache.lucene.search.Query} built for the term
+ * @exception org.apache.lucene.queryParser.ParseException throw in overridden method to disallow
+ */
+ protected Query getPrefixQuery(String field, String termStr) throws ParseException
+ {
+ if (!allowLeadingWildcard && termStr.startsWith("*"))
+ throw new ParseException("'*' not allowed as first character in PrefixQuery");
+ if (lowercaseExpandedTerms) {
+ termStr = termStr.toLowerCase();
+ }
+ Term t = new Term(field, termStr);
+ return newPrefixQuery(t);
+ }
+
+ /**
+ * Factory method for generating a query (similar to
+ * {@link #getWildcardQuery}). Called when parser parses
+ * an input term token that has the fuzzy suffix (~) appended.
+ *
+ * @param field Name of the field query will use.
+ * @param termStr Term token to use for building term for the query
+ *
+ * @return Resulting {@link org.apache.lucene.search.Query} built for the term
+ * @exception org.apache.lucene.queryParser.ParseException throw in overridden method to disallow
+ */
+ protected Query getFuzzyQuery(String field, String termStr, float minSimilarity) throws ParseException
+ {
+ if (lowercaseExpandedTerms) {
+ termStr = termStr.toLowerCase();
+ }
+ Term t = new Term(field, termStr);
+ return newFuzzyQuery(t, minSimilarity, fuzzyPrefixLength);
+ }
+
+
+ // extracted from the .jj grammar
+ Query handleBareTokenQuery(String qfield, Token term, Token fuzzySlop, boolean prefix, boolean wildcard, boolean fuzzy, boolean regexp) throws ParseException {
+ Query q;
+
+ String termImage=discardEscapeChar(term.image);
+ if (wildcard) {
+ q = getWildcardQuery(qfield, term.image);
+ } else if (prefix) {
+ q = getPrefixQuery(qfield,
+ discardEscapeChar(term.image.substring
+ (0, term.image.length()-1)));
+ } else if (regexp) {
+ q = getRegexpQuery(qfield, term.image.substring(1, term.image.length()-1));
+ } else if (fuzzy) {
+ float fms = fuzzyMinSim;
+ try {
+ fms = Float.valueOf(fuzzySlop.image.substring(1)).floatValue();
+ } catch (Exception ignored) { }
+ if(fms < 0.0f){
+ throw new ParseException("Minimum similarity for a FuzzyQuery has to be between 0.0f and 1.0f !");
+ } else if (fms >= 1.0f && fms != (int) fms) {
+ throw new ParseException("Fractional edit distances are not allowed!");
+ }
+ q = getFuzzyQuery(qfield, termImage, fms);
+ } else {
+ q = getFieldQuery(qfield, termImage, false);
+ }
+ return q;
+ }
+
+ // extracted from the .jj grammar
+ Query handleQuotedTerm(String qfield, Token term, Token fuzzySlop) throws ParseException {
+ int s = phraseSlop; // default
+ if (fuzzySlop != null) {
+ try {
+ s = Float.valueOf(fuzzySlop.image.substring(1)).intValue();
+ }
+ catch (Exception ignored) { }
+ }
+ return getFieldQuery(qfield, discardEscapeChar(term.image.substring(1, term.image.length()-1)), s);
+ }
+
+ // extracted from the .jj grammar
+ Query handleBoost(Query q, Token boost) throws ParseException {
+ if (boost != null) {
+ float f = (float) 1.0;
+ try {
+ f = Float.valueOf(boost.image).floatValue();
+ }
+ catch (Exception ignored) {
+ /* Should this be handled somehow? (defaults to "no boost", if
+ * boost number is invalid)
+ */
+ }
+
+ // avoid boosting null queries, such as those caused by stop words
+ if (q != null) {
+ q.setBoost(f);
+ }
+ }
+ return q;
+ }
+
+
+
+ /**
+ * Returns a String where the escape char has been
+ * removed, or kept only once if there was a double escape.
+ *
+ * Supports escaped unicode characters, e. g. translates
+ * <code>\\u0041</code> to <code>A</code>.
+ *
+ */
+ String discardEscapeChar(String input) throws ParseException {
+ // Create char array to hold unescaped char sequence
+ char[] output = new char[input.length()];
+
+ // The length of the output can be less than the input
+ // due to discarded escape chars. This variable holds
+ // the actual length of the output
+ int length = 0;
+
+ // We remember whether the last processed character was
+ // an escape character
+ boolean lastCharWasEscapeChar = false;
+
+ // The multiplier the current unicode digit must be multiplied with.
+ // E. g. the first digit must be multiplied with 16^3, the second with 16^2...
+ int codePointMultiplier = 0;
+
+ // Used to calculate the codepoint of the escaped unicode character
+ int codePoint = 0;
+
+ for (int i = 0; i < input.length(); i++) {
+ char curChar = input.charAt(i);
+ if (codePointMultiplier > 0) {
+ codePoint += hexToInt(curChar) * codePointMultiplier;
+ codePointMultiplier >>>= 4;
+ if (codePointMultiplier == 0) {
+ output[length++] = (char)codePoint;
+ codePoint = 0;
+ }
+ } else if (lastCharWasEscapeChar) {
+ if (curChar == 'u') {
+ // found an escaped unicode character
+ codePointMultiplier = 16 * 16 * 16;
+ } else {
+ // this character was escaped
+ output[length] = curChar;
+ length++;
+ }
+ lastCharWasEscapeChar = false;
+ } else {
+ if (curChar == '\\') {
+ lastCharWasEscapeChar = true;
+ } else {
+ output[length] = curChar;
+ length++;
+ }
+ }
+ }
+
+ if (codePointMultiplier > 0) {
+ throw new ParseException("Truncated unicode escape sequence.");
+ }
+
+ if (lastCharWasEscapeChar) {
+ throw new ParseException("Term can not end with escape character.");
+ }
+
+ return new String(output, 0, length);
+ }
+
+ /** Returns the numeric value of the hexadecimal character */
+ static final int hexToInt(char c) throws ParseException {
+ if ('0' <= c && c <= '9') {
+ return c - '0';
+ } else if ('a' <= c && c <= 'f'){
+ return c - 'a' + 10;
+ } else if ('A' <= c && c <= 'F') {
+ return c - 'A' + 10;
+ } else {
+ throw new ParseException("None-hex character in unicode escape sequence: " + c);
+ }
+ }
+
+ /**
+ * Returns a String where those characters that QueryParser
+ * expects to be escaped are escaped by a preceding <code>\</code>.
+ */
+ public static String escape(String s) {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < s.length(); i++) {
+ char c = s.charAt(i);
+ // These characters are part of the query syntax and must be escaped
+ if (c == '\\' || c == '+' || c == '-' || c == '!' || c == '(' || c == ')' || c == ':'
+ || c == '^' || c == '[' || c == ']' || c == '\"' || c == '{' || c == '}' || c == '~'
+ || c == '*' || c == '?' || c == '|' || c == '&') {
+ sb.append('\\');
+ }
+ sb.append(c);
+ }
+ return sb.toString();
+ }
+
+}
diff --git a/solr/src/java/org/apache/solr/util/SentinelIntSet.java b/solr/src/java/org/apache/solr/util/SentinelIntSet.java
index fc4d120e7d5..2c53a723f39 100644
--- a/solr/src/java/org/apache/solr/util/SentinelIntSet.java
+++ b/solr/src/java/org/apache/solr/util/SentinelIntSet.java
@@ -1,134 +1,134 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.solr.util;
-
-import java.util.Arrays;
-
-/** A native int set where one value is reserved to mean "EMPTY" */
-public class SentinelIntSet {
- public int[] keys;
- public int count;
- public final int emptyVal;
- public int rehashCount; // the count at which a rehash should be done
-
- public SentinelIntSet(int size, int emptyVal) {
- this.emptyVal = emptyVal;
- int tsize = Math.max(org.apache.lucene.util.BitUtil.nextHighestPowerOfTwo(size), 1);
- rehashCount = tsize - (tsize>>2);
- if (size >= rehashCount) { // should be able to hold "size" w/o rehashing
- tsize <<= 1;
- rehashCount = tsize - (tsize>>2);
- }
- keys = new int[tsize];
- if (emptyVal != 0)
- clear();
- }
-
- public void clear() {
- Arrays.fill(keys, emptyVal);
- count = 0;
- }
-
- public int hash(int key) {
- return key;
- }
-
- public int size() { return count; }
-
- /** returns the slot for this key */
- public int getSlot(int key) {
- assert key != emptyVal;
- int h = hash(key);
- int s = h & (keys.length-1);
- if (keys[s] == key || keys[s]== emptyVal) return s;
-
- int increment = (h>>7)|1;
- do {
- s = (s + increment) & (keys.length-1);
- } while (keys[s] != key && keys[s] != emptyVal);
- return s;
- }
-
- /** returns the slot for this key, or -slot-1 if not found */
- public int find(int key) {
- assert key != emptyVal;
- int h = hash(key);
- int s = h & (keys.length-1);
- if (keys[s] == key) return s;
- if (keys[s] == emptyVal) return -s-1;
-
- int increment = (h>>7)|1;
- for(;;) {
- s = (s + increment) & (keys.length-1);
- if (keys[s] == key) return s;
- if (keys[s] == emptyVal) return -s-1;
- }
- }
-
-
- public boolean exists(int key) {
- return find(key) >= 0;
- }
-
-
- public int put(int key) {
- int s = find(key);
- if (s < 0) {
- if (count >= rehashCount) {
- rehash();
- s = getSlot(key);
- } else {
- s = -s-1;
- }
- count++;
- keys[s] = key;
- putKey(key, s);
- } else {
- overwriteKey(key, s);
- }
- return s;
- }
-
-
- protected void putKey(int key, int slot) {}
- protected void overwriteKey(int key, int slot) {}
-
- protected void startRehash(int newSize) {}
- protected void moveKey(int key, int oldSlot, int newSlot) {}
- protected void endRehash() {}
-
- public void rehash() {
- int newSize = keys.length << 1;
- startRehash(newSize);
- int[] oldKeys = keys;
- keys = new int[newSize];
- if (emptyVal != 0) Arrays.fill(keys, emptyVal);
-
- for (int i=0; i<oldKeys.length; i++) {
- int key = oldKeys[i];
- if (key == emptyVal) continue;
- int newSlot = getSlot(key);
- keys[newSlot] = key;
- moveKey(key, i, newSlot);
- }
- endRehash();
- rehashCount = newSize - (newSize>>2);
-
- }
-
-}
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.util;
+
+import java.util.Arrays;
+
+/** A native int set where one value is reserved to mean "EMPTY" */
+public class SentinelIntSet {
+ public int[] keys;
+ public int count;
+ public final int emptyVal;
+ public int rehashCount; // the count at which a rehash should be done
+
+ public SentinelIntSet(int size, int emptyVal) {
+ this.emptyVal = emptyVal;
+ int tsize = Math.max(org.apache.lucene.util.BitUtil.nextHighestPowerOfTwo(size), 1);
+ rehashCount = tsize - (tsize>>2);
+ if (size >= rehashCount) { // should be able to hold "size" w/o rehashing
+ tsize <<= 1;
+ rehashCount = tsize - (tsize>>2);
+ }
+ keys = new int[tsize];
+ if (emptyVal != 0)
+ clear();
+ }
+
+ public void clear() {
+ Arrays.fill(keys, emptyVal);
+ count = 0;
+ }
+
+ public int hash(int key) {
+ return key;
+ }
+
+ public int size() { return count; }
+
+ /** returns the slot for this key */
+ public int getSlot(int key) {
+ assert key != emptyVal;
+ int h = hash(key);
+ int s = h & (keys.length-1);
+ if (keys[s] == key || keys[s]== emptyVal) return s;
+
+ int increment = (h>>7)|1;
+ do {
+ s = (s + increment) & (keys.length-1);
+ } while (keys[s] != key && keys[s] != emptyVal);
+ return s;
+ }
+
+ /** returns the slot for this key, or -slot-1 if not found */
+ public int find(int key) {
+ assert key != emptyVal;
+ int h = hash(key);
+ int s = h & (keys.length-1);
+ if (keys[s] == key) return s;
+ if (keys[s] == emptyVal) return -s-1;
+
+ int increment = (h>>7)|1;
+ for(;;) {
+ s = (s + increment) & (keys.length-1);
+ if (keys[s] == key) return s;
+ if (keys[s] == emptyVal) return -s-1;
+ }
+ }
+
+
+ public boolean exists(int key) {
+ return find(key) >= 0;
+ }
+
+
+ public int put(int key) {
+ int s = find(key);
+ if (s < 0) {
+ if (count >= rehashCount) {
+ rehash();
+ s = getSlot(key);
+ } else {
+ s = -s-1;
+ }
+ count++;
+ keys[s] = key;
+ putKey(key, s);
+ } else {
+ overwriteKey(key, s);
+ }
+ return s;
+ }
+
+
+ protected void putKey(int key, int slot) {}
+ protected void overwriteKey(int key, int slot) {}
+
+ protected void startRehash(int newSize) {}
+ protected void moveKey(int key, int oldSlot, int newSlot) {}
+ protected void endRehash() {}
+
+ public void rehash() {
+ int newSize = keys.length << 1;
+ startRehash(newSize);
+ int[] oldKeys = keys;
+ keys = new int[newSize];
+ if (emptyVal != 0) Arrays.fill(keys, emptyVal);
+
+ for (int i=0; i<oldKeys.length; i++) {
+ int key = oldKeys[i];
+ if (key == emptyVal) continue;
+ int newSlot = getSlot(key);
+ keys[newSlot] = key;
+ moveKey(key, i, newSlot);
+ }
+ endRehash();
+ rehashCount = newSize - (newSize>>2);
+
+ }
+
+}
diff --git a/solr/src/test/org/apache/solr/cloud/AbstractDistributedZkTestCase.java b/solr/src/test/org/apache/solr/cloud/AbstractDistributedZkTestCase.java
index 3fe298359ca..e7ced578ee8 100644
--- a/solr/src/test/org/apache/solr/cloud/AbstractDistributedZkTestCase.java
+++ b/solr/src/test/org/apache/solr/cloud/AbstractDistributedZkTestCase.java
@@ -1,93 +1,93 @@
-package org.apache.solr.cloud;
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.io.File;
-
-import org.apache.solr.BaseDistributedSearchTestCase;
-import org.apache.solr.client.solrj.embedded.JettySolrRunner;
-import org.apache.solr.common.cloud.SolrZkClient;
-import org.apache.solr.core.SolrConfig;
-import org.junit.Before;
-
-public abstract class AbstractDistributedZkTestCase extends BaseDistributedSearchTestCase {
- private static final boolean DEBUG = false;
- protected ZkTestServer zkServer;
-
- @Before
- @Override
- public void setUp() throws Exception {
- super.setUp();
- log.info("####SETUP_START " + getName());
-
- ignoreException("java.nio.channels.ClosedChannelException");
-
- String zkDir = testDir.getAbsolutePath() + File.separator
- + "zookeeper/server1/data";
- zkServer = new ZkTestServer(zkDir);
- zkServer.run();
-
- System.setProperty("zkHost", zkServer.getZkAddress());
-
- AbstractZkTestCase.buildZooKeeper(zkServer.getZkHost(), zkServer.getZkAddress(), "solrconfig.xml", "schema.xml");
-
- // set some system properties for use by tests
- System.setProperty("solr.test.sys.prop1", "propone");
- System.setProperty("solr.test.sys.prop2", "proptwo");
- }
-
- @Override
- protected void createServers(int numShards) throws Exception {
- System.setProperty("collection", "control_collection");
- controlJetty = createJetty(testDir, testDir + "/control/data", "control_shard");
- System.clearProperty("collection");
- controlClient = createNewSolrServer(controlJetty.getLocalPort());
-
- StringBuilder sb = new StringBuilder();
- for (int i = 1; i <= numShards; i++) {
- if (sb.length() > 0) sb.append(',');
- JettySolrRunner j = createJetty(testDir, testDir + "/jetty" + i, "shard" + (i + 2));
- jettys.add(j);
- clients.add(createNewSolrServer(j.getLocalPort()));
- sb.append("localhost:").append(j.getLocalPort()).append(context);
- }
-
- shards = sb.toString();
- }
-
- @Override
- public void tearDown() throws Exception {
- if (DEBUG) {
- printLayout();
- }
- zkServer.shutdown();
- System.clearProperty("zkHost");
- System.clearProperty("collection");
- System.clearProperty("solr.test.sys.prop1");
- System.clearProperty("solr.test.sys.prop2");
- super.tearDown();
- resetExceptionIgnores();
- SolrConfig.severeErrors.clear();
- }
-
- protected void printLayout() throws Exception {
- SolrZkClient zkClient = new SolrZkClient(zkServer.getZkHost(), AbstractZkTestCase.TIMEOUT);
- zkClient.printLayoutToStdOut();
- zkClient.close();
- }
-}
+package org.apache.solr.cloud;
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.io.File;
+
+import org.apache.solr.BaseDistributedSearchTestCase;
+import org.apache.solr.client.solrj.embedded.JettySolrRunner;
+import org.apache.solr.common.cloud.SolrZkClient;
+import org.apache.solr.core.SolrConfig;
+import org.junit.Before;
+
+public abstract class AbstractDistributedZkTestCase extends BaseDistributedSearchTestCase {
+ private static final boolean DEBUG = false;
+ protected ZkTestServer zkServer;
+
+ @Before
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ log.info("####SETUP_START " + getName());
+
+ ignoreException("java.nio.channels.ClosedChannelException");
+
+ String zkDir = testDir.getAbsolutePath() + File.separator
+ + "zookeeper/server1/data";
+ zkServer = new ZkTestServer(zkDir);
+ zkServer.run();
+
+ System.setProperty("zkHost", zkServer.getZkAddress());
+
+ AbstractZkTestCase.buildZooKeeper(zkServer.getZkHost(), zkServer.getZkAddress(), "solrconfig.xml", "schema.xml");
+
+ // set some system properties for use by tests
+ System.setProperty("solr.test.sys.prop1", "propone");
+ System.setProperty("solr.test.sys.prop2", "proptwo");
+ }
+
+ @Override
+ protected void createServers(int numShards) throws Exception {
+ System.setProperty("collection", "control_collection");
+ controlJetty = createJetty(testDir, testDir + "/control/data", "control_shard");
+ System.clearProperty("collection");
+ controlClient = createNewSolrServer(controlJetty.getLocalPort());
+
+ StringBuilder sb = new StringBuilder();
+ for (int i = 1; i <= numShards; i++) {
+ if (sb.length() > 0) sb.append(',');
+ JettySolrRunner j = createJetty(testDir, testDir + "/jetty" + i, "shard" + (i + 2));
+ jettys.add(j);
+ clients.add(createNewSolrServer(j.getLocalPort()));
+ sb.append("localhost:").append(j.getLocalPort()).append(context);
+ }
+
+ shards = sb.toString();
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ if (DEBUG) {
+ printLayout();
+ }
+ zkServer.shutdown();
+ System.clearProperty("zkHost");
+ System.clearProperty("collection");
+ System.clearProperty("solr.test.sys.prop1");
+ System.clearProperty("solr.test.sys.prop2");
+ super.tearDown();
+ resetExceptionIgnores();
+ SolrConfig.severeErrors.clear();
+ }
+
+ protected void printLayout() throws Exception {
+ SolrZkClient zkClient = new SolrZkClient(zkServer.getZkHost(), AbstractZkTestCase.TIMEOUT);
+ zkClient.printLayoutToStdOut();
+ zkClient.close();
+ }
+}
diff --git a/solr/src/test/org/apache/solr/cloud/AbstractZkTestCase.java b/solr/src/test/org/apache/solr/cloud/AbstractZkTestCase.java
index 72eb68a523b..f7660f05cf0 100644
--- a/solr/src/test/org/apache/solr/cloud/AbstractZkTestCase.java
+++ b/solr/src/test/org/apache/solr/cloud/AbstractZkTestCase.java
@@ -1,147 +1,147 @@
-package org.apache.solr.cloud;
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-
-import org.apache.solr.SolrTestCaseJ4;
-import org.apache.solr.common.cloud.SolrZkClient;
-import org.apache.solr.common.cloud.ZkNodeProps;
-import org.apache.solr.core.SolrConfig;
-import org.apache.zookeeper.CreateMode;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Base test class for ZooKeeper tests.
- */
-public abstract class AbstractZkTestCase extends SolrTestCaseJ4 {
-
- static final int TIMEOUT = 10000;
-
- private static final boolean DEBUG = false;
-
- protected static Logger log = LoggerFactory
- .getLogger(AbstractZkTestCase.class);
-
- protected static ZkTestServer zkServer;
-
- protected static String zkDir;
-
-
- @BeforeClass
- public static void azt_beforeClass() throws Exception {
- createTempDir();
- zkDir = dataDir.getAbsolutePath() + File.separator
- + "zookeeper/server1/data";
- zkServer = new ZkTestServer(zkDir);
- zkServer.run();
-
- System.setProperty("zkHost", zkServer.getZkAddress());
- System.setProperty("hostPort", "0000");
-
- buildZooKeeper(zkServer.getZkHost(), zkServer.getZkAddress(),
- "solrconfig.xml", "schema.xml");
-
- initCore("solrconfig.xml", "schema.xml");
- }
-
- // static to share with distrib test
- static void buildZooKeeper(String zkHost, String zkAddress, String config,
- String schema) throws Exception {
- SolrZkClient zkClient = new SolrZkClient(zkHost, AbstractZkTestCase.TIMEOUT);
- zkClient.makePath("/solr");
- zkClient.close();
-
- zkClient = new SolrZkClient(zkAddress, AbstractZkTestCase.TIMEOUT);
-
- ZkNodeProps props = new ZkNodeProps();
- props.put("configName", "conf1");
- zkClient.makePath("/collections/collection1", props.store(), CreateMode.PERSISTENT);
- zkClient.makePath("/collections/collection1/shards", CreateMode.PERSISTENT);
-
- zkClient.makePath("/collections/control_collection", props.store(), CreateMode.PERSISTENT);
- zkClient.makePath("/collections/control_collection/shards", CreateMode.PERSISTENT);
-
- putConfig(zkClient, config);
- putConfig(zkClient, schema);
- putConfig(zkClient, "stopwords.txt");
- putConfig(zkClient, "protwords.txt");
- putConfig(zkClient, "mapping-ISOLatin1Accent.txt");
- putConfig(zkClient, "old_synonyms.txt");
- putConfig(zkClient, "synonyms.txt");
-
- zkClient.close();
- }
-
- private static void putConfig(SolrZkClient zkConnection, String name)
- throws Exception {
- zkConnection.setData("/configs/conf1/" + name, getFile("solr"
- + File.separator + "conf" + File.separator + name));
- }
-
- @Override
- public void tearDown() throws Exception {
- if (DEBUG) {
- printLayout(zkServer.getZkHost());
- }
-
- SolrConfig.severeErrors.clear();
- super.tearDown();
- }
-
- @AfterClass
- public static void azt_afterClass() throws IOException {
- zkServer.shutdown();
- System.clearProperty("zkHost");
- System.clearProperty("solr.test.sys.prop1");
- System.clearProperty("solr.test.sys.prop2");
- }
-
- protected void printLayout(String zkHost) throws Exception {
- SolrZkClient zkClient = new SolrZkClient(zkHost, AbstractZkTestCase.TIMEOUT);
- zkClient.printLayoutToStdOut();
- zkClient.close();
- }
-
- static void makeSolrZkNode(String zkHost) throws Exception {
- SolrZkClient zkClient = new SolrZkClient(zkHost, TIMEOUT);
- zkClient.makePath("/solr");
- zkClient.close();
- }
-
- static void tryCleanSolrZkNode(String zkHost) throws Exception {
- tryCleanPath(zkHost, "/solr");
- }
-
- static void tryCleanPath(String zkHost, String path) throws Exception {
- SolrZkClient zkClient = new SolrZkClient(zkHost, TIMEOUT);
- if (zkClient.exists(path)) {
- List<String> children = zkClient.getChildren(path, null);
- for (String string : children) {
- tryCleanPath(zkHost, path+"/"+string);
- }
- zkClient.delete(path, -1);
- }
- zkClient.close();
- }
-}
+package org.apache.solr.cloud;
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+
+import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.common.cloud.SolrZkClient;
+import org.apache.solr.common.cloud.ZkNodeProps;
+import org.apache.solr.core.SolrConfig;
+import org.apache.zookeeper.CreateMode;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Base test class for ZooKeeper tests.
+ */
+public abstract class AbstractZkTestCase extends SolrTestCaseJ4 {
+
+ static final int TIMEOUT = 10000;
+
+ private static final boolean DEBUG = false;
+
+ protected static Logger log = LoggerFactory
+ .getLogger(AbstractZkTestCase.class);
+
+ protected static ZkTestServer zkServer;
+
+ protected static String zkDir;
+
+
+ @BeforeClass
+ public static void azt_beforeClass() throws Exception {
+ createTempDir();
+ zkDir = dataDir.getAbsolutePath() + File.separator
+ + "zookeeper/server1/data";
+ zkServer = new ZkTestServer(zkDir);
+ zkServer.run();
+
+ System.setProperty("zkHost", zkServer.getZkAddress());
+ System.setProperty("hostPort", "0000");
+
+ buildZooKeeper(zkServer.getZkHost(), zkServer.getZkAddress(),
+ "solrconfig.xml", "schema.xml");
+
+ initCore("solrconfig.xml", "schema.xml");
+ }
+
+ // static to share with distrib test
+ static void buildZooKeeper(String zkHost, String zkAddress, String config,
+ String schema) throws Exception {
+ SolrZkClient zkClient = new SolrZkClient(zkHost, AbstractZkTestCase.TIMEOUT);
+ zkClient.makePath("/solr");
+ zkClient.close();
+
+ zkClient = new SolrZkClient(zkAddress, AbstractZkTestCase.TIMEOUT);
+
+ ZkNodeProps props = new ZkNodeProps();
+ props.put("configName", "conf1");
+ zkClient.makePath("/collections/collection1", props.store(), CreateMode.PERSISTENT);
+ zkClient.makePath("/collections/collection1/shards", CreateMode.PERSISTENT);
+
+ zkClient.makePath("/collections/control_collection", props.store(), CreateMode.PERSISTENT);
+ zkClient.makePath("/collections/control_collection/shards", CreateMode.PERSISTENT);
+
+ putConfig(zkClient, config);
+ putConfig(zkClient, schema);
+ putConfig(zkClient, "stopwords.txt");
+ putConfig(zkClient, "protwords.txt");
+ putConfig(zkClient, "mapping-ISOLatin1Accent.txt");
+ putConfig(zkClient, "old_synonyms.txt");
+ putConfig(zkClient, "synonyms.txt");
+
+ zkClient.close();
+ }
+
+ private static void putConfig(SolrZkClient zkConnection, String name)
+ throws Exception {
+ zkConnection.setData("/configs/conf1/" + name, getFile("solr"
+ + File.separator + "conf" + File.separator + name));
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ if (DEBUG) {
+ printLayout(zkServer.getZkHost());
+ }
+
+ SolrConfig.severeErrors.clear();
+ super.tearDown();
+ }
+
+ @AfterClass
+ public static void azt_afterClass() throws IOException {
+ zkServer.shutdown();
+ System.clearProperty("zkHost");
+ System.clearProperty("solr.test.sys.prop1");
+ System.clearProperty("solr.test.sys.prop2");
+ }
+
+ protected void printLayout(String zkHost) throws Exception {
+ SolrZkClient zkClient = new SolrZkClient(zkHost, AbstractZkTestCase.TIMEOUT);
+ zkClient.printLayoutToStdOut();
+ zkClient.close();
+ }
+
+ static void makeSolrZkNode(String zkHost) throws Exception {
+ SolrZkClient zkClient = new SolrZkClient(zkHost, TIMEOUT);
+ zkClient.makePath("/solr");
+ zkClient.close();
+ }
+
+ static void tryCleanSolrZkNode(String zkHost) throws Exception {
+ tryCleanPath(zkHost, "/solr");
+ }
+
+ static void tryCleanPath(String zkHost, String path) throws Exception {
+ SolrZkClient zkClient = new SolrZkClient(zkHost, TIMEOUT);
+ if (zkClient.exists(path)) {
+ List<String> children = zkClient.getChildren(path, null);
+ for (String string : children) {
+ tryCleanPath(zkHost, path+"/"+string);
+ }
+ zkClient.delete(path, -1);
+ }
+ zkClient.close();
+ }
+}
diff --git a/solr/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java b/solr/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java
index fbcd378cf0e..35d86e0ac5c 100644
--- a/solr/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java
+++ b/solr/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java
@@ -1,284 +1,284 @@
-package org.apache.solr.cloud;
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.net.MalformedURLException;
-
-import org.apache.solr.SolrTestCaseJ4;
-import org.apache.solr.client.solrj.SolrServerException;
-import org.apache.solr.client.solrj.impl.CloudSolrServer;
-import org.apache.solr.client.solrj.response.QueryResponse;
-import org.apache.solr.common.params.CommonParams;
-import org.apache.solr.common.params.ModifiableSolrParams;
-import org.junit.BeforeClass;
-
-/**
- *
- */
-public class BasicDistributedZkTest extends AbstractDistributedZkTestCase {
-
- private static final String DEFAULT_COLLECTION = "collection1";
- private static final boolean DEBUG = false;
- String t1="a_t";
- String i1="a_si";
- String nint = "n_i";
- String tint = "n_ti";
- String nfloat = "n_f";
- String tfloat = "n_tf";
- String ndouble = "n_d";
- String tdouble = "n_td";
- String nlong = "n_l";
- String tlong = "n_tl";
- String ndate = "n_dt";
- String tdate = "n_tdt";
-
- String oddField="oddField_s";
- String missingField="ignore_exception__missing_but_valid_field_t";
- String invalidField="ignore_exception__invalid_field_not_in_schema";
-
- public BasicDistributedZkTest() {
- fixShardCount = true;
-
- System.setProperty("CLOUD_UPDATE_DELAY", "0");
- }
-
-
- @BeforeClass
- public static void beforeClass() throws Exception {
- System.setProperty("solr.solr.home", SolrTestCaseJ4.TEST_HOME);
- }
-
- @Override
- protected void setDistributedParams(ModifiableSolrParams params) {
-
- if (r.nextBoolean()) {
- // don't set shards, let that be figured out from the cloud state
- params.set("distrib", "true");
- } else {
- // use shard ids rather than physical locations
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < shardCount; i++) {
- if (i > 0)
- sb.append(',');
- sb.append("shard" + (i + 3));
- }
- params.set("shards", sb.toString());
- params.set("distrib", "true");
- }
- }
-
- @Override
- public void doTest() throws Exception {
- del("*:*");
- indexr(id,1, i1, 100, tlong, 100,t1,"now is the time for all good men"
- ,"foo_f", 1.414f, "foo_b", "true", "foo_d", 1.414d);
- indexr(id,2, i1, 50 , tlong, 50,t1,"to come to the aid of their country."
- );
- indexr(id,3, i1, 2, tlong, 2,t1,"how now brown cow"
- );
- indexr(id,4, i1, -100 ,tlong, 101,t1,"the quick fox jumped over the lazy dog"
- );
- indexr(id,5, i1, 500, tlong, 500 ,t1,"the quick fox jumped way over the lazy dog"
- );
- indexr(id,6, i1, -600, tlong, 600 ,t1,"humpty dumpy sat on a wall");
- indexr(id,7, i1, 123, tlong, 123 ,t1,"humpty dumpy had a great fall");
- indexr(id,8, i1, 876, tlong, 876,t1,"all the kings horses and all the kings men");
- indexr(id,9, i1, 7, tlong, 7,t1,"couldn't put humpty together again");
- indexr(id,10, i1, 4321, tlong, 4321,t1,"this too shall pass");
- indexr(id,11, i1, -987, tlong, 987,t1,"An eye for eye only ends up making the whole world blind.");
- indexr(id,12, i1, 379, tlong, 379,t1,"Great works are performed, not by strength, but by perseverance.");
- indexr(id,13, i1, 232, tlong, 232,t1,"no eggs on wall, lesson learned", oddField, "odd man out");
-
- indexr(id, 14, "SubjectTerms_mfacet", new String[] {"mathematical models", "mathematical analysis"});
- indexr(id, 15, "SubjectTerms_mfacet", new String[] {"test 1", "test 2", "test3"});
- indexr(id, 16, "SubjectTerms_mfacet", new String[] {"test 1", "test 2", "test3"});
- String[] vals = new String[100];
- for (int i=0; i<100; i++) {
- vals[i] = "test " + i;
- }
- indexr(id, 17, "SubjectTerms_mfacet", vals);
-
- for (int i=100; i<150; i++) {
- indexr(id, i);
- }
-
- commit();
-
- handle.clear();
- handle.put("QTime", SKIPVAL);
- handle.put("timestamp", SKIPVAL);
-
- // random value sort
- for (String f : fieldNames) {
- query("q","*:*", "sort",f+" desc");
- query("q","*:*", "sort",f+" asc");
- }
-
- // these queries should be exactly ordered and scores should exactly match
- query("q","*:*", "sort",i1+" desc");
- query("q","*:*", "sort",i1+" asc");
- query("q","*:*", "sort",i1+" desc", "fl","*,score");
- query("q","*:*", "sort",tlong+" asc", "fl","score"); // test legacy behavior - "score"=="*,score"
- query("q","*:*", "sort",tlong+" desc");
- handle.put("maxScore", SKIPVAL);
- query("q","{!func}"+i1);// does not expect maxScore. So if it comes ,ignore it. JavaBinCodec.writeSolrDocumentList()
- //is agnostic of request params.
- handle.remove("maxScore");
- query("q","{!func}"+i1, "fl","*,score"); // even scores should match exactly here
-
- handle.put("highlighting", UNORDERED);
- handle.put("response", UNORDERED);
-
- handle.put("maxScore", SKIPVAL);
- query("q","quick");
- query("q","all","fl","id","start","0");
- query("q","all","fl","foofoofoo","start","0"); // no fields in returned docs
- query("q","all","fl","id","start","100");
-
- handle.put("score", SKIPVAL);
- query("q","quick","fl","*,score");
- query("q","all","fl","*,score","start","1");
- query("q","all","fl","*,score","start","100");
-
- query("q","now their fox sat had put","fl","*,score",
- "hl","true","hl.fl",t1);
-
- query("q","now their fox sat had put","fl","foofoofoo",
- "hl","true","hl.fl",t1);
-
- query("q","matchesnothing","fl","*,score");
-
- query("q","*:*", "rows",100, "facet","true", "facet.field",t1);
- query("q","*:*", "rows",100, "facet","true", "facet.field",t1, "facet.limit",-1, "facet.sort","count");
- query("q","*:*", "rows",100, "facet","true", "facet.field",t1, "facet.limit",-1, "facet.sort","count", "facet.mincount",2);
- query("q","*:*", "rows",100, "facet","true", "facet.field",t1, "facet.limit",-1, "facet.sort","index");
- query("q","*:*", "rows",100, "facet","true", "facet.field",t1, "facet.limit",-1, "facet.sort","index", "facet.mincount",2);
- query("q","*:*", "rows",100, "facet","true", "facet.field",t1,"facet.limit",1);
- query("q","*:*", "rows",100, "facet","true", "facet.query","quick", "facet.query","all", "facet.query","*:*");
- query("q","*:*", "rows",100, "facet","true", "facet.field",t1, "facet.offset",1);
- query("q","*:*", "rows",100, "facet","true", "facet.field",t1, "facet.mincount",2);
-
- // test faceting multiple things at once
- query("q","*:*", "rows",100, "facet","true", "facet.query","quick", "facet.query","all", "facet.query","*:*"
- ,"facet.field",t1);
-
- // test filter tagging, facet exclusion, and naming (multi-select facet support)
- query("q","*:*", "rows",100, "facet","true", "facet.query","{!key=myquick}quick", "facet.query","{!key=myall ex=a}all", "facet.query","*:*"
- ,"facet.field","{!key=mykey ex=a}"+t1
- ,"facet.field","{!key=other ex=b}"+t1
- ,"facet.field","{!key=again ex=a,b}"+t1
- ,"facet.field",t1
- ,"fq","{!tag=a}id:[1 TO 7]", "fq","{!tag=b}id:[3 TO 9]"
- );
- query("q", "*:*", "facet", "true", "facet.field", "{!ex=t1}SubjectTerms_mfacet", "fq", "{!tag=t1}SubjectTerms_mfacet:(test 1)", "facet.limit", "10", "facet.mincount", "1");
-
- // test field that is valid in schema but missing in all shards
- query("q","*:*", "rows",100, "facet","true", "facet.field",missingField, "facet.mincount",2);
- // test field that is valid in schema and missing in some shards
- query("q","*:*", "rows",100, "facet","true", "facet.field",oddField, "facet.mincount",2);
-
- query("q","*:*", "sort",i1+" desc", "stats", "true", "stats.field", i1);
-
- /*** TODO: the failure may come back in "exception"
- try {
- // test error produced for field that is invalid for schema
- query("q","*:*", "rows",100, "facet","true", "facet.field",invalidField, "facet.mincount",2);
- TestCase.fail("SolrServerException expected for invalid field that is not in schema");
- } catch (SolrServerException ex) {
- // expected
- }
- ***/
-
- // Try to get better coverage for refinement queries by turning off over requesting.
- // This makes it much more likely that we may not get the top facet values and hence
- // we turn of that checking.
- handle.put("facet_fields", SKIPVAL);
- query("q","*:*", "rows",0, "facet","true", "facet.field",t1,"facet.limit",5, "facet.shard.limit",5);
- // check a complex key name
- query("q","*:*", "rows",0, "facet","true", "facet.field","{!key='a b/c \\' \\} foo'}"+t1,"facet.limit",5, "facet.shard.limit",5);
- handle.remove("facet_fields");
-
-
- // index the same document to two servers and make sure things
- // don't blow up.
- if (clients.size()>=2) {
- index(id,100, i1, 107 ,t1,"oh no, a duplicate!");
- for (int i=0; i<clients.size(); i++) {
- index_specific(i, id,100, i1, 107 ,t1,"oh no, a duplicate!");
- }
- commit();
- query("q","duplicate", "hl","true", "hl.fl", t1);
- query("q","fox duplicate horses", "hl","true", "hl.fl", t1);
- query("q","*:*", "rows",100);
- }
-
- // test debugging
- handle.put("explain", UNORDERED);
- handle.put("debug", UNORDERED);
- handle.put("time", SKIPVAL);
- query("q","now their fox sat had put","fl","*,score",CommonParams.DEBUG_QUERY, "true");
- query("q", "id:[1 TO 5]", CommonParams.DEBUG_QUERY, "true");
- query("q", "id:[1 TO 5]", CommonParams.DEBUG, CommonParams.TIMING);
- query("q", "id:[1 TO 5]", CommonParams.DEBUG, CommonParams.RESULTS);
- query("q", "id:[1 TO 5]", CommonParams.DEBUG, CommonParams.QUERY);
-
- // TODO: This test currently fails because debug info is obtained only
- // on shards with matches.
- // query("q","matchesnothing","fl","*,score", "debugQuery", "true");
-
- // Thread.sleep(10000000000L);
- if (DEBUG) {
- super.printLayout();
- }
- }
-
- volatile CloudSolrServer solrj;
-
- @Override
- protected QueryResponse queryServer(ModifiableSolrParams params) throws SolrServerException {
-
- if (r.nextBoolean())
- return super.queryServer(params);
-
- // use the distributed solrj client
- if (solrj == null) {
- synchronized(this) {
- try {
- CloudSolrServer server = new CloudSolrServer(zkServer.getZkAddress());
- server.setDefaultCollection(DEFAULT_COLLECTION);
- solrj = server;
- } catch (MalformedURLException e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- if (r.nextBoolean())
- params.set("collection",DEFAULT_COLLECTION);
-
- QueryResponse rsp = solrj.query(params);
- return rsp;
- }
-
- @Override
- public void tearDown() throws Exception {
- super.tearDown();
- System.clearProperty("CLOUD_UPDATE_DELAY");
- System.clearProperty("zkHost");
- }
-}
+package org.apache.solr.cloud;
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.net.MalformedURLException;
+
+import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.impl.CloudSolrServer;
+import org.apache.solr.client.solrj.response.QueryResponse;
+import org.apache.solr.common.params.CommonParams;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.junit.BeforeClass;
+
+/**
+ *
+ */
+public class BasicDistributedZkTest extends AbstractDistributedZkTestCase {
+
+ private static final String DEFAULT_COLLECTION = "collection1";
+ private static final boolean DEBUG = false;
+ String t1="a_t";
+ String i1="a_si";
+ String nint = "n_i";
+ String tint = "n_ti";
+ String nfloat = "n_f";
+ String tfloat = "n_tf";
+ String ndouble = "n_d";
+ String tdouble = "n_td";
+ String nlong = "n_l";
+ String tlong = "n_tl";
+ String ndate = "n_dt";
+ String tdate = "n_tdt";
+
+ String oddField="oddField_s";
+ String missingField="ignore_exception__missing_but_valid_field_t";
+ String invalidField="ignore_exception__invalid_field_not_in_schema";
+
+ public BasicDistributedZkTest() {
+ fixShardCount = true;
+
+ System.setProperty("CLOUD_UPDATE_DELAY", "0");
+ }
+
+
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ System.setProperty("solr.solr.home", SolrTestCaseJ4.TEST_HOME);
+ }
+
+ @Override
+ protected void setDistributedParams(ModifiableSolrParams params) {
+
+ if (r.nextBoolean()) {
+ // don't set shards, let that be figured out from the cloud state
+ params.set("distrib", "true");
+ } else {
+ // use shard ids rather than physical locations
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < shardCount; i++) {
+ if (i > 0)
+ sb.append(',');
+ sb.append("shard" + (i + 3));
+ }
+ params.set("shards", sb.toString());
+ params.set("distrib", "true");
+ }
+ }
+
+ @Override
+ public void doTest() throws Exception {
+ del("*:*");
+ indexr(id,1, i1, 100, tlong, 100,t1,"now is the time for all good men"
+ ,"foo_f", 1.414f, "foo_b", "true", "foo_d", 1.414d);
+ indexr(id,2, i1, 50 , tlong, 50,t1,"to come to the aid of their country."
+ );
+ indexr(id,3, i1, 2, tlong, 2,t1,"how now brown cow"
+ );
+ indexr(id,4, i1, -100 ,tlong, 101,t1,"the quick fox jumped over the lazy dog"
+ );
+ indexr(id,5, i1, 500, tlong, 500 ,t1,"the quick fox jumped way over the lazy dog"
+ );
+ indexr(id,6, i1, -600, tlong, 600 ,t1,"humpty dumpy sat on a wall");
+ indexr(id,7, i1, 123, tlong, 123 ,t1,"humpty dumpy had a great fall");
+ indexr(id,8, i1, 876, tlong, 876,t1,"all the kings horses and all the kings men");
+ indexr(id,9, i1, 7, tlong, 7,t1,"couldn't put humpty together again");
+ indexr(id,10, i1, 4321, tlong, 4321,t1,"this too shall pass");
+ indexr(id,11, i1, -987, tlong, 987,t1,"An eye for eye only ends up making the whole world blind.");
+ indexr(id,12, i1, 379, tlong, 379,t1,"Great works are performed, not by strength, but by perseverance.");
+ indexr(id,13, i1, 232, tlong, 232,t1,"no eggs on wall, lesson learned", oddField, "odd man out");
+
+ indexr(id, 14, "SubjectTerms_mfacet", new String[] {"mathematical models", "mathematical analysis"});
+ indexr(id, 15, "SubjectTerms_mfacet", new String[] {"test 1", "test 2", "test3"});
+ indexr(id, 16, "SubjectTerms_mfacet", new String[] {"test 1", "test 2", "test3"});
+ String[] vals = new String[100];
+ for (int i=0; i<100; i++) {
+ vals[i] = "test " + i;
+ }
+ indexr(id, 17, "SubjectTerms_mfacet", vals);
+
+ for (int i=100; i<150; i++) {
+ indexr(id, i);
+ }
+
+ commit();
+
+ handle.clear();
+ handle.put("QTime", SKIPVAL);
+ handle.put("timestamp", SKIPVAL);
+
+ // random value sort
+ for (String f : fieldNames) {
+ query("q","*:*", "sort",f+" desc");
+ query("q","*:*", "sort",f+" asc");
+ }
+
+ // these queries should be exactly ordered and scores should exactly match
+ query("q","*:*", "sort",i1+" desc");
+ query("q","*:*", "sort",i1+" asc");
+ query("q","*:*", "sort",i1+" desc", "fl","*,score");
+ query("q","*:*", "sort",tlong+" asc", "fl","score"); // test legacy behavior - "score"=="*,score"
+ query("q","*:*", "sort",tlong+" desc");
+ handle.put("maxScore", SKIPVAL);
+ query("q","{!func}"+i1);// does not expect maxScore. So if it comes ,ignore it. JavaBinCodec.writeSolrDocumentList()
+ //is agnostic of request params.
+ handle.remove("maxScore");
+ query("q","{!func}"+i1, "fl","*,score"); // even scores should match exactly here
+
+ handle.put("highlighting", UNORDERED);
+ handle.put("response", UNORDERED);
+
+ handle.put("maxScore", SKIPVAL);
+ query("q","quick");
+ query("q","all","fl","id","start","0");
+ query("q","all","fl","foofoofoo","start","0"); // no fields in returned docs
+ query("q","all","fl","id","start","100");
+
+ handle.put("score", SKIPVAL);
+ query("q","quick","fl","*,score");
+ query("q","all","fl","*,score","start","1");
+ query("q","all","fl","*,score","start","100");
+
+ query("q","now their fox sat had put","fl","*,score",
+ "hl","true","hl.fl",t1);
+
+ query("q","now their fox sat had put","fl","foofoofoo",
+ "hl","true","hl.fl",t1);
+
+ query("q","matchesnothing","fl","*,score");
+
+ query("q","*:*", "rows",100, "facet","true", "facet.field",t1);
+ query("q","*:*", "rows",100, "facet","true", "facet.field",t1, "facet.limit",-1, "facet.sort","count");
+ query("q","*:*", "rows",100, "facet","true", "facet.field",t1, "facet.limit",-1, "facet.sort","count", "facet.mincount",2);
+ query("q","*:*", "rows",100, "facet","true", "facet.field",t1, "facet.limit",-1, "facet.sort","index");
+ query("q","*:*", "rows",100, "facet","true", "facet.field",t1, "facet.limit",-1, "facet.sort","index", "facet.mincount",2);
+ query("q","*:*", "rows",100, "facet","true", "facet.field",t1,"facet.limit",1);
+ query("q","*:*", "rows",100, "facet","true", "facet.query","quick", "facet.query","all", "facet.query","*:*");
+ query("q","*:*", "rows",100, "facet","true", "facet.field",t1, "facet.offset",1);
+ query("q","*:*", "rows",100, "facet","true", "facet.field",t1, "facet.mincount",2);
+
+ // test faceting multiple things at once
+ query("q","*:*", "rows",100, "facet","true", "facet.query","quick", "facet.query","all", "facet.query","*:*"
+ ,"facet.field",t1);
+
+ // test filter tagging, facet exclusion, and naming (multi-select facet support)
+ query("q","*:*", "rows",100, "facet","true", "facet.query","{!key=myquick}quick", "facet.query","{!key=myall ex=a}all", "facet.query","*:*"
+ ,"facet.field","{!key=mykey ex=a}"+t1
+ ,"facet.field","{!key=other ex=b}"+t1
+ ,"facet.field","{!key=again ex=a,b}"+t1
+ ,"facet.field",t1
+ ,"fq","{!tag=a}id:[1 TO 7]", "fq","{!tag=b}id:[3 TO 9]"
+ );
+ query("q", "*:*", "facet", "true", "facet.field", "{!ex=t1}SubjectTerms_mfacet", "fq", "{!tag=t1}SubjectTerms_mfacet:(test 1)", "facet.limit", "10", "facet.mincount", "1");
+
+ // test field that is valid in schema but missing in all shards
+ query("q","*:*", "rows",100, "facet","true", "facet.field",missingField, "facet.mincount",2);
+ // test field that is valid in schema and missing in some shards
+ query("q","*:*", "rows",100, "facet","true", "facet.field",oddField, "facet.mincount",2);
+
+ query("q","*:*", "sort",i1+" desc", "stats", "true", "stats.field", i1);
+
+ /*** TODO: the failure may come back in "exception"
+ try {
+ // test error produced for field that is invalid for schema
+ query("q","*:*", "rows",100, "facet","true", "facet.field",invalidField, "facet.mincount",2);
+ TestCase.fail("SolrServerException expected for invalid field that is not in schema");
+ } catch (SolrServerException ex) {
+ // expected
+ }
+ ***/
+
+ // Try to get better coverage for refinement queries by turning off over requesting.
+ // This makes it much more likely that we may not get the top facet values and hence
+ // we turn of that checking.
+ handle.put("facet_fields", SKIPVAL);
+ query("q","*:*", "rows",0, "facet","true", "facet.field",t1,"facet.limit",5, "facet.shard.limit",5);
+ // check a complex key name
+ query("q","*:*", "rows",0, "facet","true", "facet.field","{!key='a b/c \\' \\} foo'}"+t1,"facet.limit",5, "facet.shard.limit",5);
+ handle.remove("facet_fields");
+
+
+ // index the same document to two servers and make sure things
+ // don't blow up.
+ if (clients.size()>=2) {
+ index(id,100, i1, 107 ,t1,"oh no, a duplicate!");
+ for (int i=0; i<clients.size(); i++) {
+ index_specific(i, id,100, i1, 107 ,t1,"oh no, a duplicate!");
+ }
+ commit();
+ query("q","duplicate", "hl","true", "hl.fl", t1);
+ query("q","fox duplicate horses", "hl","true", "hl.fl", t1);
+ query("q","*:*", "rows",100);
+ }
+
+ // test debugging
+ handle.put("explain", UNORDERED);
+ handle.put("debug", UNORDERED);
+ handle.put("time", SKIPVAL);
+ query("q","now their fox sat had put","fl","*,score",CommonParams.DEBUG_QUERY, "true");
+ query("q", "id:[1 TO 5]", CommonParams.DEBUG_QUERY, "true");
+ query("q", "id:[1 TO 5]", CommonParams.DEBUG, CommonParams.TIMING);
+ query("q", "id:[1 TO 5]", CommonParams.DEBUG, CommonParams.RESULTS);
+ query("q", "id:[1 TO 5]", CommonParams.DEBUG, CommonParams.QUERY);
+
+ // TODO: This test currently fails because debug info is obtained only
+ // on shards with matches.
+ // query("q","matchesnothing","fl","*,score", "debugQuery", "true");
+
+ // Thread.sleep(10000000000L);
+ if (DEBUG) {
+ super.printLayout();
+ }
+ }
+
+ volatile CloudSolrServer solrj;
+
+ @Override
+ protected QueryResponse queryServer(ModifiableSolrParams params) throws SolrServerException {
+
+ if (r.nextBoolean())
+ return super.queryServer(params);
+
+ // use the distributed solrj client
+ if (solrj == null) {
+ synchronized(this) {
+ try {
+ CloudSolrServer server = new CloudSolrServer(zkServer.getZkAddress());
+ server.setDefaultCollection(DEFAULT_COLLECTION);
+ solrj = server;
+ } catch (MalformedURLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ if (r.nextBoolean())
+ params.set("collection",DEFAULT_COLLECTION);
+
+ QueryResponse rsp = solrj.query(params);
+ return rsp;
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ super.tearDown();
+ System.clearProperty("CLOUD_UPDATE_DELAY");
+ System.clearProperty("zkHost");
+ }
+}
diff --git a/solr/src/test/org/apache/solr/cloud/BasicZkTest.java b/solr/src/test/org/apache/solr/cloud/BasicZkTest.java
index ccb974b1633..abe57a8ddf9 100644
--- a/solr/src/test/org/apache/solr/cloud/BasicZkTest.java
+++ b/solr/src/test/org/apache/solr/cloud/BasicZkTest.java
@@ -1,138 +1,138 @@
-package org.apache.solr.cloud;
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import org.apache.lucene.index.LogMergePolicy;
-import org.apache.solr.core.SolrCore;
-import org.apache.solr.update.SolrIndexWriter;
-
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-/**
- *
- */
-public class BasicZkTest extends AbstractZkTestCase {
-
- @BeforeClass
- public static void beforeClass() {
- System.setProperty("CLOUD_UPDATE_DELAY", "1");
- }
-
- @Test
- public void testBasic() throws Exception {
- // test using ZooKeeper
- assertTrue("Not using ZooKeeper", h.getCoreContainer().isZooKeeperAware());
-
- ZkController zkController = h.getCoreContainer().getZkController();
-
- // test merge factor picked up
- SolrCore core = h.getCore();
- SolrIndexWriter writer = new SolrIndexWriter("testWriter", core
- .getNewIndexDir(), core.getDirectoryFactory(), false, core.getSchema(),
- core.getSolrConfig().mainIndexConfig, core.getDeletionPolicy());
- assertEquals("Mergefactor was not picked up", ((LogMergePolicy)writer.getConfig().getMergePolicy()).getMergeFactor(), 8);
- writer.close();
-
- lrf.args.put("version", "2.0");
- assertQ("test query on empty index", req("qlkciyopsbgzyvkylsjhchghjrdf"),
- "//result[@numFound='0']");
-
- // test escaping of ";"
- assertU("deleting 42 for no reason at all", delI("42"));
- assertU("adding doc#42", adoc("id", "42", "val_s", "aa;bb"));
- assertU("does commit work?", commit());
-
- assertQ("backslash escaping semicolon", req("id:42 AND val_s:aa\\;bb"),
- "//*[@numFound='1']", "//int[@name='id'][.='42']");
-
- assertQ("quote escaping semicolon", req("id:42 AND val_s:\"aa;bb\""),
- "//*[@numFound='1']", "//int[@name='id'][.='42']");
-
- assertQ("no escaping semicolon", req("id:42 AND val_s:aa"),
- "//*[@numFound='0']");
-
- assertU(delI("42"));
- assertU(commit());
- assertQ(req("id:42"), "//*[@numFound='0']");
-
- // test overwrite default of true
-
- assertU(adoc("id", "42", "val_s", "AAA"));
- assertU(adoc("id", "42", "val_s", "BBB"));
- assertU(commit());
- assertQ(req("id:42"), "//*[@numFound='1']", "//str[.='BBB']");
- assertU(adoc("id", "42", "val_s", "CCC"));
- assertU(adoc("id", "42", "val_s", "DDD"));
- assertU(commit());
- assertQ(req("id:42"), "//*[@numFound='1']", "//str[.='DDD']");
-
- // test deletes
- String[] adds = new String[] { add(doc("id", "101"), "overwrite", "true"),
- add(doc("id", "101"), "overwrite", "true"),
- add(doc("id", "105"), "overwrite", "false"),
- add(doc("id", "102"), "overwrite", "true"),
- add(doc("id", "103"), "overwrite", "false"),
- add(doc("id", "101"), "overwrite", "true"), };
- for (String a : adds) {
- assertU(a, a);
- }
- assertU(commit());
-
- zkServer.shutdown();
-
- Thread.sleep(300);
-
- // try a reconnect from disconnect
- zkServer = new ZkTestServer(zkDir);
- zkServer.run();
-
- Thread.sleep(300);
-
- // ensure zk still thinks node is up
- assertTrue(
- zkController.getCloudState().getLiveNodes().toString(),
- zkController.getCloudState().liveNodesContain(
- zkController.getNodeName()));
-
- // test maxint
- assertQ(req("q", "id:[100 TO 110]", "rows", "2147483647"),
- "//*[@numFound='4']");
-
- // test big limit
- assertQ(req("q", "id:[100 TO 111]", "rows", "1147483647"),
- "//*[@numFound='4']");
-
- assertQ(req("id:[100 TO 110]"), "//*[@numFound='4']");
- assertU(delI("102"));
- assertU(commit());
- assertQ(req("id:[100 TO 110]"), "//*[@numFound='3']");
- assertU(delI("105"));
- assertU(commit());
- assertQ(req("id:[100 TO 110]"), "//*[@numFound='2']");
- assertU(delQ("id:[100 TO 110]"));
- assertU(commit());
- assertQ(req("id:[100 TO 110]"), "//*[@numFound='0']");
- }
-
- @AfterClass
- public static void afterClass() {
- System.clearProperty("CLOUD_UPDATE_DELAY");
- }
-}
+package org.apache.solr.cloud;
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import org.apache.lucene.index.LogMergePolicy;
+import org.apache.solr.core.SolrCore;
+import org.apache.solr.update.SolrIndexWriter;
+
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ *
+ */
+public class BasicZkTest extends AbstractZkTestCase {
+
+ @BeforeClass
+ public static void beforeClass() {
+ System.setProperty("CLOUD_UPDATE_DELAY", "1");
+ }
+
+ @Test
+ public void testBasic() throws Exception {
+ // test using ZooKeeper
+ assertTrue("Not using ZooKeeper", h.getCoreContainer().isZooKeeperAware());
+
+ ZkController zkController = h.getCoreContainer().getZkController();
+
+ // test merge factor picked up
+ SolrCore core = h.getCore();
+ SolrIndexWriter writer = new SolrIndexWriter("testWriter", core
+ .getNewIndexDir(), core.getDirectoryFactory(), false, core.getSchema(),
+ core.getSolrConfig().mainIndexConfig, core.getDeletionPolicy());
+ assertEquals("Mergefactor was not picked up", ((LogMergePolicy)writer.getConfig().getMergePolicy()).getMergeFactor(), 8);
+ writer.close();
+
+ lrf.args.put("version", "2.0");
+ assertQ("test query on empty index", req("qlkciyopsbgzyvkylsjhchghjrdf"),
+ "//result[@numFound='0']");
+
+ // test escaping of ";"
+ assertU("deleting 42 for no reason at all", delI("42"));
+ assertU("adding doc#42", adoc("id", "42", "val_s", "aa;bb"));
+ assertU("does commit work?", commit());
+
+ assertQ("backslash escaping semicolon", req("id:42 AND val_s:aa\\;bb"),
+ "//*[@numFound='1']", "//int[@name='id'][.='42']");
+
+ assertQ("quote escaping semicolon", req("id:42 AND val_s:\"aa;bb\""),
+ "//*[@numFound='1']", "//int[@name='id'][.='42']");
+
+ assertQ("no escaping semicolon", req("id:42 AND val_s:aa"),
+ "//*[@numFound='0']");
+
+ assertU(delI("42"));
+ assertU(commit());
+ assertQ(req("id:42"), "//*[@numFound='0']");
+
+ // test overwrite default of true
+
+ assertU(adoc("id", "42", "val_s", "AAA"));
+ assertU(adoc("id", "42", "val_s", "BBB"));
+ assertU(commit());
+ assertQ(req("id:42"), "//*[@numFound='1']", "//str[.='BBB']");
+ assertU(adoc("id", "42", "val_s", "CCC"));
+ assertU(adoc("id", "42", "val_s", "DDD"));
+ assertU(commit());
+ assertQ(req("id:42"), "//*[@numFound='1']", "//str[.='DDD']");
+
+ // test deletes
+ String[] adds = new String[] { add(doc("id", "101"), "overwrite", "true"),
+ add(doc("id", "101"), "overwrite", "true"),
+ add(doc("id", "105"), "overwrite", "false"),
+ add(doc("id", "102"), "overwrite", "true"),
+ add(doc("id", "103"), "overwrite", "false"),
+ add(doc("id", "101"), "overwrite", "true"), };
+ for (String a : adds) {
+ assertU(a, a);
+ }
+ assertU(commit());
+
+ zkServer.shutdown();
+
+ Thread.sleep(300);
+
+ // try a reconnect from disconnect
+ zkServer = new ZkTestServer(zkDir);
+ zkServer.run();
+
+ Thread.sleep(300);
+
+ // ensure zk still thinks node is up
+ assertTrue(
+ zkController.getCloudState().getLiveNodes().toString(),
+ zkController.getCloudState().liveNodesContain(
+ zkController.getNodeName()));
+
+ // test maxint
+ assertQ(req("q", "id:[100 TO 110]", "rows", "2147483647"),
+ "//*[@numFound='4']");
+
+ // test big limit
+ assertQ(req("q", "id:[100 TO 111]", "rows", "1147483647"),
+ "//*[@numFound='4']");
+
+ assertQ(req("id:[100 TO 110]"), "//*[@numFound='4']");
+ assertU(delI("102"));
+ assertU(commit());
+ assertQ(req("id:[100 TO 110]"), "//*[@numFound='3']");
+ assertU(delI("105"));
+ assertU(commit());
+ assertQ(req("id:[100 TO 110]"), "//*[@numFound='2']");
+ assertU(delQ("id:[100 TO 110]"));
+ assertU(commit());
+ assertQ(req("id:[100 TO 110]"), "//*[@numFound='0']");
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ System.clearProperty("CLOUD_UPDATE_DELAY");
+ }
+}
diff --git a/solr/src/test/org/apache/solr/cloud/CloudStateUpdateTest.java b/solr/src/test/org/apache/solr/cloud/CloudStateUpdateTest.java
index 3e60c0401e9..db03ce10b5f 100644
--- a/solr/src/test/org/apache/solr/cloud/CloudStateUpdateTest.java
+++ b/solr/src/test/org/apache/solr/cloud/CloudStateUpdateTest.java
@@ -1,255 +1,255 @@
-package org.apache.solr.cloud;
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.io.File;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.solr.SolrTestCaseJ4;
-import org.apache.solr.common.cloud.CloudState;
-import org.apache.solr.common.cloud.Slice;
-import org.apache.solr.common.cloud.SolrZkClient;
-import org.apache.solr.common.cloud.ZkNodeProps;
-import org.apache.solr.core.CoreContainer;
-import org.apache.solr.core.CoreContainer.Initializer;
-import org.apache.solr.core.CoreDescriptor;
-import org.apache.solr.core.SolrConfig;
-import org.apache.solr.core.SolrCore;
-import org.apache.zookeeper.CreateMode;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * TODO: look at hostPort used below
- */
-public class CloudStateUpdateTest extends SolrTestCaseJ4 {
- protected static Logger log = LoggerFactory
- .getLogger(AbstractZkTestCase.class);
-
- private static final boolean VERBOSE = false;
-
- protected ZkTestServer zkServer;
-
- protected String zkDir;
-
- private CoreContainer container1;
-
- private CoreContainer container2;
-
- private CoreContainer container3;
-
- private File dataDir1;
-
- private File dataDir2;
-
- private File dataDir3;
-
- private File dataDir4;
-
- private Initializer init2;
-
- @BeforeClass
- public static void beforeClass() throws Exception {
- initCore();
- }
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
-
- System.setProperty("zkClientTimeout", "3000");
-
- zkDir = dataDir.getAbsolutePath() + File.separator
- + "zookeeper/server1/data";
- zkServer = new ZkTestServer(zkDir);
- zkServer.run();
- System.setProperty("zkHost", zkServer.getZkAddress());
- AbstractZkTestCase.buildZooKeeper(zkServer.getZkHost(), zkServer
- .getZkAddress(), "solrconfig.xml", "schema.xml");
-
- log.info("####SETUP_START " + getName());
- dataDir1 = new File(dataDir + File.separator + "data1");
- dataDir1.mkdirs();
-
- dataDir2 = new File(dataDir + File.separator + "data2");
- dataDir2.mkdirs();
-
- dataDir3 = new File(dataDir + File.separator + "data3");
- dataDir3.mkdirs();
-
- dataDir4 = new File(dataDir + File.separator + "data3");
- dataDir4.mkdirs();
-
- // set some system properties for use by tests
- System.setProperty("solr.test.sys.prop1", "propone");
- System.setProperty("solr.test.sys.prop2", "proptwo");
-
- System.setProperty("hostPort", "1661");
- CoreContainer.Initializer init1 = new CoreContainer.Initializer() {
- {
- this.dataDir = CloudStateUpdateTest.this.dataDir1.getAbsolutePath();
- }
- };
-
- container1 = init1.initialize();
- System.clearProperty("hostPort");
-
- System.setProperty("hostPort", "1662");
- init2 = new CoreContainer.Initializer() {
- {
- this.dataDir = CloudStateUpdateTest.this.dataDir2.getAbsolutePath();
- }
- };
-
- container2 = init2.initialize();
- System.clearProperty("hostPort");
-
- System.setProperty("hostPort", "1663");
- CoreContainer.Initializer init3 = new CoreContainer.Initializer() {
- {
- this.dataDir = CloudStateUpdateTest.this.dataDir3.getAbsolutePath();
- }
- };
- container3 = init3.initialize();
- System.clearProperty("hostPort");
-
- log.info("####SETUP_END " + getName());
-
- }
-
- @Test
- public void testCoreRegistration() throws Exception {
- System.setProperty("CLOUD_UPDATE_DELAY", "1");
-
- ZkNodeProps props2 = new ZkNodeProps();
- props2.put("configName", "conf1");
-
- SolrZkClient zkClient = new SolrZkClient(zkServer.getZkAddress(), AbstractZkTestCase.TIMEOUT);
- zkClient.makePath("/collections/testcore", props2.store(), CreateMode.PERSISTENT);
- zkClient.makePath("/collections/testcore/shards", CreateMode.PERSISTENT);
- zkClient.close();
-
- CoreDescriptor dcore = new CoreDescriptor(container1, "testcore",
- "testcore");
-
- dcore.setDataDir(dataDir4.getAbsolutePath());
-
- SolrCore core = container1.create(dcore);
- container1.register(core, false);
-
- ZkController zkController2 = container2.getZkController();
-
- String host = zkController2.getHostName();
-
- // slight pause - TODO: takes an oddly long amount of time to schedule tasks
- // with almost no delay ...
- CloudState cloudState2 = null;
- Map<String,Slice> slices = null;
- for (int i = 75; i > 0; i--) {
- cloudState2 = zkController2.getCloudState();
- slices = cloudState2.getSlices("testcore");
-
- if (slices != null && slices.containsKey(host + ":1661_solr_testcore")) {
- break;
- }
- Thread.sleep(500);
- }
-
- assertNotNull(slices);
- assertTrue(slices.containsKey(host + ":1661_solr_testcore"));
-
- Slice slice = slices.get(host + ":1661_solr_testcore");
- assertEquals(host + ":1661_solr_testcore", slice.getName());
-
- Map<String,ZkNodeProps> shards = slice.getShards();
-
- assertEquals(1, shards.size());
-
- ZkNodeProps zkProps = shards.get(host + ":1661_solr_testcore");
-
- assertNotNull(zkProps);
-
- assertEquals(host + ":1661_solr", zkProps.get("node_name"));
-
- assertEquals("http://" + host + ":1661/solr/testcore", zkProps.get("url"));
-
- Set<String> liveNodes = cloudState2.getLiveNodes();
- assertNotNull(liveNodes);
- assertEquals(3, liveNodes.size());
-
- container3.shutdown();
-
- // slight pause (15s timeout) for watch to trigger
- for(int i = 0; i < (5 * 15); i++) {
- if(zkController2.getCloudState().getLiveNodes().size() == 2) {
- break;
- }
- Thread.sleep(200);
- }
-
- assertEquals(2, zkController2.getCloudState().getLiveNodes().size());
-
- // quickly kill / start client
-
- container2.getZkController().getZkClient().getSolrZooKeeper().getConnection()
- .disconnect();
- container2.shutdown();
-
- container2 = init2.initialize();
-
- // pause for watch to trigger
- for(int i = 0; i < 200; i++) {
- if (container1.getZkController().getCloudState().liveNodesContain(
- container2.getZkController().getNodeName())) {
- break;
- }
- Thread.sleep(100);
- }
-
- assertTrue(container1.getZkController().getCloudState().liveNodesContain(
- container2.getZkController().getNodeName()));
-
- }
-
- @Override
- public void tearDown() throws Exception {
- if (VERBOSE) {
- printLayout(zkServer.getZkHost());
- }
- container1.shutdown();
- container2.shutdown();
- container3.shutdown();
- zkServer.shutdown();
- super.tearDown();
- System.clearProperty("zkClientTimeout");
- System.clearProperty("zkHost");
- System.clearProperty("hostPort");
- System.clearProperty("CLOUD_UPDATE_DELAY");
- SolrConfig.severeErrors.clear();
- }
-
- private void printLayout(String zkHost) throws Exception {
- SolrZkClient zkClient = new SolrZkClient(
- zkHost, AbstractZkTestCase.TIMEOUT);
- zkClient.printLayoutToStdOut();
- zkClient.close();
- }
-}
+package org.apache.solr.cloud;
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.io.File;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.common.cloud.CloudState;
+import org.apache.solr.common.cloud.Slice;
+import org.apache.solr.common.cloud.SolrZkClient;
+import org.apache.solr.common.cloud.ZkNodeProps;
+import org.apache.solr.core.CoreContainer;
+import org.apache.solr.core.CoreContainer.Initializer;
+import org.apache.solr.core.CoreDescriptor;
+import org.apache.solr.core.SolrConfig;
+import org.apache.solr.core.SolrCore;
+import org.apache.zookeeper.CreateMode;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * TODO: look at hostPort used below
+ */
+public class CloudStateUpdateTest extends SolrTestCaseJ4 {
+ protected static Logger log = LoggerFactory
+ .getLogger(AbstractZkTestCase.class);
+
+ private static final boolean VERBOSE = false;
+
+ protected ZkTestServer zkServer;
+
+ protected String zkDir;
+
+ private CoreContainer container1;
+
+ private CoreContainer container2;
+
+ private CoreContainer container3;
+
+ private File dataDir1;
+
+ private File dataDir2;
+
+ private File dataDir3;
+
+ private File dataDir4;
+
+ private Initializer init2;
+
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ initCore();
+ }
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+
+ System.setProperty("zkClientTimeout", "3000");
+
+ zkDir = dataDir.getAbsolutePath() + File.separator
+ + "zookeeper/server1/data";
+ zkServer = new ZkTestServer(zkDir);
+ zkServer.run();
+ System.setProperty("zkHost", zkServer.getZkAddress());
+ AbstractZkTestCase.buildZooKeeper(zkServer.getZkHost(), zkServer
+ .getZkAddress(), "solrconfig.xml", "schema.xml");
+
+ log.info("####SETUP_START " + getName());
+ dataDir1 = new File(dataDir + File.separator + "data1");
+ dataDir1.mkdirs();
+
+ dataDir2 = new File(dataDir + File.separator + "data2");
+ dataDir2.mkdirs();
+
+ dataDir3 = new File(dataDir + File.separator + "data3");
+ dataDir3.mkdirs();
+
+ dataDir4 = new File(dataDir + File.separator + "data3");
+ dataDir4.mkdirs();
+
+ // set some system properties for use by tests
+ System.setProperty("solr.test.sys.prop1", "propone");
+ System.setProperty("solr.test.sys.prop2", "proptwo");
+
+ System.setProperty("hostPort", "1661");
+ CoreContainer.Initializer init1 = new CoreContainer.Initializer() {
+ {
+ this.dataDir = CloudStateUpdateTest.this.dataDir1.getAbsolutePath();
+ }
+ };
+
+ container1 = init1.initialize();
+ System.clearProperty("hostPort");
+
+ System.setProperty("hostPort", "1662");
+ init2 = new CoreContainer.Initializer() {
+ {
+ this.dataDir = CloudStateUpdateTest.this.dataDir2.getAbsolutePath();
+ }
+ };
+
+ container2 = init2.initialize();
+ System.clearProperty("hostPort");
+
+ System.setProperty("hostPort", "1663");
+ CoreContainer.Initializer init3 = new CoreContainer.Initializer() {
+ {
+ this.dataDir = CloudStateUpdateTest.this.dataDir3.getAbsolutePath();
+ }
+ };
+ container3 = init3.initialize();
+ System.clearProperty("hostPort");
+
+ log.info("####SETUP_END " + getName());
+
+ }
+
+ @Test
+ public void testCoreRegistration() throws Exception {
+ System.setProperty("CLOUD_UPDATE_DELAY", "1");
+
+ ZkNodeProps props2 = new ZkNodeProps();
+ props2.put("configName", "conf1");
+
+ SolrZkClient zkClient = new SolrZkClient(zkServer.getZkAddress(), AbstractZkTestCase.TIMEOUT);
+ zkClient.makePath("/collections/testcore", props2.store(), CreateMode.PERSISTENT);
+ zkClient.makePath("/collections/testcore/shards", CreateMode.PERSISTENT);
+ zkClient.close();
+
+ CoreDescriptor dcore = new CoreDescriptor(container1, "testcore",
+ "testcore");
+
+ dcore.setDataDir(dataDir4.getAbsolutePath());
+
+ SolrCore core = container1.create(dcore);
+ container1.register(core, false);
+
+ ZkController zkController2 = container2.getZkController();
+
+ String host = zkController2.getHostName();
+
+ // slight pause - TODO: takes an oddly long amount of time to schedule tasks
+ // with almost no delay ...
+ CloudState cloudState2 = null;
+ Map<String,Slice> slices = null;
+ for (int i = 75; i > 0; i--) {
+ cloudState2 = zkController2.getCloudState();
+ slices = cloudState2.getSlices("testcore");
+
+ if (slices != null && slices.containsKey(host + ":1661_solr_testcore")) {
+ break;
+ }
+ Thread.sleep(500);
+ }
+
+ assertNotNull(slices);
+ assertTrue(slices.containsKey(host + ":1661_solr_testcore"));
+
+ Slice slice = slices.get(host + ":1661_solr_testcore");
+ assertEquals(host + ":1661_solr_testcore", slice.getName());
+
+ Map<String,ZkNodeProps> shards = slice.getShards();
+
+ assertEquals(1, shards.size());
+
+ ZkNodeProps zkProps = shards.get(host + ":1661_solr_testcore");
+
+ assertNotNull(zkProps);
+
+ assertEquals(host + ":1661_solr", zkProps.get("node_name"));
+
+ assertEquals("http://" + host + ":1661/solr/testcore", zkProps.get("url"));
+
+ Set<String> liveNodes = cloudState2.getLiveNodes();
+ assertNotNull(liveNodes);
+ assertEquals(3, liveNodes.size());
+
+ container3.shutdown();
+
+ // slight pause (15s timeout) for watch to trigger
+ for(int i = 0; i < (5 * 15); i++) {
+ if(zkController2.getCloudState().getLiveNodes().size() == 2) {
+ break;
+ }
+ Thread.sleep(200);
+ }
+
+ assertEquals(2, zkController2.getCloudState().getLiveNodes().size());
+
+ // quickly kill / start client
+
+ container2.getZkController().getZkClient().getSolrZooKeeper().getConnection()
+ .disconnect();
+ container2.shutdown();
+
+ container2 = init2.initialize();
+
+ // pause for watch to trigger
+ for(int i = 0; i < 200; i++) {
+ if (container1.getZkController().getCloudState().liveNodesContain(
+ container2.getZkController().getNodeName())) {
+ break;
+ }
+ Thread.sleep(100);
+ }
+
+ assertTrue(container1.getZkController().getCloudState().liveNodesContain(
+ container2.getZkController().getNodeName()));
+
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ if (VERBOSE) {
+ printLayout(zkServer.getZkHost());
+ }
+ container1.shutdown();
+ container2.shutdown();
+ container3.shutdown();
+ zkServer.shutdown();
+ super.tearDown();
+ System.clearProperty("zkClientTimeout");
+ System.clearProperty("zkHost");
+ System.clearProperty("hostPort");
+ System.clearProperty("CLOUD_UPDATE_DELAY");
+ SolrConfig.severeErrors.clear();
+ }
+
+ private void printLayout(String zkHost) throws Exception {
+ SolrZkClient zkClient = new SolrZkClient(
+ zkHost, AbstractZkTestCase.TIMEOUT);
+ zkClient.printLayoutToStdOut();
+ zkClient.close();
+ }
+}
diff --git a/solr/src/test/org/apache/solr/cloud/ZkControllerTest.java b/solr/src/test/org/apache/solr/cloud/ZkControllerTest.java
index f8eedd9cb5a..5b74b0926ac 100644
--- a/solr/src/test/org/apache/solr/cloud/ZkControllerTest.java
+++ b/solr/src/test/org/apache/solr/cloud/ZkControllerTest.java
@@ -1,225 +1,225 @@
-package org.apache.solr.cloud;
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Map;
-
-import org.apache.solr.SolrTestCaseJ4;
-import org.apache.solr.common.cloud.CloudState;
-import org.apache.solr.common.cloud.Slice;
-import org.apache.solr.common.cloud.SolrZkClient;
-import org.apache.solr.common.cloud.ZkNodeProps;
-import org.apache.solr.common.cloud.ZkStateReader;
-import org.apache.solr.core.SolrConfig;
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.KeeperException;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-public class ZkControllerTest extends SolrTestCaseJ4 {
-
- private static final String TEST_NODE_NAME = "test_node_name";
-
- private static final String URL3 = "http://localhost:3133/solr/core1";
-
- private static final String URL2 = "http://localhost:3123/solr/core1";
-
- private static final String SHARD3 = "localhost:3123_solr_core3";
-
- private static final String SHARD2 = "localhost:3123_solr_core2";
-
- private static final String SHARD1 = "localhost:3123_solr_core1";
-
- private static final String COLLECTION_NAME = "collection1";
-
- static final int TIMEOUT = 10000;
-
- private static final String URL1 = "http://localhost:3133/solr/core0";
-
- private static final boolean DEBUG = false;
-
- @BeforeClass
- public static void beforeClass() throws Exception {
- initCore();
- }
-
- @Test
- public void testReadShards() throws Exception {
- String zkDir = dataDir.getAbsolutePath() + File.separator
- + "zookeeper/server1/data";
- ZkTestServer server = null;
- SolrZkClient zkClient = null;
- ZkController zkController = null;
- try {
- server = new ZkTestServer(zkDir);
- server.run();
- AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost());
- AbstractZkTestCase.makeSolrZkNode(server.getZkHost());
-
- zkClient = new SolrZkClient(server.getZkAddress(), TIMEOUT);
- String shardsPath = "/collections/collection1/shards/shardid1";
- zkClient.makePath(shardsPath);
-
- addShardToZk(zkClient, shardsPath, SHARD1, URL1);
- addShardToZk(zkClient, shardsPath, SHARD2, URL2);
- addShardToZk(zkClient, shardsPath, SHARD3, URL3);
-
- if (DEBUG) {
- zkClient.printLayoutToStdOut();
- }
-
- zkController = new ZkController(server.getZkAddress(),
- TIMEOUT, 1000, "localhost", "8983", "solr");
-
- zkController.getZkStateReader().updateCloudState(true);
- CloudState cloudInfo = zkController.getCloudState();
- Map<String,Slice> slices = cloudInfo.getSlices("collection1");
- assertNotNull(slices);
-
- for (Slice slice : slices.values()) {
- Map<String,ZkNodeProps> shards = slice.getShards();
- if (DEBUG) {
- for (String shardName : shards.keySet()) {
- ZkNodeProps props = shards.get(shardName);
- System.out.println("shard:" + shardName);
- System.out.println("props:" + props.toString());
- }
- }
- assertNotNull(shards.get(SHARD1));
- assertNotNull(shards.get(SHARD2));
- assertNotNull(shards.get(SHARD3));
-
- ZkNodeProps props = shards.get(SHARD1);
- assertEquals(URL1, props.get(ZkStateReader.URL_PROP));
- assertEquals(TEST_NODE_NAME, props.get(ZkStateReader.NODE_NAME));
-
- props = shards.get(SHARD2);
- assertEquals(URL2, props.get(ZkStateReader.URL_PROP));
- assertEquals(TEST_NODE_NAME, props.get(ZkStateReader.NODE_NAME));
-
- props = shards.get(SHARD3);
- assertEquals(URL3, props.get(ZkStateReader.URL_PROP));
- assertEquals(TEST_NODE_NAME, props.get(ZkStateReader.NODE_NAME));
-
- }
-
- } finally {
- if (zkClient != null) {
- zkClient.close();
- }
- if (zkController != null) {
- zkController.close();
- }
- if (server != null) {
- server.shutdown();
- }
- }
- }
-
- @Test
- public void testReadConfigName() throws Exception {
- String zkDir = dataDir.getAbsolutePath() + File.separator
- + "zookeeper/server1/data";
-
- ZkTestServer server = new ZkTestServer(zkDir);
- try {
- server.run();
-
- AbstractZkTestCase.makeSolrZkNode(server.getZkHost());
-
- SolrZkClient zkClient = new SolrZkClient(server.getZkAddress(), TIMEOUT);
- String actualConfigName = "firstConfig";
-
- zkClient.makePath(ZkController.CONFIGS_ZKNODE + "/" + actualConfigName);
-
- ZkNodeProps props = new ZkNodeProps();
- props.put("configName", actualConfigName);
- zkClient.makePath(ZkStateReader.COLLECTIONS_ZKNODE + "/" + COLLECTION_NAME , props.store(), CreateMode.PERSISTENT);
-
- if (DEBUG) {
- zkClient.printLayoutToStdOut();
- }
- zkClient.close();
- ZkController zkController = new ZkController(server.getZkAddress(), TIMEOUT, TIMEOUT,
- "localhost", "8983", "/solr");
- try {
- String configName = zkController.readConfigName(COLLECTION_NAME);
- assertEquals(configName, actualConfigName);
- } finally {
- zkController.close();
- }
- } finally {
-
- server.shutdown();
- }
-
- }
-
- @Test
- public void testUploadToCloud() throws Exception {
- String zkDir = dataDir.getAbsolutePath() + File.separator
- + "zookeeper/server1/data";
-
- ZkTestServer server = new ZkTestServer(zkDir);
- ZkController zkController = null;
- try {
- server.run();
-
- AbstractZkTestCase.makeSolrZkNode(server.getZkHost());
-
- zkController = new ZkController(server.getZkAddress(),
- TIMEOUT, 1000, "localhost", "8983", "/solr");
-
- zkController.uploadToZK(getFile("solr/conf"),
- ZkController.CONFIGS_ZKNODE + "/config1");
-
- if (DEBUG) {
- zkController.printLayoutToStdOut();
- }
-
- } finally {
- if (zkController != null) {
- zkController.close();
- }
- server.shutdown();
- }
-
- }
-
- private void addShardToZk(SolrZkClient zkClient, String shardsPath,
- String zkNodeName, String url) throws IOException,
- KeeperException, InterruptedException {
-
- ZkNodeProps props = new ZkNodeProps();
- props.put(ZkStateReader.URL_PROP, url);
- props.put(ZkStateReader.NODE_NAME, TEST_NODE_NAME);
- byte[] bytes = props.store();
-
- zkClient
- .create(shardsPath + "/" + zkNodeName, bytes, CreateMode.PERSISTENT);
- }
-
- @Override
- public void tearDown() throws Exception {
- SolrConfig.severeErrors.clear();
- super.tearDown();
- }
-}
+package org.apache.solr.cloud;
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with this
+ * work for additional information regarding copyright ownership. The ASF
+ * licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Map;
+
+import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.common.cloud.CloudState;
+import org.apache.solr.common.cloud.Slice;
+import org.apache.solr.common.cloud.SolrZkClient;
+import org.apache.solr.common.cloud.ZkNodeProps;
+import org.apache.solr.common.cloud.ZkStateReader;
+import org.apache.solr.core.SolrConfig;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.KeeperException;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class ZkControllerTest extends SolrTestCaseJ4 {
+
+ private static final String TEST_NODE_NAME = "test_node_name";
+
+ private static final String URL3 = "http://localhost:3133/solr/core1";
+
+ private static final String URL2 = "http://localhost:3123/solr/core1";
+
+ private static final String SHARD3 = "localhost:3123_solr_core3";
+
+ private static final String SHARD2 = "localhost:3123_solr_core2";
+
+ private static final String SHARD1 = "localhost:3123_solr_core1";
+
+ private static final String COLLECTION_NAME = "collection1";
+
+ static final int TIMEOUT = 10000;
+
+ private static final String URL1 = "http://localhost:3133/solr/core0";
+
+ private static final boolean DEBUG = false;
+
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ initCore();
+ }
+
+ @Test
+ public void testReadShards() throws Exception {
+ String zkDir = dataDir.getAbsolutePath() + File.separator
+ + "zookeeper/server1/data";
+ ZkTestServer server = null;
+ SolrZkClient zkClient = null;
+ ZkController zkController = null;
+ try {
+ server = new ZkTestServer(zkDir);
+ server.run();
+ AbstractZkTestCase.tryCleanSolrZkNode(server.getZkHost());
+ AbstractZkTestCase.makeSolrZkNode(server.getZkHost());
+
+ zkClient = new SolrZkClient(server.getZkAddress(), TIMEOUT);
+ String shardsPath = "/collections/collection1/shards/shardid1";
+ zkClient.makePath(shardsPath);
+
+ addShardToZk(zkClient, shardsPath, SHARD1, URL1);
+ addShardToZk(zkClient, shardsPath, SHARD2, URL2);
+ addShardToZk(zkClient, shardsPath, SHARD3, URL3);
+
+ if (DEBUG) {
+ zkClient.printLayoutToStdOut();
+ }
+
+ zkController = new ZkController(server.getZkAddress(),
+ TIMEOUT, 1000, "localhost", "8983", "solr");
+
+ zkController.getZkStateReader().updateCloudState(true);
+ CloudState cloudInfo = zkController.getCloudState();
+ Map<String,Slice> slices = cloudInfo.getSlices("collection1");
+ assertNotNull(slices);
+
+ for (Slice slice : slices.values()) {
+ Map<String,ZkNodeProps> shards = slice.getShards();
+ if (DEBUG) {
+ for (String shardName : shards.keySet()) {
+ ZkNodeProps props = shards.get(shardName);
+ System.out.println("shard:" + shardName);
+ System.out.println("props:" + props.toString());
+ }
+ }
+ assertNotNull(shards.get(SHARD1));
+ assertNotNull(shards.get(SHARD2));
+ assertNotNull(shards.get(SHARD3));
+
+ ZkNodeProps props = shards.get(SHARD1);
+ assertEquals(URL1, props.get(ZkStateReader.URL_PROP));
+ assertEquals(TEST_NODE_NAME, props.get(ZkStateReader.NODE_NAME));
+
+ props = shards.get(SHARD2);
+ assertEquals(URL2, props.get(ZkStateReader.URL_PROP));
+ assertEquals(TEST_NODE_NAME, props.get(ZkStateReader.NODE_NAME));
+
+ props = shards.get(SHARD3);
+ assertEquals(URL3, props.get(ZkStateReader.URL_PROP));
+ assertEquals(TEST_NODE_NAME, props.get(ZkStateReader.NODE_NAME));
+
+ }
+
+ } finally {
+ if (zkClient != null) {
+ zkClient.close();
+ }
+ if (zkController != null) {
+ zkController.close();
+ }
+ if (server != null) {
+ server.shutdown();
+ }
+ }
+ }
+
+ @Test
+ public void testReadConfigName() throws Exception {
+ String zkDir = dataDir.getAbsolutePath() + File.separator
+ + "zookeeper/server1/data";
+
+ ZkTestServer server = new ZkTestServer(zkDir);
+ try {
+ server.run();
+
+ AbstractZkTestCase.makeSolrZkNode(server.getZkHost());
+
+ SolrZkClient zkClient = new SolrZkClient(server.getZkAddress(), TIMEOUT);
+ String actualConfigName = "firstConfig";
+
+ zkClient.makePath(ZkController.CONFIGS_ZKNODE + "/" + actualConfigName);
+
+ ZkNodeProps props = new ZkNodeProps();
+ props.put("configName", actualConfigName);
+ zkClient.makePath(ZkStateReader.COLLECTIONS_ZKNODE + "/" + COLLECTION_NAME , props.store(), CreateMode.PERSISTENT);
+
+ if (DEBUG) {
+ zkClient.printLayoutToStdOut();
+ }
+ zkClient.close();
+ ZkController zkController = new ZkController(server.getZkAddress(), TIMEOUT, TIMEOUT,
+ "localhost", "8983", "/solr");
+ try {
+ String configName = zkController.readConfigName(COLLECTION_NAME);
+ assertEquals(configName, actualConfigName);
+ } finally {
+ zkController.close();
+ }
+ } finally {
+
+ server.shutdown();
+ }
+
+ }
+
+ @Test
+ public void testUploadToCloud() throws Exception {
+ String zkDir = dataDir.getAbsolutePath() + File.separator
+ + "zookeeper/server1/data";
+
+ ZkTestServer server = new ZkTestServer(zkDir);
+ ZkController zkController = null;
+ try {
+ server.run();
+
+ AbstractZkTestCase.makeSolrZkNode(server.getZkHost());
+
+ zkController = new ZkController(server.getZkAddress(),
+ TIMEOUT, 1000, "localhost", "8983", "/solr");
+
+ zkController.uploadToZK(getFile("solr/conf"),
+ ZkController.CONFIGS_ZKNODE + "/config1");
+
+ if (DEBUG) {
+ zkController.printLayoutToStdOut();
+ }
+
+ } finally {
+ if (zkController != null) {
+ zkController.close();
+ }
+ server.shutdown();
+ }
+
+ }
+
+ private void addShardToZk(SolrZkClient zkClient, String shardsPath,
+ String zkNodeName, String url) throws IOException,
+ KeeperException, InterruptedException {
+
+ ZkNodeProps props = new ZkNodeProps();
+ props.put(ZkStateReader.URL_PROP, url);
+ props.put(ZkStateReader.NODE_NAME, TEST_NODE_NAME);
+ byte[] bytes = props.store();
+
+ zkClient
+ .create(shardsPath + "/" + zkNodeName, bytes, CreateMode.PERSISTENT);
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ SolrConfig.severeErrors.clear();
+ super.tearDown();
+ }
+}
diff --git a/solr/src/test/org/apache/solr/cloud/ZkNodePropsTest.java b/solr/src/test/org/apache/solr/cloud/ZkNodePropsTest.java
index e7516e2338f..3da482c4cf7 100644
--- a/solr/src/test/org/apache/solr/cloud/ZkNodePropsTest.java
+++ b/solr/src/test/org/apache/solr/cloud/ZkNodePropsTest.java
@@ -1,49 +1,49 @@
-package org.apache.solr.cloud;
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-import java.io.IOException;
-
-import org.apache.solr.SolrTestCaseJ4;
-import org.apache.solr.common.cloud.ZkNodeProps;
-import org.junit.Test;
-
-
-public class ZkNodePropsTest extends SolrTestCaseJ4 {
- @Test
- public void testBasic() throws IOException {
-
- ZkNodeProps props = new ZkNodeProps();
- props.put("prop1", "value1");
- props.put("prop2", "value2");
- props.put("prop3", "value3");
- props.put("prop4", "value4");
- props.put("prop5", "value5");
- props.put("prop6", "value6");
- byte[] bytes = props.store();
-
- ZkNodeProps props2 = new ZkNodeProps();
- props2.load(bytes);
- assertEquals("value1", props2.get("prop1"));
- assertEquals("value2", props2.get("prop2"));
- assertEquals("value3", props2.get("prop3"));
- assertEquals("value4", props2.get("prop4"));
- assertEquals("value5", props2.get("prop5"));
- assertEquals("value6", props2.get("prop6"));
- }
-}
+package org.apache.solr.cloud;
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with this
+ * work for additional information regarding copyright ownership. The ASF
+ * licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+import java.io.IOException;
+
+import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.common.cloud.ZkNodeProps;
+import org.junit.Test;
+
+
+public class ZkNodePropsTest extends SolrTestCaseJ4 {
+ @Test
+ public void testBasic() throws IOException {
+
+ ZkNodeProps props = new ZkNodeProps();
+ props.put("prop1", "value1");
+ props.put("prop2", "value2");
+ props.put("prop3", "value3");
+ props.put("prop4", "value4");
+ props.put("prop5", "value5");
+ props.put("prop6", "value6");
+ byte[] bytes = props.store();
+
+ ZkNodeProps props2 = new ZkNodeProps();
+ props2.load(bytes);
+ assertEquals("value1", props2.get("prop1"));
+ assertEquals("value2", props2.get("prop2"));
+ assertEquals("value3", props2.get("prop3"));
+ assertEquals("value4", props2.get("prop4"));
+ assertEquals("value5", props2.get("prop5"));
+ assertEquals("value6", props2.get("prop6"));
+ }
+}
diff --git a/solr/src/test/org/apache/solr/cloud/ZkSolrClientTest.java b/solr/src/test/org/apache/solr/cloud/ZkSolrClientTest.java
index 7aece955627..7358e1987b1 100644
--- a/solr/src/test/org/apache/solr/cloud/ZkSolrClientTest.java
+++ b/solr/src/test/org/apache/solr/cloud/ZkSolrClientTest.java
@@ -1,241 +1,241 @@
-package org.apache.solr.cloud;
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-import java.io.File;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import junit.framework.TestCase;
-
-import org.apache.solr.common.cloud.SolrZkClient;
-import org.apache.solr.core.SolrConfig;
-import org.apache.solr.util.AbstractSolrTestCase;
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
-
-public class ZkSolrClientTest extends AbstractSolrTestCase {
- private static final boolean DEBUG = false;
-
- public void testConnect() throws Exception {
- String zkDir = dataDir.getAbsolutePath() + File.separator
- + "zookeeper/server1/data";
- ZkTestServer server = null;
-
- server = new ZkTestServer(zkDir);
- server.run();
-
- SolrZkClient zkClient = new SolrZkClient(server.getZkAddress(), 100);
-
- zkClient.close();
- server.shutdown();
- }
-
- public void testMakeRootNode() throws Exception {
- String zkDir = dataDir.getAbsolutePath() + File.separator
- + "zookeeper/server1/data";
- ZkTestServer server = null;
-
- server = new ZkTestServer(zkDir);
- server.run();
-
- AbstractZkTestCase.makeSolrZkNode(server.getZkHost());
-
- SolrZkClient zkClient = new SolrZkClient(server.getZkHost(),
- AbstractZkTestCase.TIMEOUT);
-
- assertTrue(zkClient.exists("/solr"));
-
- zkClient.close();
- server.shutdown();
- }
-
- public void testReconnect() throws Exception {
- String zkDir = dataDir.getAbsolutePath() + File.separator
- + "zookeeper/server1/data";
- ZkTestServer server = null;
- SolrZkClient zkClient = null;
- try {
- server = new ZkTestServer(zkDir);
- server.run();
-
- AbstractZkTestCase.makeSolrZkNode(server.getZkHost());
-
- zkClient = new SolrZkClient(server.getZkAddress(), AbstractZkTestCase.TIMEOUT);
- String shardsPath = "/collections/collection1/shards";
- zkClient.makePath(shardsPath);
-
- zkClient.makePath("collections/collection1");
- int zkServerPort = server.getPort();
- // this tests disconnect state
- server.shutdown();
-
- Thread.sleep(80);
-
-
- try {
- zkClient.makePath("collections/collection2");
- TestCase.fail("Server should be down here");
- } catch (KeeperException.ConnectionLossException e) {
-
- }
-
- // bring server back up
- server = new ZkTestServer(zkDir, zkServerPort);
- server.run();
-
- // TODO: can we do better?
- // wait for reconnect
- Thread.sleep(600);
-
- try {
- zkClient.makePath("collections/collection3");
- } catch (KeeperException.ConnectionLossException e) {
- Thread.sleep(5000); // try again in a bit
- zkClient.makePath("collections/collection3");
- }
-
- if (DEBUG) {
- zkClient.printLayoutToStdOut();
- }
-
- assertNotNull(zkClient.exists("/collections/collection3", null));
- assertNotNull(zkClient.exists("/collections/collection1", null));
-
- // simulate session expiration
-
- // one option
- long sessionId = zkClient.getSolrZooKeeper().getSessionId();
- server.expire(sessionId);
-
- // another option
- //zkClient.getSolrZooKeeper().getConnection().disconnect();
-
- // this tests expired state
-
- Thread.sleep(1000); // pause for reconnect
-
- for (int i = 0; i < 8; i++) {
- try {
- zkClient.makePath("collections/collection4");
- break;
- } catch (KeeperException.SessionExpiredException e) {
-
- } catch (KeeperException.ConnectionLossException e) {
-
- }
- Thread.sleep(1000 * i);
- }
-
- if (DEBUG) {
- zkClient.printLayoutToStdOut();
- }
-
- assertNotNull("Node does not exist, but it should", zkClient.exists("/collections/collection4", null));
-
- } finally {
-
- if (zkClient != null) {
- zkClient.close();
- }
- if (server != null) {
- server.shutdown();
- }
- }
- }
-
- public void testWatchChildren() throws Exception {
- String zkDir = dataDir.getAbsolutePath() + File.separator
- + "zookeeper/server1/data";
-
- final AtomicInteger cnt = new AtomicInteger();
- ZkTestServer server = new ZkTestServer(zkDir);
- server.run();
- Thread.sleep(400);
- AbstractZkTestCase.makeSolrZkNode(server.getZkHost());
- final SolrZkClient zkClient = new SolrZkClient(server.getZkAddress(), AbstractZkTestCase.TIMEOUT);
- try {
- zkClient.makePath("/collections");
-
- zkClient.getChildren("/collections", new Watcher() {
-
- public void process(WatchedEvent event) {
- if (DEBUG) {
- System.out.println("children changed");
- }
- cnt.incrementAndGet();
- // remake watch
- try {
- zkClient.getChildren("/collections", this);
- } catch (KeeperException e) {
- throw new RuntimeException(e);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- });
-
- zkClient.makePath("/collections/collection99/shards");
-
- zkClient.makePath("collections/collection99/config=collection1");
-
- zkClient.makePath("collections/collection99/config=collection3");
-
- zkClient.makePath("/collections/collection97/shards");
-
- if (DEBUG) {
- zkClient.printLayoutToStdOut();
- }
-
- // pause for the watches to fire
- Thread.sleep(700);
-
- if (cnt.intValue() < 2) {
- Thread.sleep(4000); // wait a bit more
- }
-
- assertEquals(2, cnt.intValue());
-
- } finally {
-
- if (zkClient != null) {
- zkClient.close();
- }
- if (server != null) {
- server.shutdown();
- }
- }
- }
-
- @Override
- public String getSchemaFile() {
- return null;
- }
-
- @Override
- public String getSolrConfigFile() {
- return null;
- }
-
- @Override
- public void tearDown() throws Exception {
- SolrConfig.severeErrors.clear();
- super.tearDown();
- }
-
-}
+package org.apache.solr.cloud;
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with this
+ * work for additional information regarding copyright ownership. The ASF
+ * licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+import java.io.File;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import junit.framework.TestCase;
+
+import org.apache.solr.common.cloud.SolrZkClient;
+import org.apache.solr.core.SolrConfig;
+import org.apache.solr.util.AbstractSolrTestCase;
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.WatchedEvent;
+import org.apache.zookeeper.Watcher;
+
+public class ZkSolrClientTest extends AbstractSolrTestCase {
+ private static final boolean DEBUG = false;
+
+ public void testConnect() throws Exception {
+ String zkDir = dataDir.getAbsolutePath() + File.separator
+ + "zookeeper/server1/data";
+ ZkTestServer server = null;
+
+ server = new ZkTestServer(zkDir);
+ server.run();
+
+ SolrZkClient zkClient = new SolrZkClient(server.getZkAddress(), 100);
+
+ zkClient.close();
+ server.shutdown();
+ }
+
+ public void testMakeRootNode() throws Exception {
+ String zkDir = dataDir.getAbsolutePath() + File.separator
+ + "zookeeper/server1/data";
+ ZkTestServer server = null;
+
+ server = new ZkTestServer(zkDir);
+ server.run();
+
+ AbstractZkTestCase.makeSolrZkNode(server.getZkHost());
+
+ SolrZkClient zkClient = new SolrZkClient(server.getZkHost(),
+ AbstractZkTestCase.TIMEOUT);
+
+ assertTrue(zkClient.exists("/solr"));
+
+ zkClient.close();
+ server.shutdown();
+ }
+
+ public void testReconnect() throws Exception {
+ String zkDir = dataDir.getAbsolutePath() + File.separator
+ + "zookeeper/server1/data";
+ ZkTestServer server = null;
+ SolrZkClient zkClient = null;
+ try {
+ server = new ZkTestServer(zkDir);
+ server.run();
+
+ AbstractZkTestCase.makeSolrZkNode(server.getZkHost());
+
+ zkClient = new SolrZkClient(server.getZkAddress(), AbstractZkTestCase.TIMEOUT);
+ String shardsPath = "/collections/collection1/shards";
+ zkClient.makePath(shardsPath);
+
+ zkClient.makePath("collections/collection1");
+ int zkServerPort = server.getPort();
+ // this tests disconnect state
+ server.shutdown();
+
+ Thread.sleep(80);
+
+
+ try {
+ zkClient.makePath("collections/collection2");
+ TestCase.fail("Server should be down here");
+ } catch (KeeperException.ConnectionLossException e) {
+
+ }
+
+ // bring server back up
+ server = new ZkTestServer(zkDir, zkServerPort);
+ server.run();
+
+ // TODO: can we do better?
+ // wait for reconnect
+ Thread.sleep(600);
+
+ try {
+ zkClient.makePath("collections/collection3");
+ } catch (KeeperException.ConnectionLossException e) {
+ Thread.sleep(5000); // try again in a bit
+ zkClient.makePath("collections/collection3");
+ }
+
+ if (DEBUG) {
+ zkClient.printLayoutToStdOut();
+ }
+
+ assertNotNull(zkClient.exists("/collections/collection3", null));
+ assertNotNull(zkClient.exists("/collections/collection1", null));
+
+ // simulate session expiration
+
+ // one option
+ long sessionId = zkClient.getSolrZooKeeper().getSessionId();
+ server.expire(sessionId);
+
+ // another option
+ //zkClient.getSolrZooKeeper().getConnection().disconnect();
+
+ // this tests expired state
+
+ Thread.sleep(1000); // pause for reconnect
+
+ for (int i = 0; i < 8; i++) {
+ try {
+ zkClient.makePath("collections/collection4");
+ break;
+ } catch (KeeperException.SessionExpiredException e) {
+
+ } catch (KeeperException.ConnectionLossException e) {
+
+ }
+ Thread.sleep(1000 * i);
+ }
+
+ if (DEBUG) {
+ zkClient.printLayoutToStdOut();
+ }
+
+ assertNotNull("Node does not exist, but it should", zkClient.exists("/collections/collection4", null));
+
+ } finally {
+
+ if (zkClient != null) {
+ zkClient.close();
+ }
+ if (server != null) {
+ server.shutdown();
+ }
+ }
+ }
+
+ public void testWatchChildren() throws Exception {
+ String zkDir = dataDir.getAbsolutePath() + File.separator
+ + "zookeeper/server1/data";
+
+ final AtomicInteger cnt = new AtomicInteger();
+ ZkTestServer server = new ZkTestServer(zkDir);
+ server.run();
+ Thread.sleep(400);
+ AbstractZkTestCase.makeSolrZkNode(server.getZkHost());
+ final SolrZkClient zkClient = new SolrZkClient(server.getZkAddress(), AbstractZkTestCase.TIMEOUT);
+ try {
+ zkClient.makePath("/collections");
+
+ zkClient.getChildren("/collections", new Watcher() {
+
+ public void process(WatchedEvent event) {
+ if (DEBUG) {
+ System.out.println("children changed");
+ }
+ cnt.incrementAndGet();
+ // remake watch
+ try {
+ zkClient.getChildren("/collections", this);
+ } catch (KeeperException e) {
+ throw new RuntimeException(e);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ });
+
+ zkClient.makePath("/collections/collection99/shards");
+
+ zkClient.makePath("collections/collection99/config=collection1");
+
+ zkClient.makePath("collections/collection99/config=collection3");
+
+ zkClient.makePath("/collections/collection97/shards");
+
+ if (DEBUG) {
+ zkClient.printLayoutToStdOut();
+ }
+
+ // pause for the watches to fire
+ Thread.sleep(700);
+
+ if (cnt.intValue() < 2) {
+ Thread.sleep(4000); // wait a bit more
+ }
+
+ assertEquals(2, cnt.intValue());
+
+ } finally {
+
+ if (zkClient != null) {
+ zkClient.close();
+ }
+ if (server != null) {
+ server.shutdown();
+ }
+ }
+ }
+
+ @Override
+ public String getSchemaFile() {
+ return null;
+ }
+
+ @Override
+ public String getSolrConfigFile() {
+ return null;
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ SolrConfig.severeErrors.clear();
+ super.tearDown();
+ }
+
+}
diff --git a/solr/src/test/org/apache/solr/cloud/ZkTestServer.java b/solr/src/test/org/apache/solr/cloud/ZkTestServer.java
index ef1275823cb..d435910d790 100644
--- a/solr/src/test/org/apache/solr/cloud/ZkTestServer.java
+++ b/solr/src/test/org/apache/solr/cloud/ZkTestServer.java
@@ -1,319 +1,319 @@
-package org.apache.solr.cloud;
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.management.JMException;
-
-import org.apache.solr.SolrTestCaseJ4;
-import org.apache.zookeeper.jmx.ManagedUtil;
-import org.apache.zookeeper.server.NIOServerCnxn;
-import org.apache.zookeeper.server.ServerConfig;
-import org.apache.zookeeper.server.ZooKeeperServer;
-import org.apache.zookeeper.server.SessionTracker.Session;
-import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
-import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
-
-public class ZkTestServer {
-
- protected final ZKServerMain zkServer = new ZKServerMain();
-
- private String zkDir;
-
- private int clientPort;
-
- private Thread zooThread;
-
- class ZKServerMain {
-
- private NIOServerCnxn.Factory cnxnFactory;
- private ZooKeeperServer zooKeeperServer;
-
- protected void initializeAndRun(String[] args) throws ConfigException,
- IOException {
- try {
- ManagedUtil.registerLog4jMBeans();
- } catch (JMException e) {
-
- }
-
- ServerConfig config = new ServerConfig();
- if (args.length == 1) {
- config.parse(args[0]);
- } else {
- config.parse(args);
- }
-
- runFromConfig(config);
- }
-
- /**
- * Run from a ServerConfig.
- *
- * @param config ServerConfig to use.
- * @throws IOException
- */
- public void runFromConfig(ServerConfig config) throws IOException {
- try {
- // Note that this thread isn't going to be doing anything else,
- // so rather than spawning another thread, we will just call
- // run() in this thread.
- // create a file logger url from the command line args
- zooKeeperServer = new ZooKeeperServer();
-
- FileTxnSnapLog ftxn = new FileTxnSnapLog(new File(config
- .getDataLogDir()), new File(config.getDataDir()));
- zooKeeperServer.setTxnLogFactory(ftxn);
- zooKeeperServer.setTickTime(config.getTickTime());
- cnxnFactory = new NIOServerCnxn.Factory(config.getClientPortAddress(), config
- .getMaxClientCnxns());
- cnxnFactory.startup(zooKeeperServer);
- cnxnFactory.join();
- if (zooKeeperServer.isRunning()) {
- zooKeeperServer.shutdown();
- }
- } catch (InterruptedException e) {
- }
- }
-
- /**
- * Shutdown the serving instance
- * @throws IOException
- */
- protected void shutdown() throws IOException {
- zooKeeperServer.shutdown();
- zooKeeperServer.getZKDatabase().close();
- waitForServerDown(getZkHost() + ":" + getPort(), 5000);
- cnxnFactory.shutdown();
- }
-
- public int getLocalPort() {
- if (cnxnFactory == null) {
- throw new IllegalStateException("A port has not yet been selected");
- }
- int port = cnxnFactory.getLocalPort();
- if (port == 0) {
- throw new IllegalStateException("A port has not yet been selected");
- }
- return port;
- }
- }
-
- public ZkTestServer(String zkDir) {
- this.zkDir = zkDir;
- }
-
- public ZkTestServer(String zkDir, int port) {
- this.zkDir = zkDir;
- this.clientPort = port;
- }
-
- public String getZkHost() {
- return "127.0.0.1:" + zkServer.getLocalPort();
- }
-
- public String getZkAddress() {
- return "127.0.0.1:" + zkServer.getLocalPort() + "/solr";
- }
-
- public int getPort() {
- return zkServer.getLocalPort();
- }
-
- public void expire(final long sessionId) {
- zkServer.zooKeeperServer.expire(new Session() {
- @Override
- public long getSessionId() {
- return sessionId;
- }
- @Override
- public int getTimeout() {
- return 4000;
- }});
- }
-
- public void run() throws InterruptedException {
- // we don't call super.setUp
- zooThread = new Thread() {
-
- @Override
- public void run() {
- ServerConfig config = new ServerConfig() {
-
- {
- setClientPort(ZkTestServer.this.clientPort);
- this.dataDir = zkDir;
- this.dataLogDir = zkDir;
- this.tickTime = 1500;
- }
-
- public void setClientPort(int clientPort) {
- if (clientPortAddress != null) {
- try {
- this.clientPortAddress = new InetSocketAddress(
- InetAddress.getByName(clientPortAddress.getHostName()), clientPort);
- } catch (UnknownHostException e) {
- throw new RuntimeException(e);
- }
- } else {
- this.clientPortAddress = new InetSocketAddress(clientPort);
- }
- }
- };
-
- try {
- zkServer.runFromConfig(config);
- } catch (Throwable e) {
- throw new RuntimeException(e);
- }
- }
- };
-
- zooThread.setDaemon(true);
- zooThread.start();
-
- int cnt = 0;
- int port = -1;
- try {
- port = getPort();
- } catch(IllegalStateException e) {
-
- }
- while (port < 1) {
- Thread.sleep(100);
- try {
- port = getPort();
- } catch(IllegalStateException e) {
-
- }
- if (cnt == 40) {
- throw new RuntimeException("Could not get the port for ZooKeeper server");
- }
- cnt++;
- }
- }
-
- @SuppressWarnings("deprecation")
- public void shutdown() throws IOException {
- SolrTestCaseJ4.ignoreException("java.nio.channels.ClosedChannelException");
- // TODO: this can log an exception while trying to unregister a JMX MBean
- try {
- zkServer.shutdown();
- } finally {
- SolrTestCaseJ4.resetExceptionIgnores();
- }
- }
-
-
- public static boolean waitForServerDown(String hp, long timeout) {
- long start = System.currentTimeMillis();
- while (true) {
- try {
- HostPort hpobj = parseHostPortList(hp).get(0);
- send4LetterWord(hpobj.host, hpobj.port, "stat");
- } catch (IOException e) {
- return true;
- }
-
- if (System.currentTimeMillis() > start + timeout) {
- break;
- }
- try {
- Thread.sleep(250);
- } catch (InterruptedException e) {
- // ignore
- }
- }
- return false;
- }
-
- public static class HostPort {
- String host;
- int port;
-
- HostPort(String host, int port) {
- this.host = host;
- this.port = port;
- }
- }
-
- /**
- * Send the 4letterword
- * @param host the destination host
- * @param port the destination port
- * @param cmd the 4letterword
- * @return
- * @throws IOException
- */
- public static String send4LetterWord(String host, int port, String cmd)
- throws IOException
- {
-
- Socket sock = new Socket(host, port);
- BufferedReader reader = null;
- try {
- OutputStream outstream = sock.getOutputStream();
- outstream.write(cmd.getBytes());
- outstream.flush();
- // this replicates NC - close the output stream before reading
- sock.shutdownOutput();
-
- reader =
- new BufferedReader(
- new InputStreamReader(sock.getInputStream()));
- StringBuilder sb = new StringBuilder();
- String line;
- while((line = reader.readLine()) != null) {
- sb.append(line + "\n");
- }
- return sb.toString();
- } finally {
- sock.close();
- if (reader != null) {
- reader.close();
- }
- }
- }
-
- public static List<HostPort> parseHostPortList(String hplist) {
- ArrayList<HostPort> alist = new ArrayList<HostPort>();
- for (String hp : hplist.split(",")) {
- int idx = hp.lastIndexOf(':');
- String host = hp.substring(0, idx);
- int port;
- try {
- port = Integer.parseInt(hp.substring(idx + 1));
- } catch (RuntimeException e) {
- throw new RuntimeException("Problem parsing " + hp + e.toString());
- }
- alist.add(new HostPort(host, port));
- }
- return alist;
- }
-}
+package org.apache.solr.cloud;
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with this
+ * work for additional information regarding copyright ownership. The ASF
+ * licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.management.JMException;
+
+import org.apache.solr.SolrTestCaseJ4;
+import org.apache.zookeeper.jmx.ManagedUtil;
+import org.apache.zookeeper.server.NIOServerCnxn;
+import org.apache.zookeeper.server.ServerConfig;
+import org.apache.zookeeper.server.ZooKeeperServer;
+import org.apache.zookeeper.server.SessionTracker.Session;
+import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
+import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
+
+public class ZkTestServer {
+
+ protected final ZKServerMain zkServer = new ZKServerMain();
+
+ private String zkDir;
+
+ private int clientPort;
+
+ private Thread zooThread;
+
+ class ZKServerMain {
+
+ private NIOServerCnxn.Factory cnxnFactory;
+ private ZooKeeperServer zooKeeperServer;
+
+ protected void initializeAndRun(String[] args) throws ConfigException,
+ IOException {
+ try {
+ ManagedUtil.registerLog4jMBeans();
+ } catch (JMException e) {
+
+ }
+
+ ServerConfig config = new ServerConfig();
+ if (args.length == 1) {
+ config.parse(args[0]);
+ } else {
+ config.parse(args);
+ }
+
+ runFromConfig(config);
+ }
+
+ /**
+ * Run from a ServerConfig.
+ *
+ * @param config ServerConfig to use.
+ * @throws IOException
+ */
+ public void runFromConfig(ServerConfig config) throws IOException {
+ try {
+ // Note that this thread isn't going to be doing anything else,
+ // so rather than spawning another thread, we will just call
+ // run() in this thread.
+ // create a file logger url from the command line args
+ zooKeeperServer = new ZooKeeperServer();
+
+ FileTxnSnapLog ftxn = new FileTxnSnapLog(new File(config
+ .getDataLogDir()), new File(config.getDataDir()));
+ zooKeeperServer.setTxnLogFactory(ftxn);
+ zooKeeperServer.setTickTime(config.getTickTime());
+ cnxnFactory = new NIOServerCnxn.Factory(config.getClientPortAddress(), config
+ .getMaxClientCnxns());
+ cnxnFactory.startup(zooKeeperServer);
+ cnxnFactory.join();
+ if (zooKeeperServer.isRunning()) {
+ zooKeeperServer.shutdown();
+ }
+ } catch (InterruptedException e) {
+ }
+ }
+
+ /**
+ * Shutdown the serving instance
+ * @throws IOException
+ */
+ protected void shutdown() throws IOException {
+ zooKeeperServer.shutdown();
+ zooKeeperServer.getZKDatabase().close();
+ waitForServerDown(getZkHost() + ":" + getPort(), 5000);
+ cnxnFactory.shutdown();
+ }
+
+ public int getLocalPort() {
+ if (cnxnFactory == null) {
+ throw new IllegalStateException("A port has not yet been selected");
+ }
+ int port = cnxnFactory.getLocalPort();
+ if (port == 0) {
+ throw new IllegalStateException("A port has not yet been selected");
+ }
+ return port;
+ }
+ }
+
+ public ZkTestServer(String zkDir) {
+ this.zkDir = zkDir;
+ }
+
+ public ZkTestServer(String zkDir, int port) {
+ this.zkDir = zkDir;
+ this.clientPort = port;
+ }
+
+ public String getZkHost() {
+ return "127.0.0.1:" + zkServer.getLocalPort();
+ }
+
+ public String getZkAddress() {
+ return "127.0.0.1:" + zkServer.getLocalPort() + "/solr";
+ }
+
+ public int getPort() {
+ return zkServer.getLocalPort();
+ }
+
+ public void expire(final long sessionId) {
+ zkServer.zooKeeperServer.expire(new Session() {
+ @Override
+ public long getSessionId() {
+ return sessionId;
+ }
+ @Override
+ public int getTimeout() {
+ return 4000;
+ }});
+ }
+
+ public void run() throws InterruptedException {
+ // we don't call super.setUp
+ zooThread = new Thread() {
+
+ @Override
+ public void run() {
+ ServerConfig config = new ServerConfig() {
+
+ {
+ setClientPort(ZkTestServer.this.clientPort);
+ this.dataDir = zkDir;
+ this.dataLogDir = zkDir;
+ this.tickTime = 1500;
+ }
+
+ public void setClientPort(int clientPort) {
+ if (clientPortAddress != null) {
+ try {
+ this.clientPortAddress = new InetSocketAddress(
+ InetAddress.getByName(clientPortAddress.getHostName()), clientPort);
+ } catch (UnknownHostException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ this.clientPortAddress = new InetSocketAddress(clientPort);
+ }
+ }
+ };
+
+ try {
+ zkServer.runFromConfig(config);
+ } catch (Throwable e) {
+ throw new RuntimeException(e);
+ }
+ }
+ };
+
+ zooThread.setDaemon(true);
+ zooThread.start();
+
+ int cnt = 0;
+ int port = -1;
+ try {
+ port = getPort();
+ } catch(IllegalStateException e) {
+
+ }
+ while (port < 1) {
+ Thread.sleep(100);
+ try {
+ port = getPort();
+ } catch(IllegalStateException e) {
+
+ }
+ if (cnt == 40) {
+ throw new RuntimeException("Could not get the port for ZooKeeper server");
+ }
+ cnt++;
+ }
+ }
+
+ @SuppressWarnings("deprecation")
+ public void shutdown() throws IOException {
+ SolrTestCaseJ4.ignoreException("java.nio.channels.ClosedChannelException");
+ // TODO: this can log an exception while trying to unregister a JMX MBean
+ try {
+ zkServer.shutdown();
+ } finally {
+ SolrTestCaseJ4.resetExceptionIgnores();
+ }
+ }
+
+
+ public static boolean waitForServerDown(String hp, long timeout) {
+ long start = System.currentTimeMillis();
+ while (true) {
+ try {
+ HostPort hpobj = parseHostPortList(hp).get(0);
+ send4LetterWord(hpobj.host, hpobj.port, "stat");
+ } catch (IOException e) {
+ return true;
+ }
+
+ if (System.currentTimeMillis() > start + timeout) {
+ break;
+ }
+ try {
+ Thread.sleep(250);
+ } catch (InterruptedException e) {
+ // ignore
+ }
+ }
+ return false;
+ }
+
+ public static class HostPort {
+ String host;
+ int port;
+
+ HostPort(String host, int port) {
+ this.host = host;
+ this.port = port;
+ }
+ }
+
+ /**
+ * Send the 4letterword
+ * @param host the destination host
+ * @param port the destination port
+ * @param cmd the 4letterword
+ * @return
+ * @throws IOException
+ */
+ public static String send4LetterWord(String host, int port, String cmd)
+ throws IOException
+ {
+
+ Socket sock = new Socket(host, port);
+ BufferedReader reader = null;
+ try {
+ OutputStream outstream = sock.getOutputStream();
+ outstream.write(cmd.getBytes());
+ outstream.flush();
+ // this replicates NC - close the output stream before reading
+ sock.shutdownOutput();
+
+ reader =
+ new BufferedReader(
+ new InputStreamReader(sock.getInputStream()));
+ StringBuilder sb = new StringBuilder();
+ String line;
+ while((line = reader.readLine()) != null) {
+ sb.append(line + "\n");
+ }
+ return sb.toString();
+ } finally {
+ sock.close();
+ if (reader != null) {
+ reader.close();
+ }
+ }
+ }
+
+ public static List<HostPort> parseHostPortList(String hplist) {
+ ArrayList<HostPort> alist = new ArrayList<HostPort>();
+ for (String hp : hplist.split(",")) {
+ int idx = hp.lastIndexOf(':');
+ String host = hp.substring(0, idx);
+ int port;
+ try {
+ port = Integer.parseInt(hp.substring(idx + 1));
+ } catch (RuntimeException e) {
+ throw new RuntimeException("Problem parsing " + hp + e.toString());
+ }
+ alist.add(new HostPort(host, port));
+ }
+ return alist;
+ }
+}