-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
PointValue.java
611 lines (561 loc) · 21 KB
/
PointValue.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/*
* Copyright (c) 2002-2018 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.values.storable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.neo4j.graphdb.spatial.CRS;
import org.neo4j.graphdb.spatial.Coordinate;
import org.neo4j.graphdb.spatial.Point;
import org.neo4j.values.AnyValue;
import org.neo4j.values.Comparison;
import org.neo4j.values.ValueMapper;
import org.neo4j.values.utils.InvalidValuesArgumentException;
import org.neo4j.values.utils.PrettyPrinter;
import org.neo4j.values.virtual.MapValue;
import static java.lang.String.format;
import static java.util.Collections.singletonList;
public class PointValue extends ScalarValue implements Point, Comparable<PointValue>
{
public static String[] ALLOWED_KEYS = new String[]{"crs", "x", "y", "z", "longitude", "latitude", "height", "srid"};
private CoordinateReferenceSystem crs;
private double[] coordinate;
PointValue( CoordinateReferenceSystem crs, double... coordinate )
{
this.crs = crs;
this.coordinate = coordinate;
for ( double c : coordinate )
{
if ( !Double.isFinite( c ) )
{
throw new InvalidValuesArgumentException( "Cannot create a point with non-finite coordinate values: " + Arrays.toString(coordinate) );
}
}
}
@Override
public <E extends Exception> void writeTo( ValueWriter<E> writer ) throws E
{
writer.writePoint( getCoordinateReferenceSystem(), coordinate );
}
@Override
public String prettyPrint()
{
PrettyPrinter prettyPrinter = new PrettyPrinter();
this.writeTo( prettyPrinter );
return prettyPrinter.value();
}
@Override
public ValueGroup valueGroup()
{
return ValueGroup.GEOMETRY;
}
@Override
public NumberType numberType()
{
return NumberType.NO_NUMBER;
}
@Override
public boolean equals( Value other )
{
if ( other instanceof PointValue )
{
PointValue pv = (PointValue) other;
return Arrays.equals( this.coordinate, pv.coordinate ) && this.getCoordinateReferenceSystem().equals( pv.getCoordinateReferenceSystem() );
}
return false;
}
public boolean equals( Point other )
{
if ( !other.getCRS().getHref().equals( this.getCRS().getHref() ) )
{
return false;
}
// TODO: This can be an assert
List<Double> otherCoordinate = other.getCoordinate().getCoordinate();
if ( otherCoordinate.size() != this.coordinate.length )
{
return false;
}
for ( int i = 0; i < this.coordinate.length; i++ )
{
if ( otherCoordinate.get( i ) != this.coordinate[i] )
{
return false;
}
}
return true;
}
@Override
public boolean eq( Object other )
{
return other != null && ((other instanceof Value && equals( (Value) other )) || (other instanceof Point && equals( (Point) other )));
}
@Override
public int compareTo( PointValue other )
{
int cmpCRS = this.crs.getCode() - other.crs.getCode();
if ( cmpCRS != 0 )
{
return cmpCRS;
}
// TODO: This is unnecessary and can be an assert. Is it even correct? This implies e.g. that all 2D points are before all 3D regardless of x and y
if ( this.coordinate.length > other.coordinate.length )
{
return 1;
}
else if ( this.coordinate.length < other.coordinate.length )
{
return -1;
}
for ( int i = 0; i < coordinate.length; i++ )
{
int cmpVal = Double.compare( this.coordinate[i], other.coordinate[i] );
if ( cmpVal != 0 )
{
return cmpVal;
}
}
return 0;
}
@Override
int unsafeCompareTo( Value otherValue )
{
return compareTo( (PointValue) otherValue );
}
@Override
Comparison unsafeTernaryCompareTo( Value otherValue )
{
PointValue other = (PointValue) otherValue;
if ( this.crs.getCode() != other.crs.getCode() || this.coordinate.length != other.coordinate.length )
{
return Comparison.UNDEFINED;
}
int result = 0;
for ( int i = 0; i < coordinate.length; i++ )
{
int cmpVal = Double.compare( this.coordinate[i], other.coordinate[i] );
if ( cmpVal != 0 && cmpVal != result )
{
if ( (cmpVal < 0 && result > 0) || (cmpVal > 0 && result < 0) )
{
return Comparison.UNDEFINED;
}
result = cmpVal;
}
}
return Comparison.from( result );
}
@Override
public Point asObjectCopy()
{
return this;
}
public CoordinateReferenceSystem getCoordinateReferenceSystem()
{
return crs;
}
/*
* Consumers must not modify the returned array.
*/
public double[] coordinate()
{
return this.coordinate;
}
@Override
public int computeHash()
{
int result = 1;
result = 31 * result + NumberValues.hash( crs.getCode() );
result = 31 * result + NumberValues.hash( coordinate );
return result;
}
@Override
public <T> T map( ValueMapper<T> mapper )
{
return mapper.mapPoint( this );
}
@Override
public String toString()
{
String coordString = coordinate.length == 2 ? format( "x: %s, y: %s", coordinate[0], coordinate[1] ) :
format( "x: %s, y: %s, z: %s", coordinate[0], coordinate[1], coordinate[2] );
return format( "point({%s, crs: '%s'})", coordString, getCoordinateReferenceSystem().getName() );
}
/**
* The string representation of this object when indexed in string-only indexes, like lucene, for equality search only. This should normally only
* happen when points are part of composite indexes, because otherwise they are indexed in the spatial index.
*/
public String toIndexableString()
{
CoordinateReferenceSystem crs = getCoordinateReferenceSystem();
return format( "P:%d-%d%s", crs.getTable().getTableId(), crs.getCode(), Arrays.toString( coordinate ) );
}
@Override
public List<Coordinate> getCoordinates()
{
return singletonList( new Coordinate( coordinate ) );
}
@Override
public CRS getCRS()
{
return crs;
}
/**
* Checks if this point is greater than (or equal) to lower and smaller than (or equal) to upper.
*
* @param lower point this value should be greater than
* @param includeLower governs if the lower comparison should be inclusive
* @param upper point this value should be smaller than
* @param includeUpper governs if the upper comparison should be inclusive
* @return true if this value is within the described range
*/
public boolean withinRange( PointValue lower, boolean includeLower, PointValue upper, boolean includeUpper )
{
if ( lower != null )
{
Comparison compareLower = this.unsafeTernaryCompareTo( lower );
if ( compareLower == Comparison.UNDEFINED || compareLower == Comparison.SMALLER_THAN || compareLower == Comparison.EQUAL && !includeLower )
{
return false;
}
}
if ( upper != null )
{
Comparison compareUpper = this.unsafeTernaryCompareTo( upper );
return compareUpper != Comparison.UNDEFINED && compareUpper != Comparison.GREATER_THAN &&
(compareUpper != Comparison.EQUAL || includeUpper);
}
return true;
}
public static PointValue fromMap( MapValue map )
{
PointBuilder fields = new PointBuilder();
for ( Map.Entry<String,AnyValue> entry : map.entrySet() )
{
fields.assign( entry.getKey().toLowerCase(), entry.getValue() );
}
return fromInputFields( fields );
}
public static PointValue parse( CharSequence text )
{
return PointValue.parse( text, null );
}
/**
* Parses the given text into a PointValue. The information stated in the header is saved into the PointValue
* unless it is overridden by the information in the text
*
* @param text the input text to be parsed into a PointValue
* @param fieldsFromHeader must be a value obtained from {@link #parseHeaderInformation(CharSequence)} or null
* @return a PointValue instance with information from the {@param fieldsFromHeader} and {@param text}
*/
public static PointValue parse( CharSequence text, CSVHeaderInformation fieldsFromHeader )
{
PointBuilder fieldsFromData = parseHeaderInformation( text );
if ( fieldsFromHeader != null )
{
// Merge InputFields: Data fields override header fields
if ( !(fieldsFromHeader instanceof PointBuilder) )
{
throw new IllegalStateException( "Wrong header information type: " + fieldsFromHeader );
}
fieldsFromData.mergeWithHeader( (PointBuilder) fieldsFromHeader );
}
return fromInputFields( fieldsFromData );
}
public static PointBuilder parseHeaderInformation( CharSequence text )
{
PointBuilder fields = new PointBuilder();
Value.parseHeaderInformation( text, "point", fields );
return fields;
}
private static CoordinateReferenceSystem findSpecifiedCRS( PointBuilder fields )
{
String crsValue = fields.crs;
int sridValue = fields.srid;
if ( crsValue != null && sridValue != -1 )
{
throw new InvalidValuesArgumentException( "Cannot specify both CRS and SRID" );
}
else if ( crsValue != null )
{
return CoordinateReferenceSystem.byName( crsValue );
}
else if ( sridValue != -1 )
{
return CoordinateReferenceSystem.get( sridValue );
}
else
{
return null;
}
}
/**
* This contains the logic to decide the default coordinate reference system based on the input fields
*/
private static PointValue fromInputFields( PointBuilder fields )
{
CoordinateReferenceSystem crs = findSpecifiedCRS( fields );
double[] coordinates;
if ( fields.x != null && fields.y != null )
{
coordinates = fields.z != null ? new double[]{fields.x, fields.y, fields.z} : new double[]{fields.x, fields.y};
if ( crs == null )
{
crs = coordinates.length == 3 ? CoordinateReferenceSystem.Cartesian_3D : CoordinateReferenceSystem.Cartesian;
}
}
else if ( fields.latitude != null && fields.longitude != null )
{
if ( fields.z != null )
{
coordinates = new double[]{fields.longitude, fields.latitude, fields.z};
}
else if ( fields.height != null )
{
coordinates = new double[]{fields.longitude, fields.latitude, fields.height};
}
else
{
coordinates = new double[]{fields.longitude, fields.latitude};
}
if ( crs == null )
{
crs = coordinates.length == 3 ? CoordinateReferenceSystem.WGS84_3D : CoordinateReferenceSystem.WGS84;
}
if ( !crs.isGeographic() )
{
throw new InvalidValuesArgumentException( "Geographic points does not support coordinate reference system: " + crs +
". This is set either in the csv header or the actual data column" );
}
}
else
{
if ( crs == CoordinateReferenceSystem.Cartesian )
{
throw new InvalidValuesArgumentException( "A " + CoordinateReferenceSystem.Cartesian.getName() + " point must contain 'x' and 'y'" );
}
else if ( crs == CoordinateReferenceSystem.Cartesian_3D )
{
throw new InvalidValuesArgumentException( "A " + CoordinateReferenceSystem.Cartesian_3D.getName() + " point must contain 'x', 'y' and 'z'" );
}
else if ( crs == CoordinateReferenceSystem.WGS84 )
{
throw new InvalidValuesArgumentException( "A " + CoordinateReferenceSystem.WGS84.getName() + " point must contain 'latitude' and 'longitude'" );
}
else if ( crs == CoordinateReferenceSystem.WGS84_3D )
{
throw new InvalidValuesArgumentException(
"A " + CoordinateReferenceSystem.WGS84_3D.getName() + " point must contain 'latitude', 'longitude' and 'height'" );
}
throw new InvalidValuesArgumentException( "A point must contain either 'x' and 'y' or 'latitude' and 'longitude'" );
}
if ( crs.getDimension() != coordinates.length )
{
throw new InvalidValuesArgumentException( "Cannot create point with " + crs.getDimension() + "D coordinate reference system and "
+ coordinates.length + " coordinates. Please consider using equivalent " + coordinates.length + "D coordinate reference system" );
}
return Values.pointValue( crs, coordinates );
}
/**
* For accessors from cypher.
*/
public Value get( String fieldName )
{
switch ( fieldName.toLowerCase() )
{
case "x":
return getNthCoordinate( 0, fieldName, false );
case "y":
return getNthCoordinate( 1, fieldName, false );
case "z":
return getNthCoordinate( 2, fieldName, false );
case "longitude":
return getNthCoordinate( 0, fieldName, true );
case "latitude":
return getNthCoordinate( 1, fieldName, true );
case "height":
return getNthCoordinate( 2, fieldName, true );
case "crs":
return Values.stringValue( crs.toString() );
case "srid":
return Values.intValue( crs.getCode() );
default:
throw new InvalidValuesArgumentException( "No such field: " + fieldName );
}
}
private DoubleValue getNthCoordinate( int n, String fieldName, boolean onlyGeographic )
{
if ( onlyGeographic && !this.getCoordinateReferenceSystem().isGeographic() )
{
throw new InvalidValuesArgumentException( "Field: " + fieldName + " is not available on cartesian point: " + this );
}
else if ( n >= this.coordinate().length )
{
throw new InvalidValuesArgumentException( "Field: " + fieldName + " is not available on point: " + this );
}
else
{
return Values.doubleValue( coordinate[n] );
}
}
private static class PointBuilder implements CSVHeaderInformation
{
private String crs;
private Double x;
private Double y;
private Double z;
private Double longitude;
private Double latitude;
private Double height;
private int srid = -1;
private boolean allowOpenMaps = true;
@Override
public void assign( String key, Object value )
{
switch ( key.toLowerCase() )
{
case "crs":
checkUnassigned( crs, key );
assignTextValue( key, value, str -> crs = quotesPattern.matcher( str ).replaceAll( "" ) );
break;
case "x":
checkUnassigned( x, key );
assignFloatingPoint( key, value, i -> x = i );
break;
case "y":
checkUnassigned( y, key );
assignFloatingPoint( key, value, i -> y = i );
break;
case "z":
checkUnassigned( z, key );
assignFloatingPoint( key, value, i -> z = i );
break;
case "longitude":
checkUnassigned( longitude, key );
assignFloatingPoint( key, value, i -> longitude = i );
break;
case "latitude":
checkUnassigned( latitude, key );
assignFloatingPoint( key, value, i -> latitude = i );
break;
case "height":
checkUnassigned( height, key );
assignFloatingPoint( key, value, i -> height = i );
break;
case "srid":
if ( srid != -1 )
{
throw new InvalidValuesArgumentException( String.format( "Duplicate field '%s' is not allowed.", key ) );
}
assignIntegral( key, value, i -> srid = i );
break;
default:
if ( !allowOpenMaps )
{
throwOnUnrecognizedKey( key );
}
}
}
void mergeWithHeader( PointBuilder header )
{
this.crs = this.crs == null ? header.crs : this.crs;
this.x = this.x == null ? header.x : this.x;
this.y = this.y == null ? header.y : this.y;
this.z = this.z == null ? header.z : this.z;
this.longitude = this.longitude == null ? header.longitude : this.longitude;
this.latitude = this.latitude == null ? header.latitude : this.latitude;
this.height = this.height == null ? header.height : this.height;
this.srid = this.srid == -1 ? header.srid : this.srid;
}
private void assignTextValue( String key, Object value, Consumer<String> assigner )
{
if ( value instanceof String )
{
assigner.accept( (String) value );
}
else if ( value instanceof TextValue )
{
assigner.accept( ((TextValue) value).stringValue() );
}
else
{
throw new InvalidValuesArgumentException( String.format( "Cannot assign %s to field %s", value, key ) );
}
}
private void assignFloatingPoint( String key, Object value, Consumer<Double> assigner )
{
if ( value instanceof String )
{
assigner.accept( assertConvertible( () -> Double.parseDouble( (String) value ) ) );
}
else if ( value instanceof IntegralValue )
{
assigner.accept( ((IntegralValue) value).doubleValue() );
}
else if ( value instanceof FloatingPointValue )
{
assigner.accept( ((FloatingPointValue) value).doubleValue() );
}
else
{
throw new InvalidValuesArgumentException( String.format( "Cannot assign %s to field %s", value, key ) );
}
}
private void assignIntegral( String key, Object value, Consumer<Integer> assigner )
{
if ( value instanceof String )
{
assigner.accept( assertConvertible( () -> Integer.parseInt( (String) value ) ) );
}
else if ( value instanceof IntegralValue )
{
assigner.accept( (int) ((IntegralValue) value).longValue() );
}
else
{
throw new InvalidValuesArgumentException( String.format( "Cannot assign %s to field %s", value, key ) );
}
}
private void throwOnUnrecognizedKey( String key )
{
throw new InvalidValuesArgumentException( String.format( "Unknown key '%s' for creating new point", key ) );
}
private <T extends Number> T assertConvertible( Supplier<T> func )
{
try
{
return func.get();
}
catch ( NumberFormatException e )
{
throw new InvalidValuesArgumentException( e.getMessage(), e );
}
}
private void checkUnassigned( Object key, String fieldName )
{
if ( key != null )
{
throw new InvalidValuesArgumentException( String.format( "Duplicate field '%s' is not allowed.", fieldName ) );
}
}
}
}