LUCENE-7145: consolidate polygon range checks, tests, box usage. make cannot -> must not consistent so we can test this stuff.

This commit is contained in:
Robert Muir 2016-03-28 14:12:49 -04:00
parent d8dd06f422
commit 70290d9c8e
48 changed files with 253 additions and 160 deletions

View File

@ -41,7 +41,7 @@ public class DictionaryCompoundWordTokenFilter extends CompoundWordTokenFilterBa
public DictionaryCompoundWordTokenFilter(TokenStream input, CharArraySet dictionary) { public DictionaryCompoundWordTokenFilter(TokenStream input, CharArraySet dictionary) {
super(input, dictionary); super(input, dictionary);
if (dictionary == null) { if (dictionary == null) {
throw new IllegalArgumentException("dictionary cannot be null"); throw new IllegalArgumentException("dictionary must not be null");
} }
} }
@ -65,7 +65,7 @@ public class DictionaryCompoundWordTokenFilter extends CompoundWordTokenFilterBa
int minWordSize, int minSubwordSize, int maxSubwordSize, boolean onlyLongestMatch) { int minWordSize, int minSubwordSize, int maxSubwordSize, boolean onlyLongestMatch) {
super(input, dictionary, minWordSize, minSubwordSize, maxSubwordSize, onlyLongestMatch); super(input, dictionary, minWordSize, minSubwordSize, maxSubwordSize, onlyLongestMatch);
if (dictionary == null) { if (dictionary == null) {
throw new IllegalArgumentException("dictionary cannot be null"); throw new IllegalArgumentException("dictionary must not be null");
} }
} }

View File

@ -41,7 +41,7 @@ public class NumericPayloadTokenFilter extends TokenFilter {
public NumericPayloadTokenFilter(TokenStream input, float payload, String typeMatch) { public NumericPayloadTokenFilter(TokenStream input, float payload, String typeMatch) {
super(input); super(input);
if (typeMatch == null) { if (typeMatch == null) {
throw new IllegalArgumentException("typeMatch cannot be null"); throw new IllegalArgumentException("typeMatch must not be null");
} }
//Need to encode the payload //Need to encode the payload
thePayload = new BytesRef(PayloadHelper.encodeFloat(payload)); thePayload = new BytesRef(PayloadHelper.encodeFloat(payload));

View File

@ -47,19 +47,19 @@ public final class BinaryPoint extends Field {
private static FieldType getType(byte[][] point) { private static FieldType getType(byte[][] point) {
if (point == null) { if (point == null) {
throw new IllegalArgumentException("point cannot be null"); throw new IllegalArgumentException("point must not be null");
} }
if (point.length == 0) { if (point.length == 0) {
throw new IllegalArgumentException("point cannot be 0 dimensions"); throw new IllegalArgumentException("point must not be 0 dimensions");
} }
int bytesPerDim = -1; int bytesPerDim = -1;
for(int i=0;i<point.length;i++) { for(int i=0;i<point.length;i++) {
byte[] oneDim = point[i]; byte[] oneDim = point[i];
if (oneDim == null) { if (oneDim == null) {
throw new IllegalArgumentException("point cannot have null values"); throw new IllegalArgumentException("point must not have null values");
} }
if (oneDim.length == 0) { if (oneDim.length == 0) {
throw new IllegalArgumentException("point cannot have 0-length values"); throw new IllegalArgumentException("point must not have 0-length values");
} }
if (bytesPerDim == -1) { if (bytesPerDim == -1) {
bytesPerDim = oneDim.length; bytesPerDim = oneDim.length;
@ -79,10 +79,10 @@ public final class BinaryPoint extends Field {
private static BytesRef pack(byte[]... point) { private static BytesRef pack(byte[]... point) {
if (point == null) { if (point == null) {
throw new IllegalArgumentException("point cannot be null"); throw new IllegalArgumentException("point must not be null");
} }
if (point.length == 0) { if (point.length == 0) {
throw new IllegalArgumentException("point cannot be 0 dimensions"); throw new IllegalArgumentException("point must not be 0 dimensions");
} }
if (point.length == 1) { if (point.length == 1) {
return new BytesRef(point[0]); return new BytesRef(point[0]);
@ -90,11 +90,11 @@ public final class BinaryPoint extends Field {
int bytesPerDim = -1; int bytesPerDim = -1;
for(byte[] dim : point) { for(byte[] dim : point) {
if (dim == null) { if (dim == null) {
throw new IllegalArgumentException("point cannot have null values"); throw new IllegalArgumentException("point must not have null values");
} }
if (bytesPerDim == -1) { if (bytesPerDim == -1) {
if (dim.length == 0) { if (dim.length == 0) {
throw new IllegalArgumentException("point cannot have 0-length values"); throw new IllegalArgumentException("point must not have 0-length values");
} }
bytesPerDim = dim.length; bytesPerDim = dim.length;
} else if (dim.length != bytesPerDim) { } else if (dim.length != bytesPerDim) {

View File

@ -81,10 +81,10 @@ public final class DoublePoint extends Field {
private static BytesRef pack(double... point) { private static BytesRef pack(double... point) {
if (point == null) { if (point == null) {
throw new IllegalArgumentException("point cannot be null"); throw new IllegalArgumentException("point must not be null");
} }
if (point.length == 0) { if (point.length == 0) {
throw new IllegalArgumentException("point cannot be 0 dimensions"); throw new IllegalArgumentException("point must not be 0 dimensions");
} }
byte[] packed = new byte[point.length * Double.BYTES]; byte[] packed = new byte[point.length * Double.BYTES];

View File

@ -97,11 +97,11 @@ public class Field implements IndexableField {
*/ */
protected Field(String name, FieldType type) { protected Field(String name, FieldType type) {
if (name == null) { if (name == null) {
throw new IllegalArgumentException("name cannot be null"); throw new IllegalArgumentException("name must not be null");
} }
this.name = name; this.name = name;
if (type == null) { if (type == null) {
throw new IllegalArgumentException("type cannot be null"); throw new IllegalArgumentException("type must not be null");
} }
this.type = type; this.type = type;
} }
@ -118,13 +118,13 @@ public class Field implements IndexableField {
*/ */
public Field(String name, Reader reader, FieldType type) { public Field(String name, Reader reader, FieldType type) {
if (name == null) { if (name == null) {
throw new IllegalArgumentException("name cannot be null"); throw new IllegalArgumentException("name must not be null");
} }
if (type == null) { if (type == null) {
throw new IllegalArgumentException("type cannot be null"); throw new IllegalArgumentException("type must not be null");
} }
if (reader == null) { if (reader == null) {
throw new NullPointerException("reader cannot be null"); throw new NullPointerException("reader must not be null");
} }
if (type.stored()) { if (type.stored()) {
throw new IllegalArgumentException("fields with a Reader value cannot be stored"); throw new IllegalArgumentException("fields with a Reader value cannot be stored");
@ -150,10 +150,10 @@ public class Field implements IndexableField {
*/ */
public Field(String name, TokenStream tokenStream, FieldType type) { public Field(String name, TokenStream tokenStream, FieldType type) {
if (name == null) { if (name == null) {
throw new IllegalArgumentException("name cannot be null"); throw new IllegalArgumentException("name must not be null");
} }
if (tokenStream == null) { if (tokenStream == null) {
throw new NullPointerException("tokenStream cannot be null"); throw new NullPointerException("tokenStream must not be null");
} }
if (type.indexOptions() == IndexOptions.NONE || !type.tokenized()) { if (type.indexOptions() == IndexOptions.NONE || !type.tokenized()) {
throw new IllegalArgumentException("TokenStream fields must be indexed and tokenized"); throw new IllegalArgumentException("TokenStream fields must be indexed and tokenized");
@ -216,10 +216,10 @@ public class Field implements IndexableField {
*/ */
public Field(String name, BytesRef bytes, FieldType type) { public Field(String name, BytesRef bytes, FieldType type) {
if (name == null) { if (name == null) {
throw new IllegalArgumentException("name cannot be null"); throw new IllegalArgumentException("name must not be null");
} }
if (bytes == null) { if (bytes == null) {
throw new IllegalArgumentException("bytes cannot be null"); throw new IllegalArgumentException("bytes must not be null");
} }
this.fieldsData = bytes; this.fieldsData = bytes;
this.type = type; this.type = type;
@ -240,10 +240,10 @@ public class Field implements IndexableField {
*/ */
public Field(String name, String value, FieldType type) { public Field(String name, String value, FieldType type) {
if (name == null) { if (name == null) {
throw new IllegalArgumentException("name cannot be null"); throw new IllegalArgumentException("name must not be null");
} }
if (value == null) { if (value == null) {
throw new IllegalArgumentException("value cannot be null"); throw new IllegalArgumentException("value must not be null");
} }
if (!type.stored() && type.indexOptions() == IndexOptions.NONE) { if (!type.stored() && type.indexOptions() == IndexOptions.NONE) {
throw new IllegalArgumentException("it doesn't make sense to have a field that " throw new IllegalArgumentException("it doesn't make sense to have a field that "
@ -307,7 +307,7 @@ public class Field implements IndexableField {
throw new IllegalArgumentException("cannot change value type from " + fieldsData.getClass().getSimpleName() + " to String"); throw new IllegalArgumentException("cannot change value type from " + fieldsData.getClass().getSimpleName() + " to String");
} }
if (value == null) { if (value == null) {
throw new IllegalArgumentException("value cannot be null"); throw new IllegalArgumentException("value must not be null");
} }
fieldsData = value; fieldsData = value;
} }
@ -346,7 +346,7 @@ public class Field implements IndexableField {
throw new IllegalArgumentException("cannot set a BytesRef value on an indexed field"); throw new IllegalArgumentException("cannot set a BytesRef value on an indexed field");
} }
if (value == null) { if (value == null) {
throw new IllegalArgumentException("value cannot be null"); throw new IllegalArgumentException("value must not be null");
} }
fieldsData = value; fieldsData = value;
} }

View File

@ -292,7 +292,7 @@ public class FieldType implements IndexableFieldType {
public void setIndexOptions(IndexOptions value) { public void setIndexOptions(IndexOptions value) {
checkIfFrozen(); checkIfFrozen();
if (value == null) { if (value == null) {
throw new NullPointerException("IndexOptions cannot be null"); throw new NullPointerException("IndexOptions must not be null");
} }
this.indexOptions = value; this.indexOptions = value;
} }
@ -482,7 +482,7 @@ public class FieldType implements IndexableFieldType {
public void setDocValuesType(DocValuesType type) { public void setDocValuesType(DocValuesType type) {
checkIfFrozen(); checkIfFrozen();
if (type == null) { if (type == null) {
throw new NullPointerException("DocValuesType cannot be null"); throw new NullPointerException("DocValuesType must not be null");
} }
docValuesType = type; docValuesType = type;
} }

View File

@ -81,10 +81,10 @@ public final class FloatPoint extends Field {
private static BytesRef pack(float... point) { private static BytesRef pack(float... point) {
if (point == null) { if (point == null) {
throw new IllegalArgumentException("point cannot be null"); throw new IllegalArgumentException("point must not be null");
} }
if (point.length == 0) { if (point.length == 0) {
throw new IllegalArgumentException("point cannot be 0 dimensions"); throw new IllegalArgumentException("point must not be 0 dimensions");
} }
byte[] packed = new byte[point.length * Float.BYTES]; byte[] packed = new byte[point.length * Float.BYTES];

View File

@ -81,10 +81,10 @@ public final class IntPoint extends Field {
private static BytesRef pack(int... point) { private static BytesRef pack(int... point) {
if (point == null) { if (point == null) {
throw new IllegalArgumentException("point cannot be null"); throw new IllegalArgumentException("point must not be null");
} }
if (point.length == 0) { if (point.length == 0) {
throw new IllegalArgumentException("point cannot be 0 dimensions"); throw new IllegalArgumentException("point must not be 0 dimensions");
} }
byte[] packed = new byte[point.length * Integer.BYTES]; byte[] packed = new byte[point.length * Integer.BYTES];

View File

@ -81,10 +81,10 @@ public final class LongPoint extends Field {
private static BytesRef pack(long... point) { private static BytesRef pack(long... point) {
if (point == null) { if (point == null) {
throw new IllegalArgumentException("point cannot be null"); throw new IllegalArgumentException("point must not be null");
} }
if (point.length == 0) { if (point.length == 0) {
throw new IllegalArgumentException("point cannot be 0 dimensions"); throw new IllegalArgumentException("point must not be 0 dimensions");
} }
byte[] packed = new byte[point.length * Long.BYTES]; byte[] packed = new byte[point.length * Long.BYTES];

View File

@ -440,7 +440,7 @@ final class DefaultIndexingChain extends DocConsumer {
DocValuesType dvType = fieldType.docValuesType(); DocValuesType dvType = fieldType.docValuesType();
if (dvType == null) { if (dvType == null) {
throw new NullPointerException("docValuesType cannot be null (field: \"" + fieldName + "\")"); throw new NullPointerException("docValuesType must not be null (field: \"" + fieldName + "\")");
} }
if (dvType != DocValuesType.NONE) { if (dvType != DocValuesType.NONE) {
if (fp == null) { if (fp == null) {

View File

@ -137,7 +137,7 @@ abstract class DocValuesFieldUpdates {
protected DocValuesFieldUpdates(String field, DocValuesType type) { protected DocValuesFieldUpdates(String field, DocValuesType type) {
this.field = field; this.field = field;
if (type == null) { if (type == null) {
throw new NullPointerException("DocValuesType cannot be null"); throw new NullPointerException("DocValuesType must not be null");
} }
this.type = type; this.type = type;
} }

View File

@ -63,8 +63,8 @@ public final class FieldInfo {
long dvGen, Map<String,String> attributes, int pointDimensionCount, int pointNumBytes) { long dvGen, Map<String,String> attributes, int pointDimensionCount, int pointNumBytes) {
this.name = Objects.requireNonNull(name); this.name = Objects.requireNonNull(name);
this.number = number; this.number = number;
this.docValuesType = Objects.requireNonNull(docValues, "DocValuesType cannot be null (field: \"" + name + "\")"); this.docValuesType = Objects.requireNonNull(docValues, "DocValuesType must not be null (field: \"" + name + "\")");
this.indexOptions = Objects.requireNonNull(indexOptions, "IndexOptions cannot be null (field: \"" + name + "\")"); this.indexOptions = Objects.requireNonNull(indexOptions, "IndexOptions must not be null (field: \"" + name + "\")");
if (indexOptions != IndexOptions.NONE) { if (indexOptions != IndexOptions.NONE) {
this.storeTermVector = storeTermVector; this.storeTermVector = storeTermVector;
this.storePayloads = storePayloads; this.storePayloads = storePayloads;
@ -130,7 +130,7 @@ public final class FieldInfo {
void update(boolean storeTermVector, boolean omitNorms, boolean storePayloads, IndexOptions indexOptions, void update(boolean storeTermVector, boolean omitNorms, boolean storePayloads, IndexOptions indexOptions,
int dimensionCount, int dimensionNumBytes) { int dimensionCount, int dimensionNumBytes) {
if (indexOptions == null) { if (indexOptions == null) {
throw new NullPointerException("IndexOptions cannot be null (field: \"" + name + "\")"); throw new NullPointerException("IndexOptions must not be null (field: \"" + name + "\")");
} }
//System.out.println("FI.update field=" + name + " indexed=" + indexed + " omitNorms=" + omitNorms + " this.omitNorms=" + this.omitNorms); //System.out.println("FI.update field=" + name + " indexed=" + indexed + " omitNorms=" + omitNorms + " this.omitNorms=" + this.omitNorms);
if (this.indexOptions != indexOptions) { if (this.indexOptions != indexOptions) {
@ -201,7 +201,7 @@ public final class FieldInfo {
void setDocValuesType(DocValuesType type) { void setDocValuesType(DocValuesType type) {
if (type == null) { if (type == null) {
throw new NullPointerException("DocValuesType cannot be null (field: \"" + name + "\")"); throw new NullPointerException("DocValuesType must not be null (field: \"" + name + "\")");
} }
if (docValuesType != DocValuesType.NONE && type != DocValuesType.NONE && docValuesType != type) { if (docValuesType != DocValuesType.NONE && type != DocValuesType.NONE && docValuesType != type) {
throw new IllegalArgumentException("cannot change DocValues type from " + docValuesType + " to " + type + " for field \"" + name + "\""); throw new IllegalArgumentException("cannot change DocValues type from " + docValuesType + " to " + type + " for field \"" + name + "\"");

View File

@ -394,7 +394,7 @@ public class FieldInfos implements Iterable<FieldInfo> {
boolean omitNorms, boolean storePayloads, IndexOptions indexOptions, DocValuesType docValues, boolean omitNorms, boolean storePayloads, IndexOptions indexOptions, DocValuesType docValues,
int dimensionCount, int dimensionNumBytes) { int dimensionCount, int dimensionNumBytes) {
if (docValues == null) { if (docValues == null) {
throw new NullPointerException("DocValuesType cannot be null"); throw new NullPointerException("DocValuesType must not be null");
} }
FieldInfo fi = fieldInfo(name); FieldInfo fi = fieldInfo(name);
if (fi == null) { if (fi == null) {

View File

@ -67,7 +67,7 @@ public abstract class FilterLeafReader extends LeafReader {
*/ */
public FilterFields(Fields in) { public FilterFields(Fields in) {
if (in == null) { if (in == null) {
throw new NullPointerException("incoming Fields cannot be null"); throw new NullPointerException("incoming Fields must not be null");
} }
this.in = in; this.in = in;
} }
@ -103,7 +103,7 @@ public abstract class FilterLeafReader extends LeafReader {
*/ */
public FilterTerms(Terms in) { public FilterTerms(Terms in) {
if (in == null) { if (in == null) {
throw new NullPointerException("incoming Terms cannot be null"); throw new NullPointerException("incoming Terms must not be null");
} }
this.in = in; this.in = in;
} }
@ -170,7 +170,7 @@ public abstract class FilterLeafReader extends LeafReader {
*/ */
public FilterTermsEnum(TermsEnum in) { public FilterTermsEnum(TermsEnum in) {
if (in == null) { if (in == null) {
throw new NullPointerException("incoming TermsEnum cannot be null"); throw new NullPointerException("incoming TermsEnum must not be null");
} }
this.in = in; this.in = in;
} }
@ -233,7 +233,7 @@ public abstract class FilterLeafReader extends LeafReader {
*/ */
public FilterPostingsEnum(PostingsEnum in) { public FilterPostingsEnum(PostingsEnum in) {
if (in == null) { if (in == null) {
throw new NullPointerException("incoming PostingsEnum cannot be null"); throw new NullPointerException("incoming PostingsEnum must not be null");
} }
this.in = in; this.in = in;
} }
@ -300,7 +300,7 @@ public abstract class FilterLeafReader extends LeafReader {
public FilterLeafReader(LeafReader in) { public FilterLeafReader(LeafReader in) {
super(); super();
if (in == null) { if (in == null) {
throw new NullPointerException("incoming LeafReader cannot be null"); throw new NullPointerException("incoming LeafReader must not be null");
} }
this.in = in; this.in = in;
in.registerParentReader(this); in.registerParentReader(this);

View File

@ -1592,7 +1592,7 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
final Field f = updates[i]; final Field f = updates[i];
final DocValuesType dvType = f.fieldType().docValuesType(); final DocValuesType dvType = f.fieldType().docValuesType();
if (dvType == null) { if (dvType == null) {
throw new NullPointerException("DocValuesType cannot be null (field: \"" + f.name() + "\")"); throw new NullPointerException("DocValuesType must not be null (field: \"" + f.name() + "\")");
} }
if (dvType == DocValuesType.NONE) { if (dvType == DocValuesType.NONE) {
throw new IllegalArgumentException("can only update NUMERIC or BINARY fields! field=" + f.name()); throw new IllegalArgumentException("can only update NUMERIC or BINARY fields! field=" + f.name());

View File

@ -160,7 +160,7 @@ public final class IndexWriterConfig extends LiveIndexWriterConfig {
* like NFS that do not support "delete on last close" semantics, which * like NFS that do not support "delete on last close" semantics, which
* Lucene's "point in time" search normally relies on. * Lucene's "point in time" search normally relies on.
* <p> * <p>
* <b>NOTE:</b> the deletion policy cannot be null. * <b>NOTE:</b> the deletion policy must not be null.
* *
* <p>Only takes effect when IndexWriter is first created. * <p>Only takes effect when IndexWriter is first created.
*/ */
@ -197,7 +197,7 @@ public final class IndexWriterConfig extends LiveIndexWriterConfig {
/** /**
* Expert: set the {@link Similarity} implementation used by this IndexWriter. * Expert: set the {@link Similarity} implementation used by this IndexWriter.
* <p> * <p>
* <b>NOTE:</b> the similarity cannot be null. * <b>NOTE:</b> the similarity must not be null.
* *
* <p>Only takes effect when IndexWriter is first created. */ * <p>Only takes effect when IndexWriter is first created. */
public IndexWriterConfig setSimilarity(Similarity similarity) { public IndexWriterConfig setSimilarity(Similarity similarity) {
@ -217,7 +217,7 @@ public final class IndexWriterConfig extends LiveIndexWriterConfig {
* Expert: sets the merge scheduler used by this writer. The default is * Expert: sets the merge scheduler used by this writer. The default is
* {@link ConcurrentMergeScheduler}. * {@link ConcurrentMergeScheduler}.
* <p> * <p>
* <b>NOTE:</b> the merge scheduler cannot be null. * <b>NOTE:</b> the merge scheduler must not be null.
* *
* <p>Only takes effect when IndexWriter is first created. */ * <p>Only takes effect when IndexWriter is first created. */
public IndexWriterConfig setMergeScheduler(MergeScheduler mergeScheduler) { public IndexWriterConfig setMergeScheduler(MergeScheduler mergeScheduler) {

View File

@ -48,7 +48,7 @@ class PointValuesWriter {
// TODO: if exactly the same value is added to exactly the same doc, should we dedup? // TODO: if exactly the same value is added to exactly the same doc, should we dedup?
public void addPackedValue(int docID, BytesRef value) { public void addPackedValue(int docID, BytesRef value) {
if (value == null) { if (value == null) {
throw new IllegalArgumentException("field=" + fieldInfo.name + ": point value cannot be null"); throw new IllegalArgumentException("field=" + fieldInfo.name + ": point value must not be null");
} }
if (value.length != fieldInfo.getPointDimensionCount() * fieldInfo.getPointNumBytes()) { if (value.length != fieldInfo.getPointDimensionCount() * fieldInfo.getPointNumBytes()) {
throw new IllegalArgumentException("field=" + fieldInfo.name + ": this field's value has length=" + value.length + " but should be " + (fieldInfo.getPointDimensionCount() * fieldInfo.getPointNumBytes())); throw new IllegalArgumentException("field=" + fieldInfo.name + ": this field's value has length=" + value.length + " but should be " + (fieldInfo.getPointDimensionCount() * fieldInfo.getPointNumBytes()));

View File

@ -35,7 +35,7 @@ public class PrefixQuery extends AutomatonQuery {
// It's OK to pass unlimited maxDeterminizedStates: the automaton is born small and determinized: // It's OK to pass unlimited maxDeterminizedStates: the automaton is born small and determinized:
super(prefix, toAutomaton(prefix.bytes()), Integer.MAX_VALUE, true); super(prefix, toAutomaton(prefix.bytes()), Integer.MAX_VALUE, true);
if (prefix == null) { if (prefix == null) {
throw new NullPointerException("prefix cannot be null"); throw new NullPointerException("prefix must not be null");
} }
} }

View File

@ -291,7 +291,7 @@ public abstract class ReferenceManager<G> implements Closeable {
*/ */
public void addListener(RefreshListener listener) { public void addListener(RefreshListener listener) {
if (listener == null) { if (listener == null) {
throw new NullPointerException("Listener cannot be null"); throw new NullPointerException("Listener must not be null");
} }
refreshListeners.add(listener); refreshListeners.add(listener);
} }
@ -301,7 +301,7 @@ public abstract class ReferenceManager<G> implements Closeable {
*/ */
public void removeListener(RefreshListener listener) { public void removeListener(RefreshListener listener) {
if (listener == null) { if (listener == null) {
throw new NullPointerException("Listener cannot be null"); throw new NullPointerException("Listener must not be null");
} }
refreshListeners.remove(listener); refreshListeners.remove(listener);
} }

View File

@ -35,7 +35,7 @@ public abstract class BaseDirectory extends Directory {
protected BaseDirectory(LockFactory lockFactory) { protected BaseDirectory(LockFactory lockFactory) {
super(); super();
if (lockFactory == null) { if (lockFactory == null) {
throw new NullPointerException("LockFactory cannot be null, use an explicit instance!"); throw new NullPointerException("LockFactory must not be null, use an explicit instance!");
} }
this.lockFactory = lockFactory; this.lockFactory = lockFactory;
} }

View File

@ -96,7 +96,7 @@ public final class CommandLineUtil {
private static String adjustDirectoryClassName(String clazzName) { private static String adjustDirectoryClassName(String clazzName) {
if (clazzName == null || clazzName.trim().length() == 0) { if (clazzName == null || clazzName.trim().length() == 0) {
throw new IllegalArgumentException("The " + FSDirectory.class.getSimpleName() throw new IllegalArgumentException("The " + FSDirectory.class.getSimpleName()
+ " implementation cannot be null or empty"); + " implementation must not be null or empty");
} }
if (clazzName.indexOf(".") == -1) {// if not fully qualified, assume .store if (clazzName.indexOf(".") == -1) {// if not fully qualified, assume .store

View File

@ -449,7 +449,7 @@ public final class UnicodeUtil {
* content is prematurely truncated. * content is prematurely truncated.
*/ */
public static int UTF8toUTF32(final BytesRef utf8, final int[] ints) { public static int UTF8toUTF32(final BytesRef utf8, final int[] ints) {
// TODO: ints cannot be null, should be an assert // TODO: ints must not be null, should be an assert
int utf32Count = 0; int utf32Count = 0;
int utf8Upto = utf8.offset; int utf8Upto = utf8.offset;
final byte[] bytes = utf8.bytes; final byte[] bytes = utf8.bytes;

View File

@ -31,7 +31,7 @@ public abstract class Range {
/** Sole constructor. */ /** Sole constructor. */
protected Range(String label) { protected Range(String label) {
if (label == null) { if (label == null) {
throw new NullPointerException("label cannot be null"); throw new NullPointerException("label must not be null");
} }
this.label = label; this.label = label;
} }

View File

@ -178,7 +178,7 @@ public class DirectoryTaxonomyReader extends TaxonomyReader {
recreated = true; recreated = true;
} }
} else if (!t1.equals(t2)) { } else if (!t1.equals(t2)) {
// t1 != null and t2 cannot be null b/c DirTaxoWriter always puts the commit data. // t1 != null and t2 must not be null b/c DirTaxoWriter always puts the commit data.
// it's ok to use String.equals because we require the two epoch values to be the same. // it's ok to use String.equals because we require the two epoch values to be the same.
recreated = true; recreated = true;
} }

View File

@ -465,7 +465,7 @@ public class PostingsHighlighter {
PassageFormatter fieldFormatter = getFormatter(field); PassageFormatter fieldFormatter = getFormatter(field);
if (fieldFormatter == null) { if (fieldFormatter == null) {
throw new NullPointerException("PassageFormatter cannot be null"); throw new NullPointerException("PassageFormatter must not be null");
} }
// check if we should do any multiterm processing // check if we should do any multiterm processing
@ -550,7 +550,7 @@ public class PostingsHighlighter {
TermsEnum termsEnum, PostingsEnum[] postings, int n) throws IOException { TermsEnum termsEnum, PostingsEnum[] postings, int n) throws IOException {
PassageScorer scorer = getScorer(field); PassageScorer scorer = getScorer(field);
if (scorer == null) { if (scorer == null) {
throw new NullPointerException("PassageScorer cannot be null"); throw new NullPointerException("PassageScorer must not be null");
} }
PriorityQueue<OffsetsEnum> pq = new PriorityQueue<>(); PriorityQueue<OffsetsEnum> pq = new PriorityQueue<>();
float weights[] = new float[terms.length]; float weights[] = new float[terms.length];

View File

@ -67,7 +67,7 @@ JNIEXPORT jlong JNICALL Java_org_apache_lucene_store_WindowsDirectory_open
HANDLE handle; HANDLE handle;
if (filename == NULL) { if (filename == NULL) {
throwException(env, "java/lang/NullPointerException", "filename cannot be null"); throwException(env, "java/lang/NullPointerException", "filename must not be null");
return -1; return -1;
} }
@ -109,7 +109,7 @@ JNIEXPORT jint JNICALL Java_org_apache_lucene_store_WindowsDirectory_read
io.OffsetHigh = (DWORD) ((pos >> 0x20) & 0x7FFFFFFF); io.OffsetHigh = (DWORD) ((pos >> 0x20) & 0x7FFFFFFF);
if (bytes == NULL) { if (bytes == NULL) {
throwException(env, "java/lang/NullPointerException", "bytes cannot be null"); throwException(env, "java/lang/NullPointerException", "bytes must not be null");
return -1; return -1;
} }

View File

@ -342,7 +342,7 @@ public abstract class QueryParserBase extends QueryBuilder implements CommonQuer
*/ */
public void setDateResolution(String fieldName, DateTools.Resolution dateResolution) { public void setDateResolution(String fieldName, DateTools.Resolution dateResolution) {
if (fieldName == null) { if (fieldName == null) {
throw new IllegalArgumentException("Field cannot be null."); throw new IllegalArgumentException("Field must not be null.");
} }
if (fieldToDateResolution == null) { if (fieldToDateResolution == null) {
@ -361,7 +361,7 @@ public abstract class QueryParserBase extends QueryBuilder implements CommonQuer
*/ */
public DateTools.Resolution getDateResolution(String fieldName) { public DateTools.Resolution getDateResolution(String fieldName) {
if (fieldName == null) { if (fieldName == null) {
throw new IllegalArgumentException("Field cannot be null."); throw new IllegalArgumentException("Field must not be null.");
} }
if (fieldToDateResolution == null) { if (fieldToDateResolution == null) {

View File

@ -51,7 +51,7 @@ public abstract class AbstractQueryConfig {
public <T> T get(ConfigurationKey<T> key) { public <T> T get(ConfigurationKey<T> key) {
if (key == null) { if (key == null) {
throw new IllegalArgumentException("key cannot be null!"); throw new IllegalArgumentException("key must not be null!");
} }
return (T) this.configMap.get(key); return (T) this.configMap.get(key);
@ -68,7 +68,7 @@ public abstract class AbstractQueryConfig {
public <T> boolean has(ConfigurationKey<T> key) { public <T> boolean has(ConfigurationKey<T> key) {
if (key == null) { if (key == null) {
throw new IllegalArgumentException("key cannot be null!"); throw new IllegalArgumentException("key must not be null!");
} }
return this.configMap.containsKey(key); return this.configMap.containsKey(key);
@ -85,7 +85,7 @@ public abstract class AbstractQueryConfig {
public <T> void set(ConfigurationKey<T> key, T value) { public <T> void set(ConfigurationKey<T> key, T value) {
if (key == null) { if (key == null) {
throw new IllegalArgumentException("key cannot be null!"); throw new IllegalArgumentException("key must not be null!");
} }
if (value == null) { if (value == null) {
@ -107,7 +107,7 @@ public abstract class AbstractQueryConfig {
public <T> boolean unset(ConfigurationKey<T> key) { public <T> boolean unset(ConfigurationKey<T> key) {
if (key == null) { if (key == null) {
throw new IllegalArgumentException("key cannot be null!"); throw new IllegalArgumentException("key must not be null!");
} }
return this.configMap.remove(key) != null; return this.configMap.remove(key) != null;

View File

@ -26,13 +26,13 @@ public class FieldConfig extends AbstractQueryConfig {
/** /**
* Constructs a {@link FieldConfig} * Constructs a {@link FieldConfig}
* *
* @param fieldName the field name, it cannot be null * @param fieldName the field name, it must not be null
* @throws IllegalArgumentException if the field name is null * @throws IllegalArgumentException if the field name is null
*/ */
public FieldConfig(String fieldName) { public FieldConfig(String fieldName) {
if (fieldName == null) { if (fieldName == null) {
throw new IllegalArgumentException("field name should not be null!"); throw new IllegalArgumentException("field name must not be null!");
} }
this.fieldName = fieldName; this.fieldName = fieldName;

View File

@ -113,7 +113,7 @@ public class LegacyNumericConfig {
public void setType(LegacyNumericType type) { public void setType(LegacyNumericType type) {
if (type == null) { if (type == null) {
throw new IllegalArgumentException("type cannot be null!"); throw new IllegalArgumentException("type must not be null!");
} }
this.type = type; this.type = type;
@ -126,12 +126,12 @@ public class LegacyNumericConfig {
* *
* @param format * @param format
* the {@link NumberFormat} used to parse a {@link String} to * the {@link NumberFormat} used to parse a {@link String} to
* {@link Number}, cannot be <code>null</code> * {@link Number}, must not be <code>null</code>
*/ */
public void setNumberFormat(NumberFormat format) { public void setNumberFormat(NumberFormat format) {
if (format == null) { if (format == null) {
throw new IllegalArgumentException("format cannot be null!"); throw new IllegalArgumentException("format must not be null!");
} }
this.format = format; this.format = format;

View File

@ -48,7 +48,7 @@ public class LegacyNumericFieldConfigListener implements FieldConfigListener {
public LegacyNumericFieldConfigListener(QueryConfigHandler config) { public LegacyNumericFieldConfigListener(QueryConfigHandler config) {
if (config == null) { if (config == null) {
throw new IllegalArgumentException("config cannot be null!"); throw new IllegalArgumentException("config must not be null!");
} }
this.config = config; this.config = config;

View File

@ -76,7 +76,7 @@ public class PointsConfig {
*/ */
public void setType(Class<? extends Number> type) { public void setType(Class<? extends Number> type) {
if (type == null) { if (type == null) {
throw new IllegalArgumentException("type cannot be null!"); throw new IllegalArgumentException("type must not be null!");
} }
if (Integer.class.equals(type) == false && if (Integer.class.equals(type) == false &&
Long.class.equals(type) == false && Long.class.equals(type) == false &&
@ -93,11 +93,11 @@ public class PointsConfig {
* *
* @param format * @param format
* the {@link NumberFormat} used to parse a {@link String} to * the {@link NumberFormat} used to parse a {@link String} to
* {@link Number}, cannot be <code>null</code> * {@link Number}, must not be <code>null</code>
*/ */
public void setNumberFormat(NumberFormat format) { public void setNumberFormat(NumberFormat format) {
if (format == null) { if (format == null) {
throw new IllegalArgumentException("format cannot be null!"); throw new IllegalArgumentException("format must not be null!");
} }
this.format = format; this.format = format;
} }

View File

@ -45,7 +45,7 @@ public class PointsConfigListener implements FieldConfigListener {
*/ */
public PointsConfigListener(QueryConfigHandler config) { public PointsConfigListener(QueryConfigHandler config) {
if (config == null) { if (config == null) {
throw new IllegalArgumentException("config cannot be null!"); throw new IllegalArgumentException("config must not be null!");
} }
this.config = config; this.config = config;
} }

View File

@ -88,7 +88,7 @@ public class LegacyNumericRangeQueryNode extends
boolean lowerInclusive, boolean upperInclusive, LegacyNumericConfig numericConfig) throws QueryNodeException { boolean lowerInclusive, boolean upperInclusive, LegacyNumericConfig numericConfig) throws QueryNodeException {
if (numericConfig == null) { if (numericConfig == null) {
throw new IllegalArgumentException("numericConfig cannot be null!"); throw new IllegalArgumentException("numericConfig must not be null!");
} }
LegacyNumericType lowerNumberType, upperNumberType; LegacyNumericType lowerNumberType, upperNumberType;

View File

@ -62,7 +62,7 @@ public class PointRangeQueryNode extends AbstractRangeQueryNode<PointQueryNode>
boolean lowerInclusive, boolean upperInclusive, PointsConfig pointsConfig) throws QueryNodeException { boolean lowerInclusive, boolean upperInclusive, PointsConfig pointsConfig) throws QueryNodeException {
if (pointsConfig == null) { if (pointsConfig == null) {
throw new IllegalArgumentException("pointsConfig cannot be null!"); throw new IllegalArgumentException("pointsConfig must not be null!");
} }
Class<? extends Number> lowerNumberType, upperNumberType; Class<? extends Number> lowerNumberType, upperNumberType;

View File

@ -34,7 +34,7 @@ public class RevisionFile {
/** Constructor with the given file name. */ /** Constructor with the given file name. */
public RevisionFile(String fileName) { public RevisionFile(String fileName) {
if (fileName == null || fileName.isEmpty()) { if (fileName == null || fileName.isEmpty()) {
throw new IllegalArgumentException("fileName cannot be null or empty"); throw new IllegalArgumentException("fileName must not be null or empty");
} }
this.fileName = fileName; this.fileName = fileName;
} }

View File

@ -85,10 +85,10 @@ public class BigIntegerPoint extends Field {
private static BytesRef pack(BigInteger... point) { private static BytesRef pack(BigInteger... point) {
if (point == null) { if (point == null) {
throw new IllegalArgumentException("point cannot be null"); throw new IllegalArgumentException("point must not be null");
} }
if (point.length == 0) { if (point.length == 0) {
throw new IllegalArgumentException("point cannot be 0 dimensions"); throw new IllegalArgumentException("point must not be 0 dimensions");
} }
byte[] packed = new byte[point.length * BYTES]; byte[] packed = new byte[point.length * BYTES];

View File

@ -68,7 +68,7 @@ public class InetAddressPoint extends Field {
/** Change the values of this field */ /** Change the values of this field */
public void setInetAddressValue(InetAddress value) { public void setInetAddressValue(InetAddress value) {
if (value == null) { if (value == null) {
throw new IllegalArgumentException("point cannot be null"); throw new IllegalArgumentException("point must not be null");
} }
fieldsData = new BytesRef(encode(value)); fieldsData = new BytesRef(encode(value));
} }
@ -165,7 +165,7 @@ public class InetAddressPoint extends Field {
*/ */
public static Query newPrefixQuery(String field, InetAddress value, int prefixLength) { public static Query newPrefixQuery(String field, InetAddress value, int prefixLength) {
if (value == null) { if (value == null) {
throw new IllegalArgumentException("InetAddress cannot be null"); throw new IllegalArgumentException("InetAddress must not be null");
} }
if (prefixLength < 0 || prefixLength > 8 * value.getAddress().length) { if (prefixLength < 0 || prefixLength > 8 * value.getAddress().length) {
throw new IllegalArgumentException("illegal prefixLength '" + prefixLength + "'. Must be 0-32 for IPv4 ranges, 0-128 for IPv6 ranges"); throw new IllegalArgumentException("illegal prefixLength '" + prefixLength + "'. Must be 0-32 for IPv4 ranges, 0-128 for IPv6 ranges");

View File

@ -236,7 +236,7 @@ public class LatLonPoint extends Field {
* Create a query for matching a bounding box. * Create a query for matching a bounding box.
* <p> * <p>
* The box may cross over the dateline. * The box may cross over the dateline.
* @param field field name. cannot be null. * @param field field name. must not be null.
* @param minLatitude latitude lower bound: must be within standard +/-90 coordinate bounds. * @param minLatitude latitude lower bound: must be within standard +/-90 coordinate bounds.
* @param maxLatitude latitude upper bound: must be within standard +/-90 coordinate bounds. * @param maxLatitude latitude upper bound: must be within standard +/-90 coordinate bounds.
* @param minLongitude longitude lower bound: must be within standard +/-180 coordinate bounds. * @param minLongitude longitude lower bound: must be within standard +/-180 coordinate bounds.
@ -288,7 +288,7 @@ public class LatLonPoint extends Field {
/** /**
* Create a query for matching points within the specified distance of the supplied location. * Create a query for matching points within the specified distance of the supplied location.
* @param field field name. cannot be null. * @param field field name. must not be null.
* @param latitude latitude at the center: must be within standard +/-90 coordinate bounds. * @param latitude latitude at the center: must be within standard +/-90 coordinate bounds.
* @param longitude longitude at the center: must be within standard +/-180 coordinate bounds. * @param longitude longitude at the center: must be within standard +/-180 coordinate bounds.
* @param radiusMeters maximum distance from the center in meters: must be non-negative and finite. * @param radiusMeters maximum distance from the center in meters: must be non-negative and finite.
@ -303,7 +303,7 @@ public class LatLonPoint extends Field {
* Create a query for matching a polygon. * Create a query for matching a polygon.
* <p> * <p>
* The supplied {@code polyLats}/{@code polyLons} must be clockwise or counter-clockwise. * The supplied {@code polyLats}/{@code polyLons} must be clockwise or counter-clockwise.
* @param field field name. cannot be null. * @param field field name. must not be null.
* @param polyLats latitude values for points of the polygon: must be within standard +/-90 coordinate bounds. * @param polyLats latitude values for points of the polygon: must be within standard +/-90 coordinate bounds.
* @param polyLons longitude values for points of the polygon: must be within standard +/-180 coordinate bounds. * @param polyLons longitude values for points of the polygon: must be within standard +/-180 coordinate bounds.
* @return query matching points within this polygon * @return query matching points within this polygon
@ -327,7 +327,7 @@ public class LatLonPoint extends Field {
* <p> * <p>
* If a document contains multiple values for the field, the <i>closest</i> distance to the location is used. * If a document contains multiple values for the field, the <i>closest</i> distance to the location is used.
* *
* @param field field name. cannot be null. * @param field field name. must not be null.
* @param latitude latitude at the center: must be within standard +/-90 coordinate bounds. * @param latitude latitude at the center: must be within standard +/-90 coordinate bounds.
* @param longitude longitude at the center: must be within standard +/-180 coordinate bounds. * @param longitude longitude at the center: must be within standard +/-180 coordinate bounds.
* @return SortField ordering documents by distance * @return SortField ordering documents by distance

View File

@ -56,7 +56,7 @@ final class LatLonPointDistanceQuery extends Query {
public LatLonPointDistanceQuery(String field, double latitude, double longitude, double radiusMeters) { public LatLonPointDistanceQuery(String field, double latitude, double longitude, double radiusMeters) {
if (field == null) { if (field == null) {
throw new IllegalArgumentException("field cannot be null"); throw new IllegalArgumentException("field must not be null");
} }
if (Double.isFinite(radiusMeters) == false || radiusMeters < 0) { if (Double.isFinite(radiusMeters) == false || radiusMeters < 0) {
throw new IllegalArgumentException("radiusMeters: '" + radiusMeters + "' is invalid"); throw new IllegalArgumentException("radiusMeters: '" + radiusMeters + "' is invalid");

View File

@ -40,6 +40,7 @@ import org.apache.lucene.util.BitSet;
import org.apache.lucene.util.DocIdSetBuilder; import org.apache.lucene.util.DocIdSetBuilder;
import org.apache.lucene.util.FixedBitSet; import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.SparseFixedBitSet; import org.apache.lucene.util.SparseFixedBitSet;
import org.apache.lucene.spatial.util.GeoRect;
import org.apache.lucene.spatial.util.GeoRelationUtils; import org.apache.lucene.spatial.util.GeoRelationUtils;
import org.apache.lucene.spatial.util.GeoUtils; import org.apache.lucene.spatial.util.GeoUtils;
@ -60,52 +61,20 @@ final class LatLonPointInPolygonQuery extends Query {
/** The lats/lons must be clockwise or counter-clockwise. */ /** The lats/lons must be clockwise or counter-clockwise. */
public LatLonPointInPolygonQuery(String field, double[] polyLats, double[] polyLons) { public LatLonPointInPolygonQuery(String field, double[] polyLats, double[] polyLons) {
this.field = field;
if (field == null) { if (field == null) {
throw new IllegalArgumentException("field cannot be null"); throw new IllegalArgumentException("field must not be null");
} }
if (polyLats == null) { GeoUtils.checkPolygon(polyLats, polyLons);
throw new IllegalArgumentException("polyLats cannot be null"); this.field = field;
}
if (polyLons == null) {
throw new IllegalArgumentException("polyLons cannot be null");
}
if (polyLats.length != polyLons.length) {
throw new IllegalArgumentException("polyLats and polyLons must be equal length");
}
if (polyLats.length < 4) {
throw new IllegalArgumentException("at least 4 polygon points required");
}
if (polyLats[0] != polyLats[polyLats.length-1]) {
throw new IllegalArgumentException("first and last points of the polygon must be the same (it must close itself): polyLats[0]=" + polyLats[0] + " polyLats[" + (polyLats.length-1) + "]=" + polyLats[polyLats.length-1]);
}
if (polyLons[0] != polyLons[polyLons.length-1]) {
throw new IllegalArgumentException("first and last points of the polygon must be the same (it must close itself): polyLons[0]=" + polyLons[0] + " polyLons[" + (polyLons.length-1) + "]=" + polyLons[polyLons.length-1]);
}
this.polyLats = polyLats; this.polyLats = polyLats;
this.polyLons = polyLons; this.polyLons = polyLons;
// TODO: we could also compute the maximal inner bounding box, to make relations faster to compute? // TODO: we could also compute the maximal inner bounding box, to make relations faster to compute?
GeoRect box = GeoUtils.polyToBBox(polyLats, polyLons);
double minLon = Double.POSITIVE_INFINITY; this.minLon = box.minLon;
double minLat = Double.POSITIVE_INFINITY; this.maxLon = box.maxLon;
double maxLon = Double.NEGATIVE_INFINITY; this.minLat = box.minLat;
double maxLat = Double.NEGATIVE_INFINITY; this.maxLat = box.maxLat;
for(int i=0;i<polyLats.length;i++) {
double lat = polyLats[i];
GeoUtils.checkLatitude(lat);
minLat = Math.min(minLat, lat);
maxLat = Math.max(maxLat, lat);
double lon = polyLons[i];
GeoUtils.checkLongitude(lon);
minLon = Math.min(minLon, lon);
maxLon = Math.max(maxLon, lon);
}
this.minLon = minLon;
this.maxLon = maxLon;
this.minLat = minLat;
this.maxLat = maxLat;
} }
@Override @Override

View File

@ -32,7 +32,7 @@ final class LatLonPointSortField extends SortField {
LatLonPointSortField(String field, double latitude, double longitude) { LatLonPointSortField(String field, double latitude, double longitude) {
super(field, SortField.Type.CUSTOM); super(field, SortField.Type.CUSTOM);
if (field == null) { if (field == null) {
throw new IllegalArgumentException("field cannot be null"); throw new IllegalArgumentException("field must not be null");
} }
GeoUtils.checkLatitude(latitude); GeoUtils.checkLatitude(latitude);
GeoUtils.checkLongitude(longitude); GeoUtils.checkLongitude(longitude);

View File

@ -141,7 +141,7 @@ public final class DocValuesRangeQuery extends Query {
@Override @Override
public Weight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException { public Weight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
if (lowerVal == null && upperVal == null) { if (lowerVal == null && upperVal == null) {
throw new IllegalStateException("Both min and max values cannot be null, call rewrite first"); throw new IllegalStateException("Both min and max values must not be null, call rewrite first");
} }
return new RandomAccessWeight(DocValuesRangeQuery.this) { return new RandomAccessWeight(DocValuesRangeQuery.this) {

View File

@ -72,10 +72,10 @@ public class GeoPointInBBoxQuery extends Query {
*/ */
public GeoPointInBBoxQuery(final String field, final TermEncoding termEncoding, final double minLat, final double maxLat, final double minLon, final double maxLon) { public GeoPointInBBoxQuery(final String field, final TermEncoding termEncoding, final double minLat, final double maxLat, final double minLon, final double maxLon) {
if (field == null) { if (field == null) {
throw new IllegalArgumentException("field cannot be null"); throw new IllegalArgumentException("field must not be null");
} }
if (termEncoding == null) { if (termEncoding == null) {
throw new IllegalArgumentException("termEncoding cannot be null"); throw new IllegalArgumentException("termEncoding must not be null");
} }
GeoUtils.checkLatitude(minLat); GeoUtils.checkLatitude(minLat);
GeoUtils.checkLatitude(maxLat); GeoUtils.checkLatitude(maxLat);

View File

@ -71,19 +71,7 @@ public final class GeoPointInPolygonQuery extends GeoPointInBBoxQuery {
/** Common constructor, used only internally. */ /** Common constructor, used only internally. */
private GeoPointInPolygonQuery(final String field, TermEncoding termEncoding, GeoRect bbox, final double[] polyLats, final double[] polyLons) { private GeoPointInPolygonQuery(final String field, TermEncoding termEncoding, GeoRect bbox, final double[] polyLats, final double[] polyLons) {
super(field, termEncoding, bbox.minLat, bbox.maxLat, bbox.minLon, bbox.maxLon); super(field, termEncoding, bbox.minLat, bbox.maxLat, bbox.minLon, bbox.maxLon);
if (polyLats.length != polyLons.length) { GeoUtils.checkPolygon(polyLats, polyLons);
throw new IllegalArgumentException("polyLats and polyLons must be equal length");
}
if (polyLats.length < 4) {
throw new IllegalArgumentException("at least 4 polygon points required");
}
if (polyLats[0] != polyLats[polyLats.length-1]) {
throw new IllegalArgumentException("first and last points of the polygon must be the same (it must close itself): polyLats[0]=" + polyLats[0] + " polyLats[" + (polyLats.length-1) + "]=" + polyLats[polyLats.length-1]);
}
if (polyLons[0] != polyLons[polyLons.length-1]) {
throw new IllegalArgumentException("first and last points of the polygon must be the same (it must close itself): polyLons[0]=" + polyLons[0] + " polyLons[" + (polyLons.length-1) + "]=" + polyLons[polyLons.length-1]);
}
this.polyLons = polyLons; this.polyLons = polyLons;
this.polyLats = polyLats; this.polyLats = polyLats;
} }
@ -111,8 +99,8 @@ public final class GeoPointInPolygonQuery extends GeoPointInBBoxQuery {
@Override @Override
public int hashCode() { public int hashCode() {
int result = super.hashCode(); int result = super.hashCode();
result = 31 * result + (polyLats != null ? Arrays.hashCode(polyLats) : 0); result = 31 * result + Arrays.hashCode(polyLats);
result = 31 * result + (polyLons != null ? Arrays.hashCode(polyLons) : 0); result = 31 * result + Arrays.hashCode(polyLons);
return result; return result;
} }

View File

@ -24,7 +24,6 @@ import static org.apache.lucene.util.SloppyMath.asin;
import static org.apache.lucene.util.SloppyMath.cos; import static org.apache.lucene.util.SloppyMath.cos;
import static org.apache.lucene.util.SloppyMath.TO_DEGREES; import static org.apache.lucene.util.SloppyMath.TO_DEGREES;
import static org.apache.lucene.util.SloppyMath.TO_RADIANS; import static org.apache.lucene.util.SloppyMath.TO_RADIANS;
import static org.apache.lucene.spatial.util.GeoEncodingUtils.TOLERANCE;
/** /**
* Basic reusable geo-spatial utility methods * Basic reusable geo-spatial utility methods
@ -75,6 +74,37 @@ public final class GeoUtils {
} }
} }
/** validates polygon values are within standard +/-180 coordinate bounds, same
* number of latitude and longitude, and is closed
*/
public static void checkPolygon(double[] polyLats, double[] polyLons) {
if (polyLats == null) {
throw new IllegalArgumentException("polyLats must not be null");
}
if (polyLons == null) {
throw new IllegalArgumentException("polyLons must not be null");
}
if (polyLats.length != polyLons.length) {
throw new IllegalArgumentException("polyLats and polyLons must be equal length");
}
if (polyLats.length != polyLons.length) {
throw new IllegalArgumentException("polyLats and polyLons must be equal length");
}
if (polyLats.length < 4) {
throw new IllegalArgumentException("at least 4 polygon points required");
}
if (polyLats[0] != polyLats[polyLats.length-1]) {
throw new IllegalArgumentException("first and last points of the polygon must be the same (it must close itself): polyLats[0]=" + polyLats[0] + " polyLats[" + (polyLats.length-1) + "]=" + polyLats[polyLats.length-1]);
}
if (polyLons[0] != polyLons[polyLons.length-1]) {
throw new IllegalArgumentException("first and last points of the polygon must be the same (it must close itself): polyLons[0]=" + polyLons[0] + " polyLons[" + (polyLons.length-1) + "]=" + polyLons[polyLons.length-1]);
}
for (int i = 0; i < polyLats.length; i++) {
checkLatitude(polyLats[i]);
checkLongitude(polyLons[i]);
}
}
/** Compute Bounding Box for a circle using WGS-84 parameters */ /** Compute Bounding Box for a circle using WGS-84 parameters */
public static GeoRect circleToBBox(final double centerLat, final double centerLon, final double radiusMeters) { public static GeoRect circleToBBox(final double centerLat, final double centerLon, final double radiusMeters) {
final double radLat = TO_RADIANS * centerLat; final double radLat = TO_RADIANS * centerLat;
@ -108,9 +138,7 @@ public final class GeoUtils {
/** Compute Bounding Box for a polygon using WGS-84 parameters */ /** Compute Bounding Box for a polygon using WGS-84 parameters */
public static GeoRect polyToBBox(double[] polyLats, double[] polyLons) { public static GeoRect polyToBBox(double[] polyLats, double[] polyLons) {
if (polyLats.length != polyLons.length) { checkPolygon(polyLats, polyLons);
throw new IllegalArgumentException("polyLats and polyLons must be equal length");
}
double minLon = Double.POSITIVE_INFINITY; double minLon = Double.POSITIVE_INFINITY;
double maxLon = Double.NEGATIVE_INFINITY; double maxLon = Double.NEGATIVE_INFINITY;
@ -118,16 +146,12 @@ public final class GeoUtils {
double maxLat = Double.NEGATIVE_INFINITY; double maxLat = Double.NEGATIVE_INFINITY;
for (int i=0;i<polyLats.length;i++) { for (int i=0;i<polyLats.length;i++) {
checkLatitude(polyLats[i]);
checkLongitude(polyLons[i]);
minLat = min(polyLats[i], minLat); minLat = min(polyLats[i], minLat);
maxLat = max(polyLats[i], maxLat); maxLat = max(polyLats[i], maxLat);
minLon = min(polyLons[i], minLon); minLon = min(polyLons[i], minLon);
maxLon = max(polyLons[i], maxLon); maxLon = max(polyLons[i], maxLon);
} }
// expand bounding box by TOLERANCE factor to handle round-off error return new GeoRect(minLat, maxLat, minLon, maxLon);
return new GeoRect(max(minLat - TOLERANCE, MIN_LAT_INCL), min(maxLat + TOLERANCE, MAX_LAT_INCL),
max(minLon - TOLERANCE, MIN_LON_INCL), min(maxLon + TOLERANCE, MAX_LON_INCL));
} }
// some sloppyish stuff, do we really need this to be done in a sloppy way? // some sloppyish stuff, do we really need this to be done in a sloppy way?

View File

@ -217,6 +217,13 @@ public abstract class BaseGeoPointTestCase extends LuceneTestCase {
dir.close(); dir.close();
} }
/** null field name not allowed */
public void testBoxNull() {
IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {
newRectQuery(null, 18, 19, -66, -65);
});
assertTrue(expected.getMessage().contains("field must not be null"));
}
// box should not accept invalid lat/lon // box should not accept invalid lat/lon
public void testBoxInvalidCoordinates() throws Exception { public void testBoxInvalidCoordinates() throws Exception {
@ -245,12 +252,21 @@ public abstract class BaseGeoPointTestCase extends LuceneTestCase {
dir.close(); dir.close();
} }
/** null field name not allowed */
public void testDistanceNull() {
IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {
newDistanceQuery(null, 18, -65, 50_000);
});
assertTrue(expected.getMessage().contains("field must not be null"));
}
/** distance query should not accept invalid lat/lon as origin */ /** distance query should not accept invalid lat/lon as origin */
public void testDistanceIllegal() throws Exception { public void testDistanceIllegal() throws Exception {
expectThrows(Exception.class, () -> { expectThrows(Exception.class, () -> {
newDistanceQuery("field", 92.0, 181.0, 120000); newDistanceQuery("field", 92.0, 181.0, 120000);
}); });
} }
/** negative distance queries are not allowed */ /** negative distance queries are not allowed */
public void testDistanceNegative() { public void testDistanceNegative() {
IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> { IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {
@ -308,6 +324,66 @@ public abstract class BaseGeoPointTestCase extends LuceneTestCase {
dir.close(); dir.close();
} }
/** null field name not allowed */
public void testPolygonNullField() {
IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {
newPolygonQuery(null,
new double[] { 18, 18, 19, 19, 18 },
new double[] { -66, -65, -65, -66, -66 });
});
assertTrue(expected.getMessage().contains("field must not be null"));
}
/** null polyLats not allowed */
public void testPolygonNullPolyLats() {
IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {
newPolygonQuery("test",
null,
new double[] { -66, -65, -65, -66, -66 });
});
assertTrue(expected.getMessage().contains("polyLats must not be null"));
}
/** null polyLons not allowed */
public void testPolygonNullPolyLons() {
IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {
newPolygonQuery("test",
new double[] { 18, 18, 19, 19, 18 },
null);
});
assertTrue(expected.getMessage().contains("polyLons must not be null"));
}
/** polygon needs at least 3 vertices */
public void testPolygonLine() {
IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {
newPolygonQuery("test",
new double[] { 18, 18, 18 },
new double[] { -66, -65, -66 });
});
assertTrue(expected.getMessage().contains("at least 4 polygon points required"));
}
/** polygon needs same number of latitudes as longitudes */
public void testPolygonBogus() {
IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {
newPolygonQuery("test",
new double[] { 18, 18, 19, 19 },
new double[] { -66, -65, -65, -66, -66 });
});
assertTrue(expected.getMessage().contains("must be equal length"));
}
/** polygon must be closed */
public void testPolygonNotClosed() {
IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {
newPolygonQuery("test",
new double[] { 18, 18, 19, 19, 19 },
new double[] { -66, -65, -65, -66, -67 });
});
assertTrue(expected.getMessage(), expected.getMessage().contains("it must close itself"));
}
// A particularly tricky adversary for BKD tree: // A particularly tricky adversary for BKD tree:
public void testSamePointManyTimes() throws Exception { public void testSamePointManyTimes() throws Exception {
int numPoints = atLeast(1000); int numPoints = atLeast(1000);

View File

@ -321,4 +321,40 @@ public class TestGeoUtils extends LuceneTestCase {
assertFalse(GeoRelationUtils.rectCrossesPolyApprox(0, 5, -5, 0.000001, py, px, yMin, yMax, xMin, xMax)); assertFalse(GeoRelationUtils.rectCrossesPolyApprox(0, 5, -5, 0.000001, py, px, yMin, yMax, xMin, xMax));
assertTrue(GeoRelationUtils.rectWithinPolyApprox(0, 5, -5, -2, py, px, yMin, yMax, xMin, xMax)); assertTrue(GeoRelationUtils.rectWithinPolyApprox(0, 5, -5, -2, py, px, yMin, yMax, xMin, xMax));
} }
public void testPolyToBBox() throws Exception {
for (int i = 0; i < 1000; i++) {
double[][] polygon = GeoTestUtil.nextPolygon();
GeoRect box = GeoUtils.polyToBBox(polygon[0], polygon[1]);
assertFalse(box.crossesDateline());
for (int j = 0; j < 1000; j++) {
double latitude = GeoTestUtil.nextLatitude();
double longitude = GeoTestUtil.nextLongitude();
// if the point is within poly, then it should be in our bounding box
if (GeoRelationUtils.pointInPolygon(polygon[0], polygon[1], latitude, longitude)) {
assertTrue(latitude >= box.minLat && latitude <= box.maxLat);
assertTrue(longitude >= box.minLon && longitude <= box.maxLon);
}
}
}
}
public void testPolyToBBoxEdgeCases() throws Exception {
for (int i = 0; i < 1000; i++) {
double[][] polygon = GeoTestUtil.nextPolygon();
GeoRect box = GeoUtils.polyToBBox(polygon[0], polygon[1]);
assertFalse(box.crossesDateline());
for (int j = 0; j < 1000; j++) {
double latitude = GeoTestUtil.nextLatitudeAround(box.minLat, box.maxLat);
double longitude = GeoTestUtil.nextLongitudeAround(box.minLon, box.maxLon);
// if the point is within poly, then it should be in our bounding box
if (GeoRelationUtils.pointInPolygon(polygon[0], polygon[1], latitude, longitude)) {
assertTrue(latitude >= box.minLat && latitude <= box.maxLat);
assertTrue(longitude >= box.minLon && longitude <= box.maxLon);
}
}
}
}
} }