diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/value/InternalValue.java b/driver/src/main/java/org/neo4j/driver/internal/AsValue.java similarity index 77% rename from driver/src/main/java/org/neo4j/driver/v1/internal/value/InternalValue.java rename to driver/src/main/java/org/neo4j/driver/internal/AsValue.java index ccec0481c9..1412f42b41 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/value/InternalValue.java +++ b/driver/src/main/java/org/neo4j/driver/internal/AsValue.java @@ -16,12 +16,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.value; +package org.neo4j.driver.internal; import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.types.TypeConstructor; -public interface InternalValue extends Value +public interface AsValue { - TypeConstructor typeConstructor(); + /** + * Retrieve a value representation of this + * + * @see Value + * @return {@link Value} that represents this + */ + Value asValue(); } diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/Identities.java b/driver/src/main/java/org/neo4j/driver/internal/Identities.java similarity index 91% rename from driver/src/main/java/org/neo4j/driver/v1/internal/Identities.java rename to driver/src/main/java/org/neo4j/driver/internal/Identities.java index b08c42c9de..4b034d9085 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/Identities.java +++ b/driver/src/main/java/org/neo4j/driver/internal/Identities.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; +package org.neo4j.driver.internal; import org.neo4j.driver.v1.Identity; @@ -24,7 +24,6 @@ public class Identities { public static Identity identity( long raw ) { - return new SimpleIdentity( raw ); + return new InternalIdentity( raw ); } - } diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/SimpleEntity.java b/driver/src/main/java/org/neo4j/driver/internal/InternalEntity.java similarity index 53% rename from driver/src/main/java/org/neo4j/driver/v1/internal/SimpleEntity.java rename to driver/src/main/java/org/neo4j/driver/internal/InternalEntity.java index 2c9f78c895..5f761e51b0 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/SimpleEntity.java +++ b/driver/src/main/java/org/neo4j/driver/internal/InternalEntity.java @@ -16,21 +16,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; +package org.neo4j.driver.internal; -import java.util.Collection; import java.util.Map; +import org.neo4j.driver.internal.util.Extract; +import org.neo4j.driver.internal.util.Iterables; +import org.neo4j.driver.internal.value.MapValue; import org.neo4j.driver.v1.Entity; +import org.neo4j.driver.v1.Function; import org.neo4j.driver.v1.Identity; +import org.neo4j.driver.v1.Property; import org.neo4j.driver.v1.Value; +import org.neo4j.driver.v1.Values; -public abstract class SimpleEntity implements Entity +import static org.neo4j.driver.v1.Values.valueAsIs; + +public abstract class InternalEntity implements Entity, AsValue { private final Identity id; private final Map properties; - public SimpleEntity( Identity id, Map properties ) + public InternalEntity( Identity id, Map properties ) { this.id = id; this.properties = properties; @@ -43,21 +50,19 @@ public Identity identity() } @Override - public Collection propertyKeys() + public Property property( String key ) { - return properties.keySet(); + return InternalProperty.of( key, value( key ) ); } - @Override - public Value property( String key ) + public int propertyCount() { - return properties.get( key ); + return properties.size(); } - @Override - public int propertyCount() + public Value asValue() { - return properties.size(); + return new MapValue( properties ); } @Override @@ -72,7 +77,7 @@ public boolean equals( Object o ) return false; } - SimpleEntity that = (SimpleEntity) o; + InternalEntity that = (InternalEntity) o; return id.equals( that.id ); @@ -92,4 +97,47 @@ public String toString() ", properties=" + properties + '}'; } + + @Override + public boolean containsKey( String key ) + { + return properties.containsKey( key ); + } + + @Override + public Iterable keys() + { + return properties.keySet(); + } + + @Override + public Value value( String key ) + { + Value value = properties.get( key ); + return value == null ? Values.NULL : value; + } + + @Override + public Iterable values() + { + return properties.values(); + } + + @Override + public Iterable values( Function mapFunction ) + { + return Iterables.map( properties.values(), mapFunction ); + } + + @Override + public Iterable> properties() + { + return properties( valueAsIs() ); + } + + @Override + public Iterable> properties( final Function Function ) + { + return Extract.properties( this, Function ); + } } diff --git a/driver/src/main/java/org/neo4j/driver/internal/InternalField.java b/driver/src/main/java/org/neo4j/driver/internal/InternalField.java new file mode 100644 index 0000000000..0474d353c6 --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/InternalField.java @@ -0,0 +1,110 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal; + +import java.util.Objects; + +import org.neo4j.driver.v1.Field; +import org.neo4j.driver.v1.Function; +import org.neo4j.driver.v1.Property; + +public class InternalField implements Field +{ + private final int index; + private final String key; + private final V value; + + public InternalField( String key, int index, V value ) + { + if ( key == null ) + { + throw new IllegalArgumentException( "null key" ); + } + if ( value == null ) + { + throw new IllegalArgumentException( "null value" ); + } + this.index = index; + this.key = key; + this.value = value; + } + + public String key() + { + return key; + } + + public V value() + { + return value; + } + + @Override + public int index() + { + return index; + } + + @Override + public Property asProperty() + { + return InternalProperty.of( key, value ); + } + + @Override + public String toString() + { + return String.format( "%s: %s", key, Objects.toString( value ) ); + } + + public String toString( Function printValue ) + { + return String.format( "%s: %s", key, printValue.apply( value ) ); + } + + @Override + public boolean equals( Object o ) + { + if ( this == o ) + { + return true; + } + if ( o == null || getClass() != o.getClass() ) + { + return false; + } + + InternalField that = (InternalField) o; + return index == that.index && key.equals( that.key ) && value.equals( that.value ); + } + + @Override + public int hashCode() + { + int result = index; + result = 31 * result + key.hashCode(); + result = 31 * result + value.hashCode(); + return result; + } + + public static Field of( String key, int index, V value ) + { + return new InternalField<>( key, index, value ); + } +} diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/SimpleIdentity.java b/driver/src/main/java/org/neo4j/driver/internal/InternalIdentity.java similarity index 78% rename from driver/src/main/java/org/neo4j/driver/v1/internal/SimpleIdentity.java rename to driver/src/main/java/org/neo4j/driver/internal/InternalIdentity.java index cb5b81f3dc..dead39c0f0 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/SimpleIdentity.java +++ b/driver/src/main/java/org/neo4j/driver/internal/InternalIdentity.java @@ -16,19 +16,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; +package org.neo4j.driver.internal; +import org.neo4j.driver.internal.value.IdentityValue; import org.neo4j.driver.v1.Identity; +import org.neo4j.driver.v1.Value; -public class SimpleIdentity implements Identity +public class InternalIdentity implements Identity, AsValue { private final long raw; - public SimpleIdentity( long raw ) + public InternalIdentity( long raw ) { this.raw = raw; } + @Override + public Value asValue() + { + return new IdentityValue( this ); + } + @Override public String toString() { @@ -47,7 +55,7 @@ public boolean equals( Object o ) return false; } - SimpleIdentity that = (SimpleIdentity) o; + InternalIdentity that = (InternalIdentity) o; return raw == that.raw; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/SimpleNode.java b/driver/src/main/java/org/neo4j/driver/internal/InternalNode.java similarity index 74% rename from driver/src/main/java/org/neo4j/driver/v1/internal/SimpleNode.java rename to driver/src/main/java/org/neo4j/driver/internal/InternalNode.java index ef731eaa0e..5c4b7235d4 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/SimpleNode.java +++ b/driver/src/main/java/org/neo4j/driver/internal/InternalNode.java @@ -16,12 +16,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; +package org.neo4j.driver.internal; import java.util.Collection; import java.util.Collections; import java.util.Map; +import org.neo4j.driver.internal.value.NodeValue; import org.neo4j.driver.v1.Identity; import org.neo4j.driver.v1.Node; import org.neo4j.driver.v1.Value; @@ -29,21 +30,21 @@ /** * {@link Node} implementation that directly contains labels and properties. */ -public class SimpleNode extends SimpleEntity implements Node +public class InternalNode extends InternalEntity implements Node { private final Collection labels; - public SimpleNode( long id ) + public InternalNode( long id ) { this( id, Collections.emptyList(), Collections.emptyMap() ); } - public SimpleNode( long id, Collection labels, Map properties ) + public InternalNode( long id, Collection labels, Map properties ) { this( Identities.identity( id ), labels, properties ); } - public SimpleNode( Identity identity, Collection labels, Map properties ) + public InternalNode( Identity identity, Collection labels, Map properties ) { super( identity, properties ); this.labels = labels; @@ -55,10 +56,22 @@ public Collection labels() return labels; } + @Override + public boolean hasLabel( String label ) + { + return labels.contains( label ); + } + + @Override + public Value asValue() + { + return new NodeValue( this ); + } + @Override public String toString() { - return "node<" + identity() + '>'; + return String.format( "node<%s>", identity() ); } @Override @@ -77,7 +90,7 @@ public boolean equals( Object o ) return false; } - SimpleNode that = (SimpleNode) o; + InternalNode that = (InternalNode) o; return !(labels != null ? !labels.equals( that.labels ) : that.labels != null); diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/SimplePath.java b/driver/src/main/java/org/neo4j/driver/internal/InternalPath.java similarity index 88% rename from driver/src/main/java/org/neo4j/driver/v1/internal/SimplePath.java rename to driver/src/main/java/org/neo4j/driver/internal/InternalPath.java index 5a61d594aa..3451d6fdb0 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/SimplePath.java +++ b/driver/src/main/java/org/neo4j/driver/internal/InternalPath.java @@ -16,22 +16,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; +package org.neo4j.driver.internal; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Iterator; import java.util.List; +import org.neo4j.driver.internal.value.PathValue; import org.neo4j.driver.v1.Entity; import org.neo4j.driver.v1.Node; import org.neo4j.driver.v1.Path; import org.neo4j.driver.v1.Relationship; +import org.neo4j.driver.v1.Value; /** * {@link Path} implementation that directly contains all nodes and relationships. */ -public class SimplePath implements Path +public class InternalPath implements Path, AsValue { public static class SelfContainedSegment implements Segment { @@ -77,7 +80,6 @@ public boolean equals( Object other ) } SelfContainedSegment that = (SelfContainedSegment) other; - return start.equals( that.start ) && end.equals( that.end ) && relationship.equals( that.relationship ); } @@ -109,11 +111,11 @@ private static boolean isEndpoint( Node node, Relationship relationship ) private final List relationships; private final List segments; - public SimplePath( List alternatingNodeAndRel ) + public InternalPath( List alternatingNodeAndRel ) { - nodes = new ArrayList<>(alternatingNodeAndRel.size() / 2 + 1); - relationships = new ArrayList<>(alternatingNodeAndRel.size() / 2); - segments = new ArrayList<>(alternatingNodeAndRel.size() / 2); + nodes = newList( alternatingNodeAndRel.size() / 2 + 1 ); + relationships = newList( alternatingNodeAndRel.size() / 2 ); + segments = newList( alternatingNodeAndRel.size() / 2 ); if ( alternatingNodeAndRel.size() % 2 == 0 ) { @@ -182,20 +184,25 @@ public SimplePath( List alternatingNodeAndRel ) buildSegments(); } - public SimplePath( Entity... alternatingNodeAndRel ) + public InternalPath( Entity... alternatingNodeAndRel ) { this( Arrays.asList( alternatingNodeAndRel ) ); } - public SimplePath( List segments, List nodes, List relationships ) + public InternalPath( List segments, List nodes, List relationships ) { this.segments = segments; this.nodes = nodes; this.relationships = relationships; } + private List newList( int size ) + { + return size == 0 ? Collections.emptyList() : new ArrayList( size ); + } + @Override - public long length() + public int length() { return relationships.size(); } @@ -242,6 +249,12 @@ public Iterator iterator() return segments.iterator(); } + @Override + public Value asValue() + { + return new PathValue( this ); + } + @Override public boolean equals( Object o ) { @@ -254,7 +267,7 @@ public boolean equals( Object o ) return false; } - SimplePath segments1 = (SimplePath) o; + InternalPath segments1 = (InternalPath) o; return segments.equals( segments1.segments ); @@ -270,7 +283,7 @@ public int hashCode() public String toString() { - return "Path[" + segments + ']'; + return "path[" + segments + ']'; } private void buildSegments() diff --git a/driver/src/main/java/org/neo4j/driver/internal/InternalProperty.java b/driver/src/main/java/org/neo4j/driver/internal/InternalProperty.java new file mode 100644 index 0000000000..28c4f04692 --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/InternalProperty.java @@ -0,0 +1,95 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal; + +import java.util.Objects; + +import org.neo4j.driver.v1.Function; +import org.neo4j.driver.v1.Property; + +public class InternalProperty implements Property +{ + private final String key; + private final V value; + + protected InternalProperty( String key, V value ) + { + if ( key == null ) + { + throw new IllegalArgumentException( "null key" ); + } + if ( value == null ) + { + throw new IllegalArgumentException( "null value" ); + } + this.key = key; + this.value = value; + } + + public String key() + { + return key; + } + + public V value() + { + return value; + } + + public static Property of( String key, V value ) + { + return new InternalProperty<>( key, value ); + } + + @Override + public String toString() + { + return String.format( "%s: %s", key, Objects.toString( value ) ); + } + + public String toString( Function printValue ) + { + return String.format( "%s: %s", key, printValue.apply( value ) ); + } + + @Override + public boolean equals( Object o ) + { + if ( this == o ) + { + return true; + } + if ( o == null || getClass() != o.getClass() ) + { + return false; + } + + InternalProperty that = (InternalProperty) o; + + return key.equals( that.key ) && value.equals( that.value ); + } + + @Override + public int hashCode() + { + int result = key.hashCode(); + result = 31 * result + value.hashCode(); + return result; + } +} diff --git a/driver/src/main/java/org/neo4j/driver/internal/InternalRecord.java b/driver/src/main/java/org/neo4j/driver/internal/InternalRecord.java new file mode 100644 index 0000000000..5d07d2e06b --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/InternalRecord.java @@ -0,0 +1,171 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +import org.neo4j.driver.internal.util.Extract; +import org.neo4j.driver.v1.Function; +import org.neo4j.driver.v1.Record; +import org.neo4j.driver.v1.Value; +import org.neo4j.driver.v1.Values; + +import static java.lang.String.format; + +import static org.neo4j.driver.internal.util.Format.formatFields; +import static org.neo4j.driver.internal.value.InternalValue.Format.VALUE_WITH_TYPE; +import static org.neo4j.driver.v1.Values.valueAsIs; + +public class InternalRecord extends InternalRecordAccessor implements Record +{ + private final List keys; + private final Map keyIndexLookup; + private final Value[] values; + private int hashcode = 0; + + public InternalRecord( List keys, Map keyIndexLookup, Value[] values ) + { + this.keys = keys; + this.keyIndexLookup = keyIndexLookup; + this.values = values; + } + + @Override + public Value value( int index ) + { + return index >= 0 && index < values.length ? values[index] : Values.NULL; + } + + @Override + public String key( int index ) + { + return keys.get( index ); + } + + @Override + public List keys() + { + return keys; + } + + @Override + public int index( String key ) + { + Integer result = keyIndexLookup.get( key ); + if ( result == null ) + { + throw new NoSuchElementException( "Unknown key: " + key ); + } + else + { + return result; + } + } + + @Override + public boolean containsKey( String key ) + { + return keyIndexLookup.containsKey( key ); + } + + @Override + public Value value( String key ) + { + Integer fieldIndex = keyIndexLookup.get( key ); + + if ( fieldIndex == null ) + { + return Values.NULL; + } + else + { + return values[fieldIndex]; + } + } + + @Override + public Record record() + { + return this; + } + + @Override + public Map asMap() + { + return asMap( valueAsIs() ); + } + + public Map asMap( Function mapFunction ) + { + return Extract.map( this, mapFunction ); + } + + @Override + public String toString() + { + return format( "Record<%s>", formatFields( VALUE_WITH_TYPE, fieldCount(), fields() ) ); + } + + public boolean equals( Object other ) + { + if ( this == other ) + { + return true; + } + else if ( other instanceof Record ) + { + Record otherRecord = (Record) other; + int size = fieldCount(); + if ( ! ( size == otherRecord.fieldCount() ) ) + { + return false; + } + if ( ! keys.equals( otherRecord.keys() ) ) + { + return false; + } + for ( int i = 0; i < size; i++ ) + { + Value value = value( i ); + Value otherValue = otherRecord.value( i ); + if ( ! value.equals( otherValue ) ) + { + return false; + } + } + return true; + } + else + { + return false; + } + } + + public int hashcode() + { + if ( hashcode == 0 ) + { + hashcode = 31 * keys.hashCode() + Arrays.hashCode( values ); + } + return hashcode; + } +} diff --git a/driver/src/main/java/org/neo4j/driver/internal/InternalRecordAccessor.java b/driver/src/main/java/org/neo4j/driver/internal/InternalRecordAccessor.java new file mode 100644 index 0000000000..9b00da71e8 --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/InternalRecordAccessor.java @@ -0,0 +1,63 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal; + +import java.util.List; + +import org.neo4j.driver.internal.util.Extract; +import org.neo4j.driver.v1.Field; +import org.neo4j.driver.v1.Function; +import org.neo4j.driver.v1.RecordAccessor; +import org.neo4j.driver.v1.Value; + +import static org.neo4j.driver.v1.Values.valueAsIs; + +public abstract class InternalRecordAccessor implements RecordAccessor +{ + @Override + public int fieldCount() + { + return keys().size(); + } + + @Override + public Field field( String key ) + { + int index = index( key ); + return InternalField.of( key, index, value( index ) ); + } + + @Override + public Field field( int index ) + { + return InternalField.of( key( index ), index, value( index) ); + } + + @Override + public List> fields() + { + return fields( valueAsIs() ); + } + + @Override + public List> fields( final Function mapFunction ) + { + return Extract.fields( this, mapFunction ); + } +} diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/SimpleRelationship.java b/driver/src/main/java/org/neo4j/driver/internal/InternalRelationship.java similarity index 70% rename from driver/src/main/java/org/neo4j/driver/v1/internal/SimpleRelationship.java rename to driver/src/main/java/org/neo4j/driver/internal/InternalRelationship.java index dce928acc3..a3031cd994 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/SimpleRelationship.java +++ b/driver/src/main/java/org/neo4j/driver/internal/InternalRelationship.java @@ -16,11 +16,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; +package org.neo4j.driver.internal; import java.util.Collections; import java.util.Map; +import org.neo4j.driver.internal.value.RelationshipValue; import org.neo4j.driver.v1.Identity; import org.neo4j.driver.v1.Relationship; import org.neo4j.driver.v1.Value; @@ -29,28 +30,28 @@ * {@link Relationship} implementation that directly contains type and properties * along with {@link Identity} values for start and end nodes. */ -public class SimpleRelationship extends SimpleEntity implements Relationship +public class InternalRelationship extends InternalEntity implements Relationship { private Identity start; private Identity end; private final String type; - public SimpleRelationship( long id, long start, long end, String type ) + public InternalRelationship( long id, long start, long end, String type ) { this( Identities.identity( id ), Identities.identity( start ), Identities.identity( end ), type, Collections.emptyMap() ); } - public SimpleRelationship( long id, long start, long end, String type, - Map properties ) + public InternalRelationship( long id, long start, long end, String type, + Map properties ) { this( Identities.identity( id ), Identities.identity( start ), Identities.identity( end ), type, properties ); } - public SimpleRelationship( Identity id, Identity start, Identity end, String type, - Map properties ) + public InternalRelationship( Identity id, Identity start, Identity end, String type, + Map properties ) { super( id, properties ); this.start = start; @@ -58,6 +59,12 @@ public SimpleRelationship( Identity id, Identity start, Identity end, String typ this.type = type; } + @Override + public boolean hasType( String relationshipType ) + { + return type().equals( relationshipType ); + } + /** Modify the start/end identities of this relationship */ public void setStartAndEnd( Identity start, Identity end ) { @@ -83,9 +90,15 @@ public String type() return type; } + @Override + public Value asValue() + { + return new RelationshipValue( this ); + } + @Override public String toString() { - return "relationship<" + identity() + '>'; + return String.format( "relationship<%s>", identity() ); } } diff --git a/driver/src/main/java/org/neo4j/driver/internal/InternalResult.java b/driver/src/main/java/org/neo4j/driver/internal/InternalResult.java new file mode 100644 index 0000000000..607b263745 --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/InternalResult.java @@ -0,0 +1,239 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.neo4j.driver.v1.Function; +import org.neo4j.driver.v1.Record; +import org.neo4j.driver.v1.RecordAccessor; +import org.neo4j.driver.v1.Result; +import org.neo4j.driver.v1.ResultSummary; +import org.neo4j.driver.v1.Value; +import org.neo4j.driver.v1.exceptions.ClientException; + +import static java.util.Collections.emptyList; + +import static org.neo4j.driver.v1.Records.recordAsIs; + +public class InternalResult extends InternalRecordAccessor implements Result +{ + private final List keys; + private final Iterator iter; + private final ResultSummary summary; + + private boolean open = true; + private Record current = null; + private long position = -1; + + public InternalResult( List keys, List body, ResultSummary summary ) + { + this.keys = keys; + this.iter = body.iterator(); + this.summary = summary; + } + + @Override + public boolean isOpen() + { + return open; + } + + public Value value( int index ) + { + return record().value( index ); + } + + public Value value( String key ) + { + return record().value( key ); + } + + @Override + public boolean containsKey( String key ) + { + return keys.contains( key ); + } + + @Override + public String key( int index ) + { + return record().key( index ); + } + + @Override + public int index( String key ) + { + return record().index( key ); + } + + public List keys() + { + return keys; + } + + private Value throwNoRecord() + { + throw new ClientException( + "In order to access fields of a record in a result, " + + "you must first call next() to point the result to the next record in the result stream." + ); + } + + @Override + public Record record() + { + assertOpen(); + if ( current == null ) + { + throwNoRecord(); + } + return current; + } + + @Override + public long position() + { + assertOpen(); + return position; + } + + @Override + public boolean atEnd() + { + assertOpen(); + return !iter.hasNext(); + } + + @Override + public boolean next() + { + assertOpen(); + if ( iter.hasNext() ) + { + current = iter.next(); + position += 1; + return true; + } + else + { + return false; + } + } + + @Override + public long skip( long elements ) + { + if ( elements < 0 ) + { + throw new IllegalArgumentException( "Cannot skip negative number of elements" ); + } + else + { + int skipped = 0; + while ( skipped < elements && next() ) + { + skipped += 1; + } + return skipped; + } + } + + @Override + public boolean first() + { + long pos = position(); + return pos < 0 ? next() : pos == 0; + } + + @Override + public boolean single() + { + return first() && atEnd(); + } + + @Override + public List retain() + { + return retain( recordAsIs() ); + } + + @Override + public List retain( Function mapFunction ) + { + if ( isEmpty() ) + { + assertOpen(); + return emptyList(); + } + else if ( first() ) + { + List result = new ArrayList<>(); + do + { + result.add( mapFunction.apply( this ) ); + } + while ( next() ); + return result; + } + else + { + throw new + ClientException( String.format( + "Can't retain records when cursor is not pointing at the first record (currently at position %d)", + position ) ); + } + } + + @SuppressWarnings("StatementWithEmptyBody") + @Override + public ResultSummary summarize() + { + while ( next() ) ; + return summary; + } + + @Override + public void close() + { + if ( open ) + { + open = false; + } + else + { + throw new IllegalStateException( "Already closed" ); + } + } + + private boolean isEmpty() + { + return position == -1 && !iter.hasNext(); + } + + private void assertOpen() + { + if ( !open ) + { + throw new IllegalStateException( "Cursor already closed" ); + } + } +} diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/StandardSession.java b/driver/src/main/java/org/neo4j/driver/internal/InternalSession.java similarity index 75% rename from driver/src/main/java/org/neo4j/driver/v1/internal/StandardSession.java rename to driver/src/main/java/org/neo4j/driver/internal/InternalSession.java index e2c228e688..180450aff2 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/StandardSession.java +++ b/driver/src/main/java/org/neo4j/driver/internal/InternalSession.java @@ -16,20 +16,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; +package org.neo4j.driver.internal; import java.util.Map; +import org.neo4j.driver.internal.spi.Connection; +import org.neo4j.driver.internal.summary.ResultBuilder; +import org.neo4j.driver.internal.types.InternalTypeSystem; import org.neo4j.driver.v1.Result; import org.neo4j.driver.v1.Session; import org.neo4j.driver.v1.Statement; import org.neo4j.driver.v1.Transaction; +import org.neo4j.driver.v1.TypeSystem; import org.neo4j.driver.v1.Value; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.spi.Connection; -import org.neo4j.driver.v1.internal.summary.ResultBuilder; -public class StandardSession implements Session +public class InternalSession implements Session { private final Connection connection; @@ -46,17 +48,17 @@ public void run() private Transaction currentTransaction; private boolean isOpen = true; - public StandardSession( Connection connection ) + public InternalSession( Connection connection ) { this.connection = connection; } @Override - public Result run( String statementText, Map parameters ) + public Result run( String statementText, Map statementParameters ) { ensureNoOpenTransaction(); - ResultBuilder resultBuilder = new ResultBuilder( statementText, parameters ); - connection.run( statementText, parameters, resultBuilder ); + ResultBuilder resultBuilder = new ResultBuilder( statementText, statementParameters ); + connection.run( statementText, statementParameters, resultBuilder ); connection.pullAll( resultBuilder ); connection.sync(); @@ -64,15 +66,15 @@ public Result run( String statementText, Map parameters ) } @Override - public Result run( String statementText ) + public Result run( String statementTemplate ) { - return run( statementText, ParameterSupport.NO_PARAMETERS ); + return run( statementTemplate, ParameterSupport.NO_PARAMETERS ); } @Override public Result run( Statement statement ) { - return run( statement.text(), statement.parameters() ); + return run( statement.template(), statement.parameters() ); } @Override @@ -110,7 +112,13 @@ public void close() public Transaction beginTransaction() { ensureNoOpenTransaction(); - return currentTransaction = new StandardTransaction( connection, txCleanup ); + return currentTransaction = new InternalTransaction( connection, txCleanup ); + } + + @Override + public TypeSystem typeSystem() + { + return InternalTypeSystem.TYPE_SYSTEM; } private void ensureNoOpenTransaction() diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/StandardTransaction.java b/driver/src/main/java/org/neo4j/driver/internal/InternalTransaction.java similarity index 80% rename from driver/src/main/java/org/neo4j/driver/v1/internal/StandardTransaction.java rename to driver/src/main/java/org/neo4j/driver/internal/InternalTransaction.java index 3da4a606c3..79da7d8d4d 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/StandardTransaction.java +++ b/driver/src/main/java/org/neo4j/driver/internal/InternalTransaction.java @@ -16,21 +16,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; +package org.neo4j.driver.internal; import java.util.Collections; import java.util.Map; +import org.neo4j.driver.internal.spi.Connection; +import org.neo4j.driver.internal.summary.ResultBuilder; +import org.neo4j.driver.internal.types.InternalTypeSystem; import org.neo4j.driver.v1.Result; import org.neo4j.driver.v1.Statement; import org.neo4j.driver.v1.Transaction; +import org.neo4j.driver.v1.TypeSystem; import org.neo4j.driver.v1.Value; import org.neo4j.driver.v1.exceptions.ClientException; import org.neo4j.driver.v1.exceptions.Neo4jException; -import org.neo4j.driver.v1.internal.spi.Connection; -import org.neo4j.driver.v1.internal.summary.ResultBuilder; -public class StandardTransaction implements Transaction +public class InternalTransaction implements Transaction { private final Connection conn; private final Runnable cleanup; @@ -40,7 +42,7 @@ private enum State /** The transaction is running with no explicit success or failure marked */ ACTIVE, - /** Running, user marked for success, meaning it'll get committed */ + /** Running, user marked for success, meaning it'll value committed */ MARKED_SUCCESS, /** User marked as failed, meaning it'll be rolled back. */ @@ -61,12 +63,12 @@ private enum State private State state = State.ACTIVE; - public StandardTransaction( Connection conn, Runnable cleanup ) + public InternalTransaction( Connection conn, Runnable cleanup ) { this.conn = conn; this.cleanup = cleanup; - // Note there is no sync here, so this will just get queued locally + // Note there is no sync here, so this will just value queued locally conn.run( "BEGIN", Collections.emptyMap(), null ); conn.discardAll(); } @@ -118,14 +120,14 @@ else if ( state == State.MARKED_FAILED || state == State.ACTIVE ) @Override @SuppressWarnings( "unchecked" ) - public Result run( String statementText, Map parameters ) + public Result run( String statementText, Map statementParameters ) { ensureNotFailed(); try { - ResultBuilder resultBuilder = new ResultBuilder( statementText, parameters ); - conn.run( statementText, parameters, resultBuilder ); + ResultBuilder resultBuilder = new ResultBuilder( statementText, statementParameters ); + conn.run( statementText, statementParameters, resultBuilder ); conn.pullAll( resultBuilder ); conn.sync(); return resultBuilder.build(); @@ -138,15 +140,15 @@ public Result run( String statementText, Map parameters ) } @Override - public Result run( String statementText ) + public Result run( String statementTemplate ) { - return run( statementText, ParameterSupport.NO_PARAMETERS ); + return run( statementTemplate, ParameterSupport.NO_PARAMETERS ); } @Override public Result run( Statement statement ) { - return run( statement.text(), statement.parameters() ); + return run( statement.template(), statement.parameters() ); } @Override @@ -166,4 +168,10 @@ private void ensureNotFailed() ); } } + + @Override + public TypeSystem typeSystem() + { + return InternalTypeSystem.TYPE_SYSTEM; + } } diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/ParameterSupport.java b/driver/src/main/java/org/neo4j/driver/internal/ParameterSupport.java similarity index 93% rename from driver/src/main/java/org/neo4j/driver/v1/internal/ParameterSupport.java rename to driver/src/main/java/org/neo4j/driver/internal/ParameterSupport.java index eebaa68b4f..cd2c226a63 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/ParameterSupport.java +++ b/driver/src/main/java/org/neo4j/driver/internal/ParameterSupport.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; +package org.neo4j.driver.internal; import java.util.Collections; import java.util.Map; @@ -25,7 +25,7 @@ public final class ParameterSupport { - public static final Map NO_PARAMETERS = Collections.emptyMap(); + public static final Map NO_PARAMETERS = Collections.emptyMap(); private ParameterSupport() { diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/Version.java b/driver/src/main/java/org/neo4j/driver/internal/Version.java similarity index 97% rename from driver/src/main/java/org/neo4j/driver/v1/internal/Version.java rename to driver/src/main/java/org/neo4j/driver/internal/Version.java index 49fafe958c..cc690ca0e5 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/Version.java +++ b/driver/src/main/java/org/neo4j/driver/internal/Version.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; +package org.neo4j.driver.internal; import org.neo4j.driver.v1.Session; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/AllOrNothingChannel.java b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/AllOrNothingChannel.java similarity index 96% rename from driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/AllOrNothingChannel.java rename to driver/src/main/java/org/neo4j/driver/internal/connector/socket/AllOrNothingChannel.java index 222fdb8b29..c6cd23f8e9 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/AllOrNothingChannel.java +++ b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/AllOrNothingChannel.java @@ -16,15 +16,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; +package org.neo4j.driver.internal.connector.socket; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.channels.SocketChannel; +import org.neo4j.driver.internal.util.BytePrinter; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.util.BytePrinter; /** * Wraps a regular socket channel such that read and write will not return until the full buffers given have been sent diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/ChunkedInput.java b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/ChunkedInput.java similarity index 98% rename from driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/ChunkedInput.java rename to driver/src/main/java/org/neo4j/driver/internal/connector/socket/ChunkedInput.java index 54d97352c6..2e00606f7b 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/ChunkedInput.java +++ b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/ChunkedInput.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; +package org.neo4j.driver.internal.connector.socket; import java.io.IOException; import java.nio.ByteBuffer; @@ -24,9 +24,9 @@ import java.nio.channels.ClosedByInterruptException; import java.nio.channels.ReadableByteChannel; +import org.neo4j.driver.internal.packstream.PackInput; +import org.neo4j.driver.internal.util.BytePrinter; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.packstream.PackInput; -import org.neo4j.driver.v1.internal.util.BytePrinter; import static java.lang.Math.min; @@ -178,7 +178,7 @@ private int freeSpace() } /** - * Return the size of bytes in a buffer. + * Return the width of bytes in a buffer. * E.g. Given a buffer with pointers 0 <= position <= limit <= capacity, * Buffer: | 0, 0, 1, 2, 3, 4, 0, 0, 0, 0, 0 | * | | | | diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/ChunkedOutput.java b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/ChunkedOutput.java similarity index 97% rename from driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/ChunkedOutput.java rename to driver/src/main/java/org/neo4j/driver/internal/connector/socket/ChunkedOutput.java index aa0e726233..281f350783 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/ChunkedOutput.java +++ b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/ChunkedOutput.java @@ -16,14 +16,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; +package org.neo4j.driver.internal.connector.socket; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; +import org.neo4j.driver.internal.packstream.PackOutput; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.packstream.PackOutput; import static java.lang.Math.max; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/LoggingByteChannel.java b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/LoggingByteChannel.java similarity index 92% rename from driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/LoggingByteChannel.java rename to driver/src/main/java/org/neo4j/driver/internal/connector/socket/LoggingByteChannel.java index d63ea15b4d..ebaa187038 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/LoggingByteChannel.java +++ b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/LoggingByteChannel.java @@ -16,14 +16,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; +package org.neo4j.driver.internal.connector.socket; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; -import org.neo4j.driver.v1.internal.spi.Logger; -import org.neo4j.driver.v1.internal.util.BytePrinter; +import org.neo4j.driver.internal.spi.Logger; +import org.neo4j.driver.internal.util.BytePrinter; /** * Basically it is a wrapper to a {@link ByteChannel} with logging enabled to record bytes sent and received over the diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/LoggingResponseHandler.java b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/LoggingResponseHandler.java similarity index 86% rename from driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/LoggingResponseHandler.java rename to driver/src/main/java/org/neo4j/driver/internal/connector/socket/LoggingResponseHandler.java index 0db84a136e..bfa78796d6 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/LoggingResponseHandler.java +++ b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/LoggingResponseHandler.java @@ -16,18 +16,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; +package org.neo4j.driver.internal.connector.socket; import java.util.Arrays; import java.util.Map; +import org.neo4j.driver.internal.spi.Logger; import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.spi.Logger; -import static org.neo4j.driver.v1.internal.messaging.AckFailureMessage.ACK_FAILURE; -import static org.neo4j.driver.v1.internal.messaging.DiscardAllMessage.DISCARD_ALL; -import static org.neo4j.driver.v1.internal.messaging.IgnoredMessage.IGNORED; -import static org.neo4j.driver.v1.internal.messaging.PullAllMessage.PULL_ALL; +import static org.neo4j.driver.internal.messaging.AckFailureMessage.ACK_FAILURE; +import static org.neo4j.driver.internal.messaging.DiscardAllMessage.DISCARD_ALL; +import static org.neo4j.driver.internal.messaging.IgnoredMessage.IGNORED; +import static org.neo4j.driver.internal.messaging.PullAllMessage.PULL_ALL; public class LoggingResponseHandler extends SocketResponseHandler { diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SSLContextFactory.java b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/SSLContextFactory.java similarity index 95% rename from driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SSLContextFactory.java rename to driver/src/main/java/org/neo4j/driver/internal/connector/socket/SSLContextFactory.java index 96c48877da..4df77b71c0 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SSLContextFactory.java +++ b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/SSLContextFactory.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; +package org.neo4j.driver.internal.connector.socket; import java.io.IOException; import java.security.GeneralSecurityException; @@ -28,7 +28,7 @@ import org.neo4j.driver.v1.Config; -import static org.neo4j.driver.v1.internal.util.CertificateTool.loadX509Cert; +import static org.neo4j.driver.internal.util.CertificateTool.loadX509Cert; class SSLContextFactory { diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SSLSocketChannel.java b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/SSLSocketChannel.java similarity index 97% rename from driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SSLSocketChannel.java rename to driver/src/main/java/org/neo4j/driver/internal/connector/socket/SSLSocketChannel.java index 019ab3c7d5..0c0733587d 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SSLSocketChannel.java +++ b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/SSLSocketChannel.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; +package org.neo4j.driver.internal.connector.socket; import java.io.IOException; import java.nio.ByteBuffer; @@ -30,10 +30,10 @@ import javax.net.ssl.SSLEngineResult.Status; import javax.net.ssl.SSLSession; +import org.neo4j.driver.internal.spi.Logger; +import org.neo4j.driver.internal.util.BytePrinter; import org.neo4j.driver.v1.Config.TlsAuthenticationConfig; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.spi.Logger; -import org.neo4j.driver.v1.internal.util.BytePrinter; import static javax.net.ssl.SSLEngineResult.HandshakeStatus.FINISHED; import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING; @@ -42,7 +42,7 @@ * A blocking SSL socket channel. * * When debugging, we could enable JSSE system debugging by setting system property: - * {@code -Djavax.net.debug=all} to get more information about handshake messages and other operations underway. + * {@code -Djavax.net.debug=all} to value more information about handshake messages and other operations underway. * * References: * http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#SSLENG @@ -122,7 +122,7 @@ private void runSSLHandShake() throws IOException handshakeStatus = runDelegatedTasks(); break; case NEED_UNWRAP: - // Unwrap the ssl packet to get ssl handshake information + // Unwrap the ssl packet to value ssl handshake information handshakeStatus = unwrap( null ); plainIn.clear(); break; @@ -195,7 +195,7 @@ private HandshakeStatus unwrap( ByteBuffer buffer ) throws IOException /* In normal situations, enlarging buffers should happen very very rarely, as usually, the initial size for application buffer and network buffer is greater than 1024 * 10, and by using ChunkedInput and ChunkedOutput, the chunks are limited to 8192. - So we should not get any enlarging buffer request in most cases. */ + So we should not value any enlarging buffer request in most cases. */ switch ( status ) { case OK: diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketClient.java b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketClient.java similarity index 96% rename from driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketClient.java rename to driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketClient.java index 362c094ace..6e81ab464c 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketClient.java +++ b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketClient.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; +package org.neo4j.driver.internal.connector.socket; import java.io.IOException; import java.net.ConnectException; @@ -28,11 +28,11 @@ import java.security.GeneralSecurityException; import java.util.List; +import org.neo4j.driver.internal.messaging.Message; +import org.neo4j.driver.internal.messaging.MessageFormat; +import org.neo4j.driver.internal.spi.Logger; import org.neo4j.driver.v1.Config; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.messaging.Message; -import org.neo4j.driver.v1.internal.spi.Logger; -import org.neo4j.driver.v1.internal.messaging.MessageFormat; import static java.nio.ByteOrder.*; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketConnection.java b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketConnection.java similarity index 86% rename from driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketConnection.java rename to driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketConnection.java index f4f137d297..9010a977f4 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketConnection.java +++ b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketConnection.java @@ -16,26 +16,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; +package org.neo4j.driver.internal.connector.socket; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.LinkedList; import java.util.Map; +import org.neo4j.driver.internal.messaging.AckFailureMessage; +import org.neo4j.driver.internal.messaging.InitMessage; +import org.neo4j.driver.internal.messaging.Message; +import org.neo4j.driver.internal.messaging.PullAllMessage; +import org.neo4j.driver.internal.messaging.RunMessage; +import org.neo4j.driver.internal.spi.Connection; +import org.neo4j.driver.internal.spi.Logger; +import org.neo4j.driver.internal.spi.StreamCollector; import org.neo4j.driver.v1.Config; import org.neo4j.driver.v1.Value; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.messaging.AckFailureMessage; -import org.neo4j.driver.v1.internal.messaging.InitMessage; -import org.neo4j.driver.v1.internal.messaging.Message; -import org.neo4j.driver.v1.internal.messaging.RunMessage; -import org.neo4j.driver.v1.internal.spi.Connection; -import org.neo4j.driver.v1.internal.spi.Logger; -import org.neo4j.driver.v1.internal.spi.StreamCollector; -import org.neo4j.driver.v1.internal.messaging.PullAllMessage; -import static org.neo4j.driver.v1.internal.messaging.DiscardAllMessage.DISCARD_ALL; +import static org.neo4j.driver.internal.messaging.DiscardAllMessage.DISCARD_ALL; public class SocketConnection implements Connection { @@ -67,7 +67,7 @@ public SocketConnection( String host, int port, Config config ) @Override public void init( String clientName ) { - // No need to sync, this'll get sent once regular communication starts + // No need to sync, this'll value sent once regular communication starts queueMessage( new InitMessage( clientName ) ); } @@ -109,7 +109,7 @@ public void sync() pendingMessages.clear(); if ( responseHandler.serverFailureOccurred() ) { - // Its enough to simply add the ack message to the outbound queue, it'll get sent + // Its enough to simply add the ack message to the outbound queue, it'll value sent // off as the first message the next time we need to sync with the database. queueMessage( new AckFailureMessage() ); throw responseHandler.serverFailure(); diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketConnector.java b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketConnector.java similarity index 84% rename from driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketConnector.java rename to driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketConnector.java index 4f682bfe08..1a381d2775 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketConnector.java +++ b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketConnector.java @@ -16,18 +16,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; +package org.neo4j.driver.internal.connector.socket; import java.net.URI; import java.util.Collection; +import java.util.Collections; +import org.neo4j.driver.internal.Version; +import org.neo4j.driver.internal.spi.Connection; +import org.neo4j.driver.internal.spi.Connector; import org.neo4j.driver.v1.Config; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.Version; -import org.neo4j.driver.v1.internal.spi.Connection; -import org.neo4j.driver.v1.internal.spi.Connector; - -import static java.util.Arrays.asList; public class SocketConnector implements Connector { @@ -49,6 +48,6 @@ public Connection connect( URI sessionURI, Config config ) throws ClientExceptio @Override public Collection supportedSchemes() { - return asList( Config.SCHEME ); + return Collections.singletonList( Config.SCHEME ); } } diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketProtocol.java b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketProtocol.java similarity index 80% rename from driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketProtocol.java rename to driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketProtocol.java index 6a1d3a6847..261d3720df 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketProtocol.java +++ b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketProtocol.java @@ -16,10 +16,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; +package org.neo4j.driver.internal.connector.socket; -import org.neo4j.driver.v1.internal.messaging.MessageFormat.Reader; -import org.neo4j.driver.v1.internal.messaging.MessageFormat.Writer; +import org.neo4j.driver.internal.messaging.MessageFormat.Reader; +import org.neo4j.driver.internal.messaging.MessageFormat.Writer; public interface SocketProtocol { diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketProtocolV1.java b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketProtocolV1.java similarity index 83% rename from driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketProtocolV1.java rename to driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketProtocolV1.java index 2ab63df3fd..0918caec76 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketProtocolV1.java +++ b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketProtocolV1.java @@ -16,15 +16,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; +package org.neo4j.driver.internal.connector.socket; import java.io.IOException; import java.nio.channels.ByteChannel; -import org.neo4j.driver.v1.internal.messaging.MessageFormat; -import org.neo4j.driver.v1.internal.messaging.MessageFormat.Reader; -import org.neo4j.driver.v1.internal.messaging.MessageFormat.Writer; -import org.neo4j.driver.v1.internal.messaging.PackStreamMessageFormatV1; +import org.neo4j.driver.internal.messaging.MessageFormat; +import org.neo4j.driver.internal.messaging.MessageFormat.Reader; +import org.neo4j.driver.internal.messaging.MessageFormat.Writer; +import org.neo4j.driver.internal.messaging.PackStreamMessageFormatV1; public class SocketProtocolV1 implements SocketProtocol { diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketResponseHandler.java b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketResponseHandler.java similarity index 84% rename from driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketResponseHandler.java rename to driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketResponseHandler.java index ffb277ac90..9dd710ebec 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/SocketResponseHandler.java +++ b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketResponseHandler.java @@ -16,23 +16,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; +package org.neo4j.driver.internal.connector.socket; import java.util.HashMap; import java.util.Map; +import org.neo4j.driver.internal.messaging.MessageHandler; +import org.neo4j.driver.internal.spi.StreamCollector; +import org.neo4j.driver.internal.summary.InternalNotification; +import org.neo4j.driver.internal.summary.InternalPlan; +import org.neo4j.driver.internal.summary.InternalProfiledPlan; +import org.neo4j.driver.internal.summary.InternalUpdateStatistics; import org.neo4j.driver.v1.StatementType; import org.neo4j.driver.v1.Value; import org.neo4j.driver.v1.exceptions.ClientException; import org.neo4j.driver.v1.exceptions.DatabaseException; import org.neo4j.driver.v1.exceptions.Neo4jException; import org.neo4j.driver.v1.exceptions.TransientException; -import org.neo4j.driver.v1.internal.summary.SimpleNotification; -import org.neo4j.driver.v1.internal.summary.SimplePlan; -import org.neo4j.driver.v1.internal.summary.SimpleProfiledPlan; -import org.neo4j.driver.v1.internal.summary.SimpleUpdateStatistics; -import org.neo4j.driver.v1.internal.messaging.MessageHandler; -import org.neo4j.driver.v1.internal.spi.StreamCollector; public class SocketResponseHandler implements MessageHandler { @@ -108,7 +108,7 @@ private void collectNotifications( StreamCollector collector, Value notification { if ( notifications != null ) { - collector.notifications( notifications.javaList( SimpleNotification.VALUE_TO_NOTIFICATION ) ); + collector.notifications( notifications.asList( InternalNotification.VALUE_TO_NOTIFICATION ) ); } } @@ -116,7 +116,7 @@ private void collectPlan( StreamCollector collector, Value plan ) { if ( plan != null ) { - collector.plan( SimplePlan.EXPLAIN_PLAN_FROM_VALUE.apply( plan ) ); + collector.plan( InternalPlan.EXPLAIN_PLAN_FROM_VALUE.apply( plan ) ); } } @@ -124,7 +124,7 @@ private void collectProfile( StreamCollector collector, Value plan ) { if ( plan != null ) { - collector.profile( SimpleProfiledPlan.PROFILED_PLAN_FROM_VALUE.apply( plan ) ); + collector.profile( InternalProfiledPlan.PROFILED_PLAN_FROM_VALUE.apply( plan ) ); } } @@ -132,15 +132,15 @@ private void collectFields( StreamCollector collector, Value fieldValue ) { if (fieldValue != null) { - if ( fieldValue.size() > 0 ) + if ( !fieldValue.isEmpty() ) { - String[] fields = new String[(int) fieldValue.size()]; + String[] fields = new String[fieldValue.size()]; int idx = 0; - for ( Value value : fieldValue ) + for ( Value value : fieldValue.values() ) { - fields[idx++] = value.javaString(); + fields[idx++] = value.asString(); } - collector.fieldNames( fields ); + collector.keys( fields ); } } } @@ -149,7 +149,7 @@ private void collectType( StreamCollector collector, Value type ) { if ( type != null ) { - collector.statementType( StatementType.fromCode( type.javaString() ) ); + collector.statementType( StatementType.fromCode( type.asString() ) ); } } @@ -158,7 +158,7 @@ private void collectStatistics( StreamCollector collector, Value stats ) if ( stats != null ) { collector.statementStatistics( - new SimpleUpdateStatistics( + new InternalUpdateStatistics( statsValue( stats, "nodes-created" ), statsValue( stats, "nodes-deleted" ), statsValue( stats, "relationships-created" ), @@ -177,8 +177,8 @@ private void collectStatistics( StreamCollector collector, Value stats ) private int statsValue( Value stats, String name ) { - Value value = stats.get( name ); - return value == null ? 0 : value.javaInteger(); + Value value = stats.value( name ); + return value.isNull() ? 0 : value.asInt(); } @Override diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/TrustOnFirstUseTrustManager.java b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/TrustOnFirstUseTrustManager.java similarity index 97% rename from driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/TrustOnFirstUseTrustManager.java rename to driver/src/main/java/org/neo4j/driver/internal/connector/socket/TrustOnFirstUseTrustManager.java index ed4f50b343..2ca32a5e58 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/connector/socket/TrustOnFirstUseTrustManager.java +++ b/driver/src/main/java/org/neo4j/driver/internal/connector/socket/TrustOnFirstUseTrustManager.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; +package org.neo4j.driver.internal.connector.socket; import java.io.BufferedReader; import java.io.BufferedWriter; @@ -30,7 +30,7 @@ import javax.net.ssl.X509TrustManager; import javax.xml.bind.DatatypeConverter; -import static org.neo4j.driver.v1.internal.util.CertificateTool.X509CertToString; +import static org.neo4j.driver.internal.util.CertificateTool.X509CertToString; /** * References: diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/logging/ConsoleLogging.java b/driver/src/main/java/org/neo4j/driver/internal/logging/ConsoleLogging.java similarity index 96% rename from driver/src/main/java/org/neo4j/driver/v1/internal/logging/ConsoleLogging.java rename to driver/src/main/java/org/neo4j/driver/internal/logging/ConsoleLogging.java index 4f79d53234..52b995c3bf 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/logging/ConsoleLogging.java +++ b/driver/src/main/java/org/neo4j/driver/internal/logging/ConsoleLogging.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.logging; +package org.neo4j.driver.internal.logging; import java.text.DateFormat; import java.text.SimpleDateFormat; @@ -27,8 +27,8 @@ import java.util.logging.Level; import java.util.logging.LogRecord; -import org.neo4j.driver.v1.internal.spi.Logger; -import org.neo4j.driver.v1.internal.spi.Logging; +import org.neo4j.driver.internal.spi.Logger; +import org.neo4j.driver.internal.spi.Logging; /** * Print all the logging messages into {@link System#err}. diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/logging/DevNullLogger.java b/driver/src/main/java/org/neo4j/driver/internal/logging/DevNullLogger.java similarity index 93% rename from driver/src/main/java/org/neo4j/driver/v1/internal/logging/DevNullLogger.java rename to driver/src/main/java/org/neo4j/driver/internal/logging/DevNullLogger.java index 9c9e995f3a..a1aed773dd 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/logging/DevNullLogger.java +++ b/driver/src/main/java/org/neo4j/driver/internal/logging/DevNullLogger.java @@ -16,9 +16,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.logging; +package org.neo4j.driver.internal.logging; -import org.neo4j.driver.v1.internal.spi.Logger; +import org.neo4j.driver.internal.spi.Logger; public class DevNullLogger implements Logger { diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/logging/JULogger.java b/driver/src/main/java/org/neo4j/driver/internal/logging/JULogger.java similarity index 95% rename from driver/src/main/java/org/neo4j/driver/v1/internal/logging/JULogger.java rename to driver/src/main/java/org/neo4j/driver/internal/logging/JULogger.java index 5a18f9374f..0f391f50ec 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/logging/JULogger.java +++ b/driver/src/main/java/org/neo4j/driver/internal/logging/JULogger.java @@ -16,11 +16,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.logging; +package org.neo4j.driver.internal.logging; import java.util.logging.Level; -import org.neo4j.driver.v1.internal.spi.Logger; +import org.neo4j.driver.internal.spi.Logger; public class JULogger implements Logger { diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/logging/JULogging.java b/driver/src/main/java/org/neo4j/driver/internal/logging/JULogging.java similarity index 87% rename from driver/src/main/java/org/neo4j/driver/v1/internal/logging/JULogging.java rename to driver/src/main/java/org/neo4j/driver/internal/logging/JULogging.java index 55d7f703e0..ebf4904699 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/logging/JULogging.java +++ b/driver/src/main/java/org/neo4j/driver/internal/logging/JULogging.java @@ -16,12 +16,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.logging; +package org.neo4j.driver.internal.logging; import java.util.logging.Level; -import org.neo4j.driver.v1.internal.spi.Logger; -import org.neo4j.driver.v1.internal.spi.Logging; +import org.neo4j.driver.internal.spi.Logger; +import org.neo4j.driver.internal.spi.Logging; public class JULogging implements Logging { diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/AckFailureMessage.java b/driver/src/main/java/org/neo4j/driver/internal/messaging/AckFailureMessage.java similarity index 93% rename from driver/src/main/java/org/neo4j/driver/v1/internal/messaging/AckFailureMessage.java rename to driver/src/main/java/org/neo4j/driver/internal/messaging/AckFailureMessage.java index 79da698aa8..e6788a9a65 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/AckFailureMessage.java +++ b/driver/src/main/java/org/neo4j/driver/internal/messaging/AckFailureMessage.java @@ -16,12 +16,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.messaging; +package org.neo4j.driver.internal.messaging; import java.io.IOException; -import static java.lang.String.format; - /** * ACK_FAILURE request message *

@@ -48,7 +46,7 @@ public void dispatch( MessageHandler handler ) throws IOException @Override public String toString() { - return format( "[ACK_FAILURE]" ); + return "[ACK_FAILURE]"; } @Override diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/DiscardAllMessage.java b/driver/src/main/java/org/neo4j/driver/internal/messaging/DiscardAllMessage.java similarity index 96% rename from driver/src/main/java/org/neo4j/driver/v1/internal/messaging/DiscardAllMessage.java rename to driver/src/main/java/org/neo4j/driver/internal/messaging/DiscardAllMessage.java index 63cdcd2130..dd68454a64 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/DiscardAllMessage.java +++ b/driver/src/main/java/org/neo4j/driver/internal/messaging/DiscardAllMessage.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.messaging; +package org.neo4j.driver.internal.messaging; import java.io.IOException; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/FailureMessage.java b/driver/src/main/java/org/neo4j/driver/internal/messaging/FailureMessage.java similarity index 85% rename from driver/src/main/java/org/neo4j/driver/v1/internal/messaging/FailureMessage.java rename to driver/src/main/java/org/neo4j/driver/internal/messaging/FailureMessage.java index 19e03a1d75..2758087079 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/FailureMessage.java +++ b/driver/src/main/java/org/neo4j/driver/internal/messaging/FailureMessage.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.messaging; +package org.neo4j.driver.internal.messaging; import java.io.IOException; @@ -66,16 +66,9 @@ public boolean equals( Object o ) FailureMessage that = (FailureMessage) o; - if ( code != null ? !code.equals( that.code ) : that.code != null ) - { - return false; - } - if ( message != null ? !message.equals( that.message ) : that.message != null ) - { - return false; - } + return !(code != null ? !code.equals( that.code ) : that.code != null) && + !(message != null ? !message.equals( that.message ) : that.message != null); - return true; } @Override diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/IgnoredMessage.java b/driver/src/main/java/org/neo4j/driver/internal/messaging/IgnoredMessage.java similarity index 96% rename from driver/src/main/java/org/neo4j/driver/v1/internal/messaging/IgnoredMessage.java rename to driver/src/main/java/org/neo4j/driver/internal/messaging/IgnoredMessage.java index 664852e4c9..ecd4863407 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/IgnoredMessage.java +++ b/driver/src/main/java/org/neo4j/driver/internal/messaging/IgnoredMessage.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.messaging; +package org.neo4j.driver.internal.messaging; import java.io.IOException; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/InitMessage.java b/driver/src/main/java/org/neo4j/driver/internal/messaging/InitMessage.java similarity index 97% rename from driver/src/main/java/org/neo4j/driver/v1/internal/messaging/InitMessage.java rename to driver/src/main/java/org/neo4j/driver/internal/messaging/InitMessage.java index 7b1d1c1830..c0f9fafbf0 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/InitMessage.java +++ b/driver/src/main/java/org/neo4j/driver/internal/messaging/InitMessage.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.messaging; +package org.neo4j.driver.internal.messaging; import java.io.IOException; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/Message.java b/driver/src/main/java/org/neo4j/driver/internal/messaging/Message.java similarity index 86% rename from driver/src/main/java/org/neo4j/driver/v1/internal/messaging/Message.java rename to driver/src/main/java/org/neo4j/driver/internal/messaging/Message.java index b75e42ac01..cae9b23a6a 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/Message.java +++ b/driver/src/main/java/org/neo4j/driver/internal/messaging/Message.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.messaging; +package org.neo4j.driver.internal.messaging; import java.io.IOException; @@ -25,6 +25,6 @@ */ public interface Message { - public abstract void dispatch( MessageHandler handler ) throws IOException; + void dispatch( MessageHandler handler ) throws IOException; } diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/MessageFormat.java b/driver/src/main/java/org/neo4j/driver/internal/messaging/MessageFormat.java similarity index 96% rename from driver/src/main/java/org/neo4j/driver/v1/internal/messaging/MessageFormat.java rename to driver/src/main/java/org/neo4j/driver/internal/messaging/MessageFormat.java index fd038475eb..4ff2d0bc87 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/MessageFormat.java +++ b/driver/src/main/java/org/neo4j/driver/internal/messaging/MessageFormat.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.messaging; +package org.neo4j.driver.internal.messaging; import java.io.IOException; import java.nio.channels.ReadableByteChannel; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/MessageHandler.java b/driver/src/main/java/org/neo4j/driver/internal/messaging/MessageHandler.java similarity index 96% rename from driver/src/main/java/org/neo4j/driver/v1/internal/messaging/MessageHandler.java rename to driver/src/main/java/org/neo4j/driver/internal/messaging/MessageHandler.java index 4b5d18c7fd..0faf0ea01c 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/MessageHandler.java +++ b/driver/src/main/java/org/neo4j/driver/internal/messaging/MessageHandler.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.messaging; +package org.neo4j.driver.internal.messaging; import java.io.IOException; import java.util.Map; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/PackStreamMessageFormatV1.java b/driver/src/main/java/org/neo4j/driver/internal/messaging/PackStreamMessageFormatV1.java similarity index 75% rename from driver/src/main/java/org/neo4j/driver/v1/internal/messaging/PackStreamMessageFormatV1.java rename to driver/src/main/java/org/neo4j/driver/internal/messaging/PackStreamMessageFormatV1.java index e56b660bb9..e9b31909c4 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/PackStreamMessageFormatV1.java +++ b/driver/src/main/java/org/neo4j/driver/internal/messaging/PackStreamMessageFormatV1.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.messaging; +package org.neo4j.driver.internal.messaging; import java.io.IOException; import java.nio.channels.ReadableByteChannel; @@ -28,6 +28,24 @@ import java.util.List; import java.util.Map; +import org.neo4j.driver.internal.Identities; +import org.neo4j.driver.internal.InternalNode; +import org.neo4j.driver.internal.InternalPath; +import org.neo4j.driver.internal.InternalRelationship; +import org.neo4j.driver.internal.connector.socket.ChunkedInput; +import org.neo4j.driver.internal.connector.socket.ChunkedOutput; +import org.neo4j.driver.internal.packstream.BufferedChannelOutput; +import org.neo4j.driver.internal.packstream.PackInput; +import org.neo4j.driver.internal.packstream.PackOutput; +import org.neo4j.driver.internal.packstream.PackStream; +import org.neo4j.driver.internal.packstream.PackType; +import org.neo4j.driver.internal.util.Iterables; +import org.neo4j.driver.internal.value.InternalValue; +import org.neo4j.driver.internal.value.ListValue; +import org.neo4j.driver.internal.value.MapValue; +import org.neo4j.driver.internal.value.NodeValue; +import org.neo4j.driver.internal.value.PathValue; +import org.neo4j.driver.internal.value.RelationshipValue; import org.neo4j.driver.v1.Entity; import org.neo4j.driver.v1.Identity; import org.neo4j.driver.v1.Node; @@ -35,23 +53,6 @@ import org.neo4j.driver.v1.Relationship; import org.neo4j.driver.v1.Value; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.Identities; -import org.neo4j.driver.v1.internal.SimpleNode; -import org.neo4j.driver.v1.internal.SimplePath; -import org.neo4j.driver.v1.internal.SimpleRelationship; -import org.neo4j.driver.v1.internal.connector.socket.ChunkedInput; -import org.neo4j.driver.v1.internal.connector.socket.ChunkedOutput; -import org.neo4j.driver.v1.internal.packstream.BufferedChannelOutput; -import org.neo4j.driver.v1.internal.packstream.PackInput; -import org.neo4j.driver.v1.internal.packstream.PackOutput; -import org.neo4j.driver.v1.internal.packstream.PackStream; -import org.neo4j.driver.v1.internal.packstream.PackType; -import org.neo4j.driver.v1.internal.util.Iterables; -import org.neo4j.driver.v1.internal.value.ListValue; -import org.neo4j.driver.v1.internal.value.MapValue; -import org.neo4j.driver.v1.internal.value.NodeValue; -import org.neo4j.driver.v1.internal.value.PathValue; -import org.neo4j.driver.v1.internal.value.RelationshipValue; import static org.neo4j.driver.v1.Values.value; @@ -215,111 +216,115 @@ private void packRawMap( Map map ) throws IOException private void packValue( Value value ) throws IOException { - // TODO: Use switch on type constructor - if ( value.isNull() ) + switch ( ( (InternalValue) value ).typeConstructor() ) { - packer.packNull(); - } - else if ( value.isBoolean() ) - { - packer.pack( value.javaBoolean() ); - } - else if ( value.isInteger() ) - { - packer.pack( value.javaLong() ); - } - else if ( value.isFloat() ) - { - packer.pack( value.javaDouble() ); - } - else if ( value.isString() ) - { - packer.pack( value.javaString() ); - } - else if ( value.isMap() ) - { - packer.packMapHeader( (int) value.size() ); - for ( String s : value.keys() ) - { - packer.pack( s ); - packValue( value.get( s ) ); - } - } - else if ( value.isList() ) - { - packer.packListHeader( (int) value.size() ); - for ( Value item : value ) - { - packValue( item ); - } - } - else if ( value.isNode() ) - { - Node node = value.asNode(); - packNode( node ); - } - else if ( value.isRelationship() ) - { - Relationship rel = value.asRelationship(); - packer.packStructHeader( 5, RELATIONSHIP ); - packer.pack( rel.identity().asLong() ); - packer.pack( rel.start().asLong() ); - packer.pack( rel.end().asLong() ); + case NULL_TyCon: + packer.packNull(); + break; - packer.pack( rel.type() ); + case STRING_TyCon: + packer.pack( value.asString() ); + break; - packProperties( rel ); - } - else if ( value.isPath() ) - { - Path path = value.asPath(); - packer.packStructHeader( 3, PATH ); + case BOOLEAN_TyCon: + packer.pack( value.asBoolean() ); + break; - // Uniq nodes - Map nodeIdx = new LinkedHashMap<>(); - for ( Node node : path.nodes() ) - { - if( !nodeIdx.containsKey( node ) ) + case INTEGER_TyCon: + packer.pack( value.asLong() ); + break; + + case FLOAT_TyCon: + packer.pack( value.asDouble() ); + break; + + case MAP_TyCon: + packer.packMapHeader( value.size() ); + for ( String s : value.keys() ) { - nodeIdx.put( node, nodeIdx.size() ); + packer.pack( s ); + packValue( value.value( s ) ); } - } - packer.packListHeader( nodeIdx.size() ); - for ( Node node : nodeIdx.keySet() ) - { - packNode( node ); - } + break; - // Uniq rels - Map relIdx = new LinkedHashMap<>(); - for ( Relationship rel : path.relationships() ) - { - if( !relIdx.containsKey( rel ) ) + case LIST_TyCon: + packer.packListHeader( value.size() ); + for ( Value item : value.values() ) { - relIdx.put( rel, relIdx.size() + 1 ); + packValue( item ); } - } - packer.packListHeader( relIdx.size() ); - for ( Relationship rel : relIdx.keySet() ) - { - packer.packStructHeader( 3, UNBOUND_RELATIONSHIP ); - packer.pack( rel.identity().asLong() ); - packer.pack( rel.type() ); - packProperties( rel ); - } + break; - // Sequence - packer.packListHeader( (int) path.length() * 2 ); - for ( Path.Segment seg : path ) - { - Relationship rel = seg.relationship(); - packer.pack( rel.end().equals( seg.end() ) ? relIdx.get( rel ) : -relIdx.get( rel ) ); - packer.pack( nodeIdx.get( seg.end() ) ); - } - } - else - { - throw new UnsupportedOperationException( "Unknown type: " + value ); + case NODE_TyCon: + { + Node node = value.asNode(); + packNode( node ); + } + break; + + case RELATIONSHIP_TyCon: + { + Relationship rel = value.asRelationship(); + packer.packStructHeader( 5, RELATIONSHIP ); + packer.pack( rel.identity().asLong() ); + packer.pack( rel.start().asLong() ); + packer.pack( rel.end().asLong() ); + + packer.pack( rel.type() ); + + packProperties( rel ); + } + break; + + case PATH_TyCon: + Path path = value.asPath(); + packer.packStructHeader( 3, PATH ); + + // Unique nodes + Map nodeIdx = new LinkedHashMap<>(); + for ( Node node : path.nodes() ) + { + if ( !nodeIdx.containsKey( node ) ) + { + nodeIdx.put( node, nodeIdx.size() ); + } + } + packer.packListHeader( nodeIdx.size() ); + for ( Node node : nodeIdx.keySet() ) + { + packNode( node ); + } + + // Unique rels + Map relIdx = new LinkedHashMap<>(); + for ( Relationship rel : path.relationships() ) + { + if ( !relIdx.containsKey( rel ) ) + { + relIdx.put( rel, relIdx.size() + 1 ); + } + } + packer.packListHeader( relIdx.size() ); + for ( Relationship rel : relIdx.keySet() ) + { + packer.packStructHeader( 3, UNBOUND_RELATIONSHIP ); + packer.pack( rel.identity().asLong() ); + packer.pack( rel.type() ); + packProperties( rel ); + } + + // Sequence + packer.packListHeader( path.length() * 2 ); + for ( Path.Segment seg : path ) + { + Relationship rel = seg.relationship(); + packer.pack( rel.end().equals( seg.end() ) ? relIdx.get( rel ) : -relIdx.get( rel ) ); + packer.pack( nodeIdx.get( seg.end() ) ); + } + break; + + default: + throw new UnsupportedOperationException( "Unknown type: " + value ); } } @@ -361,12 +366,12 @@ private void packNode( Node node ) throws IOException private void packProperties( Entity entity ) throws IOException { - Iterable keys = entity.propertyKeys(); + Iterable keys = entity.keys(); packer.packMapHeader( entity.propertyCount() ); for ( String propKey : keys ) { packer.pack( propKey ); - packValue( entity.property( propKey ) ); + packValue( entity.value( propKey ) ); } } } @@ -442,8 +447,8 @@ private void unpackIgnoredMessage( MessageHandler output ) throws IOException private void unpackFailureMessage( MessageHandler output ) throws IOException { Map params = unpackMap(); - String code = params.get( "code" ).javaString(); - String message = params.get( "message" ).javaString(); + String code = params.get( "code" ).asString(); + String message = params.get( "message" ).asString(); output.handleFailureMessage( code, message ); onMessageComplete.run(); } @@ -546,10 +551,10 @@ private Value unpackRelationship() throws IOException String relType = unpacker.unpackString(); Map props = unpackMap(); - return new RelationshipValue( new SimpleRelationship( urn, startUrn, endUrn, relType, props ) ); + return new RelationshipValue( new InternalRelationship( urn, startUrn, endUrn, relType, props ) ); } - private SimpleNode unpackNode() throws IOException + private InternalNode unpackNode() throws IOException { long urn = unpacker.unpackLong(); @@ -567,7 +572,7 @@ private SimpleNode unpackNode() throws IOException props.put( key, unpackValue() ); } - return new SimpleNode( urn, labels, props ); + return new InternalNode( urn, labels, props ); } private Value unpackPath() throws IOException @@ -582,7 +587,7 @@ private Value unpackPath() throws IOException } // List of unique relationships, without start/end information - SimpleRelationship[] uniqRels = new SimpleRelationship[(int) unpacker.unpackListHeader()]; + InternalRelationship[] uniqRels = new InternalRelationship[(int) unpacker.unpackListHeader()]; for ( int i = 0; i < uniqRels.length; i++ ) { ensureCorrectStructSize( "RELATIONSHIP", 3, unpacker.unpackStructHeader() ); @@ -590,7 +595,7 @@ private Value unpackPath() throws IOException Identity urn = Identities.identity( unpacker.unpackLong() ); String relType = unpacker.unpackString(); Map props = unpackMap(); - uniqRels[i] = new SimpleRelationship( urn, null, null, relType, props ); + uniqRels[i] = new InternalRelationship( urn, null, null, relType, props ); } // Path sequence @@ -603,7 +608,7 @@ private Value unpackPath() throws IOException Node prevNode = uniqNodes[0], nextNode; // Start node is always 0, and isn't encoded in the sequence nodes[0] = prevNode; - SimpleRelationship rel; + InternalRelationship rel; for ( int i = 0; i < segments.length; i++ ) { int relIdx = (int) unpacker.unpackLong(); @@ -622,10 +627,10 @@ private Value unpackPath() throws IOException nodes[i+1] = nextNode; rels[i] = rel; - segments[i] = new SimplePath.SelfContainedSegment( prevNode, rel, nextNode ); + segments[i] = new InternalPath.SelfContainedSegment( prevNode, rel, nextNode ); prevNode = nextNode; } - return new PathValue( new SimplePath( Arrays.asList( segments ), Arrays.asList( nodes ), Arrays.asList( rels ) ) ); + return new PathValue( new InternalPath( Arrays.asList( segments ), Arrays.asList( nodes ), Arrays.asList( rels ) ) ); } private void ensureCorrectStructSize( String structName, int expected, long actual ) diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/PullAllMessage.java b/driver/src/main/java/org/neo4j/driver/internal/messaging/PullAllMessage.java similarity index 96% rename from driver/src/main/java/org/neo4j/driver/v1/internal/messaging/PullAllMessage.java rename to driver/src/main/java/org/neo4j/driver/internal/messaging/PullAllMessage.java index 2674244142..21fb47ac3e 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/PullAllMessage.java +++ b/driver/src/main/java/org/neo4j/driver/internal/messaging/PullAllMessage.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.messaging; +package org.neo4j.driver.internal.messaging; import java.io.IOException; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/RecordMessage.java b/driver/src/main/java/org/neo4j/driver/internal/messaging/RecordMessage.java similarity index 90% rename from driver/src/main/java/org/neo4j/driver/v1/internal/messaging/RecordMessage.java rename to driver/src/main/java/org/neo4j/driver/internal/messaging/RecordMessage.java index 86f5e38d98..6a23a83589 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/RecordMessage.java +++ b/driver/src/main/java/org/neo4j/driver/internal/messaging/RecordMessage.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.messaging; +package org.neo4j.driver.internal.messaging; import java.io.IOException; import java.util.Arrays; @@ -58,12 +58,7 @@ public boolean equals( Object o ) RecordMessage that = (RecordMessage) o; - if ( !Arrays.equals( fields, that.fields ) ) - { - return false; - } - - return true; + return Arrays.equals( fields, that.fields ); } @Override diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/RunMessage.java b/driver/src/main/java/org/neo4j/driver/internal/messaging/RunMessage.java similarity index 85% rename from driver/src/main/java/org/neo4j/driver/v1/internal/messaging/RunMessage.java rename to driver/src/main/java/org/neo4j/driver/internal/messaging/RunMessage.java index 051750183e..e9132b1e43 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/RunMessage.java +++ b/driver/src/main/java/org/neo4j/driver/internal/messaging/RunMessage.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.messaging; +package org.neo4j.driver.internal.messaging; import java.io.IOException; import java.util.Map; @@ -68,16 +68,9 @@ public boolean equals( Object o ) RunMessage that = (RunMessage) o; - if ( parameters != null ? !parameters.equals( that.parameters ) : that.parameters != null ) - { - return false; - } - if ( statement != null ? !statement.equals( that.statement ) : that.statement != null ) - { - return false; - } + return !(parameters != null ? !parameters.equals( that.parameters ) : that.parameters != null) && + !(statement != null ? !statement.equals( that.statement ) : that.statement != null); - return true; } @Override diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/SuccessMessage.java b/driver/src/main/java/org/neo4j/driver/internal/messaging/SuccessMessage.java similarity index 97% rename from driver/src/main/java/org/neo4j/driver/v1/internal/messaging/SuccessMessage.java rename to driver/src/main/java/org/neo4j/driver/internal/messaging/SuccessMessage.java index cfb93b5e50..e7dffa99e9 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/messaging/SuccessMessage.java +++ b/driver/src/main/java/org/neo4j/driver/internal/messaging/SuccessMessage.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.messaging; +package org.neo4j.driver.internal.messaging; import java.io.IOException; import java.util.Map; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/packstream/BufferedChannelInput.java b/driver/src/main/java/org/neo4j/driver/internal/packstream/BufferedChannelInput.java similarity index 98% rename from driver/src/main/java/org/neo4j/driver/v1/internal/packstream/BufferedChannelInput.java rename to driver/src/main/java/org/neo4j/driver/internal/packstream/BufferedChannelInput.java index 1db8f0a9de..41fbee38b7 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/packstream/BufferedChannelInput.java +++ b/driver/src/main/java/org/neo4j/driver/internal/packstream/BufferedChannelInput.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.packstream; +package org.neo4j.driver.internal.packstream; import java.io.IOException; import java.nio.ByteBuffer; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/packstream/BufferedChannelOutput.java b/driver/src/main/java/org/neo4j/driver/internal/packstream/BufferedChannelOutput.java similarity index 98% rename from driver/src/main/java/org/neo4j/driver/v1/internal/packstream/BufferedChannelOutput.java rename to driver/src/main/java/org/neo4j/driver/internal/packstream/BufferedChannelOutput.java index d9c1aad06c..62ee13379e 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/packstream/BufferedChannelOutput.java +++ b/driver/src/main/java/org/neo4j/driver/internal/packstream/BufferedChannelOutput.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.packstream; +package org.neo4j.driver.internal.packstream; import java.io.IOException; import java.nio.ByteBuffer; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/packstream/PackInput.java b/driver/src/main/java/org/neo4j/driver/internal/packstream/PackInput.java similarity index 97% rename from driver/src/main/java/org/neo4j/driver/v1/internal/packstream/PackInput.java rename to driver/src/main/java/org/neo4j/driver/internal/packstream/PackInput.java index ec212233d7..c01550d9d1 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/packstream/PackInput.java +++ b/driver/src/main/java/org/neo4j/driver/internal/packstream/PackInput.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.packstream; +package org.neo4j.driver.internal.packstream; import java.io.IOException; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/packstream/PackOutput.java b/driver/src/main/java/org/neo4j/driver/internal/packstream/PackOutput.java similarity index 97% rename from driver/src/main/java/org/neo4j/driver/v1/internal/packstream/PackOutput.java rename to driver/src/main/java/org/neo4j/driver/internal/packstream/PackOutput.java index 4867a6d19a..4c41878ced 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/packstream/PackOutput.java +++ b/driver/src/main/java/org/neo4j/driver/internal/packstream/PackOutput.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.packstream; +package org.neo4j.driver.internal.packstream; import java.io.IOException; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/packstream/PackStream.java b/driver/src/main/java/org/neo4j/driver/internal/packstream/PackStream.java similarity index 95% rename from driver/src/main/java/org/neo4j/driver/v1/internal/packstream/PackStream.java rename to driver/src/main/java/org/neo4j/driver/internal/packstream/PackStream.java index aa9001d6eb..cc6e3374fd 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/packstream/PackStream.java +++ b/driver/src/main/java/org/neo4j/driver/internal/packstream/PackStream.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.packstream; +package org.neo4j.driver.internal.packstream; import java.io.IOException; import java.nio.channels.ReadableByteChannel; @@ -27,7 +27,7 @@ import static java.lang.Integer.toHexString; import static java.lang.String.format; -import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; /** * PackStream is a messaging serialisation format heavily inspired by MessagePack. @@ -286,26 +286,26 @@ public void pack( Object value ) throws IOException { if ( value == null ) { packNull(); } else if ( value instanceof Boolean ) { pack( (boolean) value ); } - else if ( value instanceof boolean[] ) { pack( asList( value ) ); } + else if ( value instanceof boolean[] ) { pack( singletonList( value ) ); } else if ( value instanceof Byte ) { pack( (byte) value ); } else if ( value instanceof byte[] ) { pack( (byte[]) value ); } else if ( value instanceof Short ) { pack( (short) value ); } - else if ( value instanceof short[] ) { pack( asList( value ) ); } + else if ( value instanceof short[] ) { pack( singletonList( value ) ); } else if ( value instanceof Integer ) { pack( (int) value ); } - else if ( value instanceof int[] ) { pack( asList( value ) ); } + else if ( value instanceof int[] ) { pack( singletonList( value ) ); } else if ( value instanceof Long ) { pack( (long) value ); } - else if ( value instanceof long[] ) { pack( asList( value ) ); } + else if ( value instanceof long[] ) { pack( singletonList( value ) ); } else if ( value instanceof Float ) { pack( (float) value ); } - else if ( value instanceof float[] ) { pack( asList( value ) ); } + else if ( value instanceof float[] ) { pack( singletonList( value ) ); } else if ( value instanceof Double ) { pack( (double) value ); } - else if ( value instanceof double[] ) { pack( asList( value ) ); } + else if ( value instanceof double[] ) { pack( singletonList( value ) ); } else if ( value instanceof Character ) { pack( Character.toString( (char) value ) ); } else if ( value instanceof char[] ) { pack( new String( (char[]) value ) ); } else if ( value instanceof String ) { pack( (String) value ); } - else if ( value instanceof String[] ) { pack( asList( value ) ); } + else if ( value instanceof String[] ) { pack( singletonList( value ) ); } else if ( value instanceof List ) { pack( (List) value ); } else if ( value instanceof Map ) { pack( (Map) value ); } - else { throw new Unpackable( format( "Cannot pack object %s", value ) );} + else { throw new UnPackable( format( "Cannot pack object %s", value ) );} } public void packBytesHeader( int size ) throws IOException @@ -695,7 +695,9 @@ public PackType peekNextType() throws IOException public static class PackstreamException extends IOException { - public PackstreamException( String message ) + private static final long serialVersionUID = -1491422133282345421L; + + protected PackstreamException( String message ) { super( message ); } @@ -703,6 +705,8 @@ public PackstreamException( String message ) public static class EndOfStream extends PackstreamException { + private static final long serialVersionUID = 5102836237108105603L; + public EndOfStream( String message ) { super( message ); @@ -711,6 +715,8 @@ public EndOfStream( String message ) public static class Overflow extends PackstreamException { + private static final long serialVersionUID = -923071934446993659L; + public Overflow( String message ) { super( message ); @@ -719,15 +725,19 @@ public Overflow( String message ) public static class Unexpected extends PackstreamException { + private static final long serialVersionUID = 5004685868740125469L; + public Unexpected( String message ) { super( message ); } } - public static class Unpackable extends PackstreamException + public static class UnPackable extends PackstreamException { - public Unpackable( String message ) + private static final long serialVersionUID = 2408740707769711365L; + + public UnPackable( String message ) { super( message ); } diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/packstream/PackType.java b/driver/src/main/java/org/neo4j/driver/internal/packstream/PackType.java similarity index 94% rename from driver/src/main/java/org/neo4j/driver/v1/internal/packstream/PackType.java rename to driver/src/main/java/org/neo4j/driver/internal/packstream/PackType.java index 919a090e79..37838f6ea5 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/packstream/PackType.java +++ b/driver/src/main/java/org/neo4j/driver/internal/packstream/PackType.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.packstream; +package org.neo4j.driver.internal.packstream; public enum PackType { diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/pool/Allocator.java b/driver/src/main/java/org/neo4j/driver/internal/pool/Allocator.java similarity index 94% rename from driver/src/main/java/org/neo4j/driver/v1/internal/pool/Allocator.java rename to driver/src/main/java/org/neo4j/driver/internal/pool/Allocator.java index 1154de6be5..24e8f4ceb0 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/pool/Allocator.java +++ b/driver/src/main/java/org/neo4j/driver/internal/pool/Allocator.java @@ -16,10 +16,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.pool; +package org.neo4j.driver.internal.pool; +import org.neo4j.driver.internal.util.Consumer; import org.neo4j.driver.v1.exceptions.Neo4jException; -import org.neo4j.driver.v1.internal.util.Consumer; public interface Allocator { diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/pool/StandardConnectionPool.java b/driver/src/main/java/org/neo4j/driver/internal/pool/InternalConnectionPool.java similarity index 92% rename from driver/src/main/java/org/neo4j/driver/v1/internal/pool/StandardConnectionPool.java rename to driver/src/main/java/org/neo4j/driver/internal/pool/InternalConnectionPool.java index bf220ffbbe..c59cf7f433 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/pool/StandardConnectionPool.java +++ b/driver/src/main/java/org/neo4j/driver/internal/pool/InternalConnectionPool.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.pool; +package org.neo4j.driver.internal.pool; import java.net.URI; import java.util.Arrays; @@ -27,14 +27,14 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; +import org.neo4j.driver.internal.connector.socket.SocketConnector; +import org.neo4j.driver.internal.spi.Connection; +import org.neo4j.driver.internal.spi.ConnectionPool; +import org.neo4j.driver.internal.spi.Connector; +import org.neo4j.driver.internal.util.Clock; +import org.neo4j.driver.internal.util.Consumer; import org.neo4j.driver.v1.Config; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.connector.socket.SocketConnector; -import org.neo4j.driver.v1.internal.spi.Connection; -import org.neo4j.driver.v1.internal.spi.ConnectionPool; -import org.neo4j.driver.v1.internal.spi.Connector; -import org.neo4j.driver.v1.internal.util.Clock; -import org.neo4j.driver.v1.internal.util.Consumer; /** * A basic connection pool that optimizes for threads being long-lived, acquiring/releasing many connections. @@ -48,7 +48,7 @@ *

* If threads are short-lived, this pool is not ideal. */ -public class StandardConnectionPool implements ConnectionPool +public class InternalConnectionPool implements ConnectionPool { /** * Map of scheme -> connector, this is what we use to establish new connections. @@ -68,12 +68,12 @@ public class StandardConnectionPool implements ConnectionPool private final Clock clock; private final Config config; - public StandardConnectionPool( Config config ) + public InternalConnectionPool( Config config ) { this( loadConnectors(), Clock.SYSTEM, config ); } - public StandardConnectionPool( Collection conns, Clock clock, Config config ) + public InternalConnectionPool( Collection conns, Clock clock, Config config ) { this.config = config; this.clock = clock; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/pool/PooledConnection.java b/driver/src/main/java/org/neo4j/driver/internal/pool/PooledConnection.java similarity index 94% rename from driver/src/main/java/org/neo4j/driver/v1/internal/pool/PooledConnection.java rename to driver/src/main/java/org/neo4j/driver/internal/pool/PooledConnection.java index 8ff47d93a3..2556ca06d7 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/pool/PooledConnection.java +++ b/driver/src/main/java/org/neo4j/driver/internal/pool/PooledConnection.java @@ -16,15 +16,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.pool; +package org.neo4j.driver.internal.pool; import java.util.Map; +import org.neo4j.driver.internal.spi.Connection; +import org.neo4j.driver.internal.spi.StreamCollector; +import org.neo4j.driver.internal.util.Consumer; import org.neo4j.driver.v1.Value; import org.neo4j.driver.v1.exceptions.Neo4jException; -import org.neo4j.driver.v1.internal.spi.Connection; -import org.neo4j.driver.v1.internal.spi.StreamCollector; -import org.neo4j.driver.v1.internal.util.Consumer; public class PooledConnection implements Connection { diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/pool/PooledConnectionValidator.java b/driver/src/main/java/org/neo4j/driver/internal/pool/PooledConnectionValidator.java similarity index 95% rename from driver/src/main/java/org/neo4j/driver/v1/internal/pool/PooledConnectionValidator.java rename to driver/src/main/java/org/neo4j/driver/internal/pool/PooledConnectionValidator.java index cf45b261ee..57df93f6f7 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/pool/PooledConnectionValidator.java +++ b/driver/src/main/java/org/neo4j/driver/internal/pool/PooledConnectionValidator.java @@ -16,13 +16,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.pool; +package org.neo4j.driver.internal.pool; import java.util.HashMap; import java.util.Map; +import org.neo4j.driver.internal.spi.StreamCollector; import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.spi.StreamCollector; /** * Validates connections - determining if they are ok to keep in the pool, or if they should be disposed of. diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/pool/ThreadCachingPool.java b/driver/src/main/java/org/neo4j/driver/internal/pool/ThreadCachingPool.java similarity index 97% rename from driver/src/main/java/org/neo4j/driver/v1/internal/pool/ThreadCachingPool.java rename to driver/src/main/java/org/neo4j/driver/internal/pool/ThreadCachingPool.java index 34e102f3f9..84c00cc914 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/pool/ThreadCachingPool.java +++ b/driver/src/main/java/org/neo4j/driver/internal/pool/ThreadCachingPool.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.pool; +package org.neo4j.driver.internal.pool; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; @@ -25,9 +25,9 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import org.neo4j.driver.internal.util.Clock; +import org.neo4j.driver.internal.util.Consumer; import org.neo4j.driver.v1.exceptions.Neo4jException; -import org.neo4j.driver.v1.internal.util.Clock; -import org.neo4j.driver.v1.internal.util.Consumer; import static java.util.concurrent.TimeUnit.MILLISECONDS; @@ -39,7 +39,7 @@ *

  • * The pool caches a reference for each thread who uses this pool to the resource that has ever been assigned to the * thread by the pool. - * Next time when the same thread wants to get a resource from the pool again, if the cached resource happens to be + * Next time when the same thread wants to value a resource from the pool again, if the cached resource happens to be * free, the same resource will be assigned directly to the thread to avoid searching from the global pool. *
  • *
  • @@ -96,7 +96,7 @@ public T acquire( long timeout, TimeUnit unit ) throws InterruptedException { long deadline = clock.millis() + unit.toMillis( timeout ); - // 1. Try and get an object from our local slot + // 1. Try and value an object from our local slot Slot slot = local.get(); if ( slot != null && slot.availableToClaimed() ) diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/pool/ValidationStrategy.java b/driver/src/main/java/org/neo4j/driver/internal/pool/ValidationStrategy.java similarity index 94% rename from driver/src/main/java/org/neo4j/driver/v1/internal/pool/ValidationStrategy.java rename to driver/src/main/java/org/neo4j/driver/internal/pool/ValidationStrategy.java index a55f40359e..4c2bbe9bf4 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/pool/ValidationStrategy.java +++ b/driver/src/main/java/org/neo4j/driver/internal/pool/ValidationStrategy.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.pool; +package org.neo4j.driver.internal.pool; public interface ValidationStrategy { diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/spi/Connection.java b/driver/src/main/java/org/neo4j/driver/internal/spi/Connection.java similarity index 92% rename from driver/src/main/java/org/neo4j/driver/v1/internal/spi/Connection.java rename to driver/src/main/java/org/neo4j/driver/internal/spi/Connection.java index 17a5452a58..04929969a0 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/spi/Connection.java +++ b/driver/src/main/java/org/neo4j/driver/internal/spi/Connection.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.spi; +package org.neo4j.driver.internal.spi; import java.util.Map; @@ -35,7 +35,7 @@ public interface Connection extends AutoCloseable void init( String clientName ); /** - * Queue up a run action. The collector will get called with metadata about the stream that will become available + * Queue up a run action. The collector will value called with metadata about the stream that will become available * for retrieval. */ void run( String statement, Map parameters, StreamCollector collector ); diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/spi/ConnectionPool.java b/driver/src/main/java/org/neo4j/driver/internal/spi/ConnectionPool.java similarity index 96% rename from driver/src/main/java/org/neo4j/driver/v1/internal/spi/ConnectionPool.java rename to driver/src/main/java/org/neo4j/driver/internal/spi/ConnectionPool.java index 8b719e01bc..5c63cbe527 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/spi/ConnectionPool.java +++ b/driver/src/main/java/org/neo4j/driver/internal/spi/ConnectionPool.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.spi; +package org.neo4j.driver.internal.spi; import java.net.URI; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/spi/Connector.java b/driver/src/main/java/org/neo4j/driver/internal/spi/Connector.java similarity index 97% rename from driver/src/main/java/org/neo4j/driver/v1/internal/spi/Connector.java rename to driver/src/main/java/org/neo4j/driver/internal/spi/Connector.java index 486174bb5d..60ded150cc 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/spi/Connector.java +++ b/driver/src/main/java/org/neo4j/driver/internal/spi/Connector.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.spi; +package org.neo4j.driver.internal.spi; import java.net.URI; import java.util.Collection; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/spi/Logger.java b/driver/src/main/java/org/neo4j/driver/internal/spi/Logger.java similarity index 96% rename from driver/src/main/java/org/neo4j/driver/v1/internal/spi/Logger.java rename to driver/src/main/java/org/neo4j/driver/internal/spi/Logger.java index 86be9764a1..a34a3eb11f 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/spi/Logger.java +++ b/driver/src/main/java/org/neo4j/driver/internal/spi/Logger.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.spi; +package org.neo4j.driver.internal.spi; public interface Logger { diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/spi/Logging.java b/driver/src/main/java/org/neo4j/driver/internal/spi/Logging.java similarity index 94% rename from driver/src/main/java/org/neo4j/driver/v1/internal/spi/Logging.java rename to driver/src/main/java/org/neo4j/driver/internal/spi/Logging.java index fff5b9e172..c0821e98ae 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/spi/Logging.java +++ b/driver/src/main/java/org/neo4j/driver/internal/spi/Logging.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.spi; +package org.neo4j.driver.internal.spi; public interface Logging { diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/spi/StreamCollector.java b/driver/src/main/java/org/neo4j/driver/internal/spi/StreamCollector.java similarity index 93% rename from driver/src/main/java/org/neo4j/driver/v1/internal/spi/StreamCollector.java rename to driver/src/main/java/org/neo4j/driver/internal/spi/StreamCollector.java index f79623b7b7..e0680eedcc 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/spi/StreamCollector.java +++ b/driver/src/main/java/org/neo4j/driver/internal/spi/StreamCollector.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.spi; +package org.neo4j.driver.internal.spi; import java.util.List; @@ -32,7 +32,7 @@ public interface StreamCollector StreamCollector NO_OP = new StreamCollector() { @Override - public void fieldNames( String[] names ) + public void keys( String[] names ) { } @@ -71,7 +71,7 @@ public void notifications( List notifications ) // TODO: This should be modified to simply have head/record/tail methods - void fieldNames( String[] names ); + void keys( String[] names ); void record( Value[] fields ); diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/summary/SimpleInputPosition.java b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalInputPosition.java similarity index 90% rename from driver/src/main/java/org/neo4j/driver/v1/internal/summary/SimpleInputPosition.java rename to driver/src/main/java/org/neo4j/driver/internal/summary/InternalInputPosition.java index f0f0f1bcbf..5161ad4445 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/summary/SimpleInputPosition.java +++ b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalInputPosition.java @@ -16,14 +16,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.summary; +package org.neo4j.driver.internal.summary; import org.neo4j.driver.v1.InputPosition; /** * An input position refers to a specific point in a query string. */ -public class SimpleInputPosition implements InputPosition +public class InternalInputPosition implements InputPosition { private final int offset; private final int line; @@ -36,7 +36,7 @@ public class SimpleInputPosition implements InputPosition * @param line the line number, starting from 1. * @param column the column number, starting from 1. */ - public SimpleInputPosition( int offset, int line, int column ) + public InternalInputPosition( int offset, int line, int column ) { this.offset = offset; this.line = line; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/summary/SimpleNotification.java b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalNotification.java similarity index 70% rename from driver/src/main/java/org/neo4j/driver/v1/internal/summary/SimpleNotification.java rename to driver/src/main/java/org/neo4j/driver/internal/summary/InternalNotification.java index c173036aad..0ec7c031b3 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/summary/SimpleNotification.java +++ b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalNotification.java @@ -16,35 +16,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.summary; +package org.neo4j.driver.internal.summary; import org.neo4j.driver.v1.Function; import org.neo4j.driver.v1.InputPosition; import org.neo4j.driver.v1.Notification; import org.neo4j.driver.v1.Value; -public class SimpleNotification implements Notification +public class InternalNotification implements Notification { public static final Function VALUE_TO_NOTIFICATION = new Function() { @Override public Notification apply( Value value ) { - String code = value.get( "code" ).javaString(); - String title = value.get( "title" ).javaString(); - String description = value.get( "description" ).javaString(); + String code = value.value( "code" ).asString(); + String title = value.value( "title" ).asString(); + String description = value.value( "description" ).asString(); - Value posValue = value.get( "position" ); + Value posValue = value.value( "position" ); InputPosition position = null; if( posValue != null ) { - position = new SimpleInputPosition( posValue.get( "offset" ).javaInteger(), - posValue.get( "line" ).javaInteger(), - posValue.get( "column" ).javaInteger() ); + position = new InternalInputPosition( posValue.value( "offset" ).asInt(), + posValue.value( "line" ).asInt(), + posValue.value( "column" ).asInt() ); } - Notification notification = new SimpleNotification( code, title, description, position ); - return notification; + return new InternalNotification( code, title, description, position ); } }; @@ -53,7 +52,7 @@ public Notification apply( Value value ) private final String description; private final InputPosition position; - public SimpleNotification( String code, String title, String description, InputPosition position ) + public InternalNotification( String code, String title, String description, InputPosition position ) { this.code = code; this.title = title; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/summary/SimplePlan.java b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalPlan.java similarity index 82% rename from driver/src/main/java/org/neo4j/driver/v1/internal/summary/SimplePlan.java rename to driver/src/main/java/org/neo4j/driver/internal/summary/InternalPlan.java index cd5c8e2669..d105596886 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/summary/SimplePlan.java +++ b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalPlan.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.summary; +package org.neo4j.driver.internal.summary; import java.util.Collections; import java.util.List; @@ -27,10 +27,11 @@ import org.neo4j.driver.v1.Value; import static java.lang.String.format; + import static org.neo4j.driver.v1.Values.valueAsIs; -import static org.neo4j.driver.v1.Values.valueToString; +import static org.neo4j.driver.v1.Values.valueAsString; -public class SimplePlan implements Plan +public class InternalPlan implements Plan { private final String operatorType; private final List identifiers; @@ -38,7 +39,7 @@ public class SimplePlan implements Plan private final List children; // Only call when sub-classing, for constructing plans, use .plan instead - protected SimplePlan( + protected InternalPlan( String operatorType, Map arguments, List identifiers, @@ -95,7 +96,7 @@ public boolean equals( Object o ) return false; } - SimplePlan that = (SimplePlan) o; + InternalPlan that = (InternalPlan) o; return operatorType.equals( that.operatorType ) && arguments.equals( that.arguments ) @@ -127,7 +128,7 @@ public static Plan plan( @Override public Plan create( String operatorType, Map arguments, List identifiers, List children, Value originalPlanValue ) { - return new SimplePlan( operatorType, arguments, identifiers, children ); + return new InternalPlan<>( operatorType, arguments, identifiers, children ); } }; @@ -160,22 +161,22 @@ public Converter( PlanCreator planCreator ) @Override public T apply( Value plan ) { - final String operatorType = plan.get( "operatorType" ).javaString(); + final String operatorType = plan.value( "operatorType" ).asString(); - final Value argumentsValue = plan.get( "args" ); - final Map arguments = argumentsValue == null + final Value argumentsValue = plan.value( "args" ); + final Map arguments = argumentsValue.isNull() ? Collections.emptyMap() - : argumentsValue.javaMap( valueAsIs() ); + : argumentsValue.asMap( valueAsIs() ); - final Value identifiersValue = plan.get( "identifiers" ); - final List identifiers = identifiersValue == null + final Value identifiersValue = plan.value( "identifiers" ); + final List identifiers = identifiersValue.isNull() ? Collections.emptyList() - : identifiersValue.javaList( valueToString() ); + : identifiersValue.asList( valueAsString() ); - final Value childrenValue = plan.get( "children" ); - final List children = childrenValue == null + final Value childrenValue = plan.value( "children" ); + final List children = childrenValue.isNull() ? Collections.emptyList() - : childrenValue.javaList( this ); + : childrenValue.asList( this ); return planCreator.create( operatorType, arguments, identifiers, children, plan ); } diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/summary/SimpleProfiledPlan.java b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalProfiledPlan.java similarity index 76% rename from driver/src/main/java/org/neo4j/driver/v1/internal/summary/SimpleProfiledPlan.java rename to driver/src/main/java/org/neo4j/driver/internal/summary/InternalProfiledPlan.java index 3045de1aa3..664bc51fa8 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/summary/SimpleProfiledPlan.java +++ b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalProfiledPlan.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.summary; +package org.neo4j.driver.internal.summary; import java.util.List; import java.util.Map; @@ -25,13 +25,13 @@ import org.neo4j.driver.v1.ProfiledPlan; import org.neo4j.driver.v1.Value; -public class SimpleProfiledPlan extends SimplePlan implements ProfiledPlan +public class InternalProfiledPlan extends InternalPlan implements ProfiledPlan { private final long dbHits; private final long records; - protected SimpleProfiledPlan( String operatorType, Map arguments, - List identifiers, List children, long dbHits, long records ) + protected InternalProfiledPlan( String operatorType, Map arguments, + List identifiers, List children, long dbHits, long records ) { super( operatorType, arguments, identifiers, children ); this.dbHits = dbHits; @@ -55,9 +55,9 @@ public long records() @Override public ProfiledPlan create( String operatorType, Map arguments, List identifiers, List children, Value originalPlanValue ) { - return new SimpleProfiledPlan( operatorType, arguments, identifiers, children, - originalPlanValue.get( "dbHits" ).javaLong(), - originalPlanValue.get( "rows" ).javaLong() ); + return new InternalProfiledPlan( operatorType, arguments, identifiers, children, + originalPlanValue.value( "dbHits" ).asLong(), + originalPlanValue.value( "rows" ).asLong() ); } }; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/summary/SimpleUpdateStatistics.java b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalUpdateStatistics.java similarity index 93% rename from driver/src/main/java/org/neo4j/driver/v1/internal/summary/SimpleUpdateStatistics.java rename to driver/src/main/java/org/neo4j/driver/internal/summary/InternalUpdateStatistics.java index 5e7bbed13b..5be6e1e7c9 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/summary/SimpleUpdateStatistics.java +++ b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalUpdateStatistics.java @@ -16,14 +16,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.summary; +package org.neo4j.driver.internal.summary; import org.neo4j.driver.v1.UpdateStatistics; -public class SimpleUpdateStatistics implements UpdateStatistics +public class InternalUpdateStatistics implements UpdateStatistics { - public static final SimpleUpdateStatistics EMPTY_STATS = - new SimpleUpdateStatistics( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + public static final InternalUpdateStatistics EMPTY_STATS = + new InternalUpdateStatistics( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); private final int nodesCreated; private final int nodesDeleted; private final int relationshipsCreated; @@ -36,7 +36,7 @@ public class SimpleUpdateStatistics implements UpdateStatistics private final int constraintsAdded; private final int constrainsRemoved; - public SimpleUpdateStatistics( + public InternalUpdateStatistics( int nodesCreated, int nodesDeleted, int relationshipsCreated, int relationshipsDeleted, int propertiesSet, @@ -152,7 +152,7 @@ public boolean equals( Object o ) return false; } - SimpleUpdateStatistics that = (SimpleUpdateStatistics) o; + InternalUpdateStatistics that = (InternalUpdateStatistics) o; return nodesCreated == that.nodesCreated && nodesDeleted == that.nodesDeleted diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/summary/ResultBuilder.java b/driver/src/main/java/org/neo4j/driver/internal/summary/ResultBuilder.java similarity index 70% rename from driver/src/main/java/org/neo4j/driver/v1/internal/summary/ResultBuilder.java rename to driver/src/main/java/org/neo4j/driver/internal/summary/ResultBuilder.java index 23f2bc7641..d47e787446 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/summary/ResultBuilder.java +++ b/driver/src/main/java/org/neo4j/driver/internal/summary/ResultBuilder.java @@ -16,15 +16,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.summary; +package org.neo4j.driver.internal.summary; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Set; +import org.neo4j.driver.internal.InternalRecord; +import org.neo4j.driver.internal.InternalResult; +import org.neo4j.driver.internal.spi.StreamCollector; import org.neo4j.driver.v1.Notification; import org.neo4j.driver.v1.Plan; import org.neo4j.driver.v1.ProfiledPlan; @@ -35,19 +37,18 @@ import org.neo4j.driver.v1.UpdateStatistics; import org.neo4j.driver.v1.Value; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.SimpleRecord; -import org.neo4j.driver.v1.internal.SimpleResult; -import org.neo4j.driver.v1.internal.spi.StreamCollector; import static java.util.Collections.unmodifiableMap; -import static org.neo4j.driver.v1.internal.ParameterSupport.NO_PARAMETERS; + +import static org.neo4j.driver.internal.ParameterSupport.NO_PARAMETERS; public class ResultBuilder implements StreamCollector { private final SummaryBuilder summaryBuilder; private List body = new ArrayList<>(); - private Map fieldLookup = null; + private List keys = null; + private Map keyIndexLookup = null; public ResultBuilder( String statement, Map parameters ) { @@ -57,22 +58,28 @@ public ResultBuilder( String statement, Map parameters ) } @Override - public void fieldNames( String[] names ) + public void keys( String[] names ) { - if ( fieldLookup == null ) + if ( keys == null ) { - if ( names.length == 0 ) + int numFields = names.length; + if ( numFields == 0 ) { - this.fieldLookup = Collections.emptyMap(); + this.keys = Collections.emptyList(); + this.keyIndexLookup = Collections.emptyMap(); } else { - Map fieldLookup = new HashMap<>(); - for ( int i = 0; i < names.length; i++ ) + Map fieldLookup = new HashMap<>( numFields ); + List fields = new ArrayList<>( numFields ); + for ( int i = 0; i < numFields; i++ ) { - fieldLookup.put( names[i], i ); + String name = names[i]; + fields.add( name ); + fieldLookup.put( name, i ); } - this.fieldLookup = fieldLookup; + this.keys = fields; + this.keyIndexLookup = fieldLookup; } } else @@ -82,9 +89,9 @@ public void fieldNames( String[] names ) } @Override - public void record( Value[] fields ) + public void record( Value[] values ) { - body.add( new SimpleRecord( fieldLookup, fields ) ); + body.add( new InternalRecord( keys, keyIndexLookup, values ) ); } @Override @@ -119,7 +126,6 @@ public void notifications( List notifications ) public Result build() { - Set fieldNames = fieldLookup == null ? Collections.emptySet() : fieldLookup.keySet(); - return new SimpleResult( fieldNames, body, summaryBuilder.build() ); + return new InternalResult( keys, body, summaryBuilder.build() ); } } diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/summary/SummaryBuilder.java b/driver/src/main/java/org/neo4j/driver/internal/summary/SummaryBuilder.java similarity index 94% rename from driver/src/main/java/org/neo4j/driver/v1/internal/summary/SummaryBuilder.java rename to driver/src/main/java/org/neo4j/driver/internal/summary/SummaryBuilder.java index 8cca2e9e41..92a15b6d3c 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/summary/SummaryBuilder.java +++ b/driver/src/main/java/org/neo4j/driver/internal/summary/SummaryBuilder.java @@ -16,11 +16,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.summary; +package org.neo4j.driver.internal.summary; import java.util.ArrayList; import java.util.List; +import org.neo4j.driver.internal.spi.StreamCollector; import org.neo4j.driver.v1.Notification; import org.neo4j.driver.v1.Plan; import org.neo4j.driver.v1.ProfiledPlan; @@ -30,7 +31,6 @@ import org.neo4j.driver.v1.UpdateStatistics; import org.neo4j.driver.v1.Value; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.spi.StreamCollector; public class SummaryBuilder implements StreamCollector { @@ -48,7 +48,7 @@ public SummaryBuilder( Statement statement ) } @Override - public void fieldNames( String[] names ) + public void keys( String[] names ) { // intentionally empty } @@ -136,7 +136,7 @@ public Statement statement() @Override public UpdateStatistics updateStatistics() { - return statistics == null ? SimpleUpdateStatistics.EMPTY_STATS : statistics; + return statistics == null ? InternalUpdateStatistics.EMPTY_STATS : statistics; } @Override diff --git a/driver/src/main/java/org/neo4j/driver/internal/types/InternalTypeSystem.java b/driver/src/main/java/org/neo4j/driver/internal/types/InternalTypeSystem.java new file mode 100644 index 0000000000..dab35fe0bc --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/types/InternalTypeSystem.java @@ -0,0 +1,162 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.types; + +import org.neo4j.driver.v1.Type; +import org.neo4j.driver.v1.TypeSystem; +import org.neo4j.driver.v1.Value; + +import static org.neo4j.driver.internal.types.TypeConstructor.ANY_TyCon; +import static org.neo4j.driver.internal.types.TypeConstructor.BOOLEAN_TyCon; +import static org.neo4j.driver.internal.types.TypeConstructor.FLOAT_TyCon; +import static org.neo4j.driver.internal.types.TypeConstructor.IDENTITY_TyCon; +import static org.neo4j.driver.internal.types.TypeConstructor.INTEGER_TyCon; +import static org.neo4j.driver.internal.types.TypeConstructor.LIST_TyCon; +import static org.neo4j.driver.internal.types.TypeConstructor.MAP_TyCon; +import static org.neo4j.driver.internal.types.TypeConstructor.NODE_TyCon; +import static org.neo4j.driver.internal.types.TypeConstructor.NULL_TyCon; +import static org.neo4j.driver.internal.types.TypeConstructor.NUMBER_TyCon; +import static org.neo4j.driver.internal.types.TypeConstructor.PATH_TyCon; +import static org.neo4j.driver.internal.types.TypeConstructor.RELATIONSHIP_TyCon; +import static org.neo4j.driver.internal.types.TypeConstructor.STRING_TyCon; + +/** + * Utility class for determining and working with the Cypher types of values + * + * @see Value + * @see Type + */ +public class InternalTypeSystem implements TypeSystem +{ + public static InternalTypeSystem TYPE_SYSTEM = new InternalTypeSystem(); + + private final TypeRepresentation anyType = constructType( ANY_TyCon ); + private final TypeRepresentation booleanType = constructType( BOOLEAN_TyCon ); + private final TypeRepresentation stringType = constructType( STRING_TyCon ); + private final TypeRepresentation numberType = constructType( NUMBER_TyCon ); + private final TypeRepresentation integerType = constructType( INTEGER_TyCon ); + private final TypeRepresentation floatType = constructType( FLOAT_TyCon ); + private final TypeRepresentation listType = constructType( LIST_TyCon ); + private final TypeRepresentation mapType = constructType( MAP_TyCon ); + private final TypeRepresentation identityType = constructType( IDENTITY_TyCon ); + private final TypeRepresentation nodeType = constructType( NODE_TyCon ); + private final TypeRepresentation relationshipType = constructType( RELATIONSHIP_TyCon ); + private final TypeRepresentation pathType = constructType( PATH_TyCon ); + private final TypeRepresentation nullType = constructType( NULL_TyCon ); + + private InternalTypeSystem() + { + } + + /** the Cypher type ANY */ + @Override + public Type ANY() + { + return anyType; + } + + /** the Cypher type BOOLEAN */ + @Override + public Type BOOLEAN() + { + return booleanType; + } + + /** the Cypher type STRING */ + @Override + public Type STRING() + { + return stringType; + } + + /** the Cypher type NUMBER */ + @Override + public Type NUMBER() + { + return numberType; + } + + /** the Cypher type INTEGER */ + @Override + public Type INTEGER() + { + return integerType; + } + + /** the Cypher type FLOAT */ + @Override + public Type FLOAT() + { + return floatType; + } + + /** the Cypher type LIST */ + @Override + public Type LIST() + { + return listType; + } + + /** the Cypher type MAP */ + @Override + public Type MAP() + { + return mapType; + } + + /** the Cypher type IDENTITY */ + @Override + public Type IDENTITY() + { + return identityType; + } + + /** the Cypher type NODE */ + @Override + public Type NODE() + { + return nodeType; + } + + /** the Cypher type RELATIONSHIP */ + @Override + public Type RELATIONSHIP() + { + return relationshipType; + } + + /** the Cypher type PATH */ + @Override + public Type PATH() + { + return pathType; + } + + /** the Cypher type NULL */ + @Override + public Type NULL() + { + return nullType; + } + + private TypeRepresentation constructType( TypeConstructor tyCon ) + { + return new TypeRepresentation( tyCon ); + } +} diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/types/TypeConstructor.java b/driver/src/main/java/org/neo4j/driver/internal/types/TypeConstructor.java similarity index 97% rename from driver/src/main/java/org/neo4j/driver/v1/internal/types/TypeConstructor.java rename to driver/src/main/java/org/neo4j/driver/internal/types/TypeConstructor.java index 936c4fd3f3..8bc1a03eba 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/types/TypeConstructor.java +++ b/driver/src/main/java/org/neo4j/driver/internal/types/TypeConstructor.java @@ -16,10 +16,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.types; +package org.neo4j.driver.internal.types; +import org.neo4j.driver.internal.value.InternalValue; import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.value.InternalValue; public enum TypeConstructor { diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/types/TypeRepresentation.java b/driver/src/main/java/org/neo4j/driver/internal/types/TypeRepresentation.java similarity index 89% rename from driver/src/main/java/org/neo4j/driver/v1/internal/types/TypeRepresentation.java rename to driver/src/main/java/org/neo4j/driver/internal/types/TypeRepresentation.java index ccb467e858..d76bac1381 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/types/TypeRepresentation.java +++ b/driver/src/main/java/org/neo4j/driver/internal/types/TypeRepresentation.java @@ -16,12 +16,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.types; +package org.neo4j.driver.internal.types; import org.neo4j.driver.v1.Type; import org.neo4j.driver.v1.Value; -import static org.neo4j.driver.v1.internal.types.TypeConstructor.LIST_TyCon; +import static org.neo4j.driver.internal.types.TypeConstructor.LIST_TyCon; public class TypeRepresentation implements Type { @@ -49,6 +49,11 @@ public String name() return tyCon.typeName(); } + public TypeConstructor constructor() + { + return tyCon; + } + @Override public boolean equals( Object o ) { diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/util/BytePrinter.java b/driver/src/main/java/org/neo4j/driver/internal/util/BytePrinter.java similarity index 99% rename from driver/src/main/java/org/neo4j/driver/v1/internal/util/BytePrinter.java rename to driver/src/main/java/org/neo4j/driver/internal/util/BytePrinter.java index 89629fce64..47819ad56b 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/util/BytePrinter.java +++ b/driver/src/main/java/org/neo4j/driver/internal/util/BytePrinter.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.util; +package org.neo4j.driver.internal.util; import java.io.ByteArrayOutputStream; import java.io.PrintStream; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/util/CertificateTool.java b/driver/src/main/java/org/neo4j/driver/internal/util/CertificateTool.java similarity index 99% rename from driver/src/main/java/org/neo4j/driver/v1/internal/util/CertificateTool.java rename to driver/src/main/java/org/neo4j/driver/internal/util/CertificateTool.java index a8df94c37a..32d7bf885f 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/util/CertificateTool.java +++ b/driver/src/main/java/org/neo4j/driver/internal/util/CertificateTool.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.util; +package org.neo4j.driver.internal.util; import java.io.BufferedInputStream; import java.io.BufferedWriter; diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/util/Clock.java b/driver/src/main/java/org/neo4j/driver/internal/util/Clock.java similarity index 96% rename from driver/src/main/java/org/neo4j/driver/v1/internal/util/Clock.java rename to driver/src/main/java/org/neo4j/driver/internal/util/Clock.java index 04ded51d77..27c018a1f6 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/util/Clock.java +++ b/driver/src/main/java/org/neo4j/driver/internal/util/Clock.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.util; +package org.neo4j.driver.internal.util; /** * Since {@link java.time.Clock} is only available in Java 8, use our own until we drop java 7 support. diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/util/Consumer.java b/driver/src/main/java/org/neo4j/driver/internal/util/Consumer.java similarity index 94% rename from driver/src/main/java/org/neo4j/driver/v1/internal/util/Consumer.java rename to driver/src/main/java/org/neo4j/driver/internal/util/Consumer.java index 51e8c5ee7a..a1110bf025 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/util/Consumer.java +++ b/driver/src/main/java/org/neo4j/driver/internal/util/Consumer.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.util; +package org.neo4j.driver.internal.util; public interface Consumer { diff --git a/driver/src/main/java/org/neo4j/driver/internal/util/Extract.java b/driver/src/main/java/org/neo4j/driver/internal/util/Extract.java new file mode 100644 index 0000000000..29e4f8b8da --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/util/Extract.java @@ -0,0 +1,197 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.util; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.neo4j.driver.internal.InternalField; +import org.neo4j.driver.internal.InternalProperty; +import org.neo4j.driver.v1.Field; +import org.neo4j.driver.v1.Function; +import org.neo4j.driver.v1.MapAccessor; +import org.neo4j.driver.v1.Property; +import org.neo4j.driver.v1.RecordAccessor; +import org.neo4j.driver.v1.Value; + +import static java.util.Collections.emptyList; +import static java.util.Collections.emptyMap; +import static java.util.Collections.singletonList; +import static java.util.Collections.singletonMap; +import static java.util.Collections.unmodifiableList; +import static java.util.Collections.unmodifiableMap; + +/** + * Utility class for extracting data. + */ +public final class Extract +{ + private Extract() + { + throw new UnsupportedOperationException(); + } + + public static List list( Value[] values ) + { + switch ( values.length ) + { + case 0: + return emptyList(); + case 1: + return singletonList( values[0] ); + default: + return unmodifiableList( Arrays.asList( values ) ); + } + } + + public static List list( Value[] data, Function mapFunction ) + { + int size = data.length; + switch ( size ) + { + case 0: + return emptyList(); + case 1: + return singletonList( mapFunction.apply( data[0] ) ); + default: + List result = new ArrayList<>( size ); + for ( Value value : data ) + { + result.add( mapFunction.apply( value ) ); + } + return unmodifiableList( result ); + } + } + + public static Map map( Map data ) + { + if ( data.isEmpty() ) + { + return emptyMap(); + } + else + { + return unmodifiableMap( data ); + } + } + + public static Map map( Map data, Function mapFunction ) + { + if ( data.isEmpty() ) { + return emptyMap(); + } else { + int size = data.size(); + if ( size == 1 ) { + Map.Entry head = data.entrySet().iterator().next(); + return singletonMap( head.getKey(), mapFunction.apply( head.getValue() ) ); + } else { + Map map = new HashMap<>( size ); + for ( Map.Entry entry : data.entrySet() ) + { + map.put( entry.getKey(), mapFunction.apply( entry.getValue() ) ); + } + return unmodifiableMap( map ); + } + } + } + + public static Map map( RecordAccessor record, Function mapFunction ) + { + int size = record.keys().size(); + switch ( size ) + { + case 0: + return emptyMap(); + + case 1: + return singletonMap( record.keys().get( 0 ), mapFunction.apply( record.value( 0 ) ) ); + + default: + Map map = new HashMap<>( size ); + List keys = record.keys(); + for ( int i = 0; i < size; i++ ) + { + map.put( keys.get( i ), mapFunction.apply( record.value( i ) ) ); + } + return unmodifiableMap( map ); + } + } + + public static Iterable> properties( final MapAccessor map, final Function mapFunction ) + { + return new Iterable>() + { + @Override + public Iterator> iterator() + { + final Iterator keys = map.keys().iterator(); + return new Iterator>() + { + @Override + public boolean hasNext() + { + return keys.hasNext(); + } + + @Override + public Property next() + { + String key = keys.next(); + Value value = map.value( key ); + return InternalProperty.of( key, mapFunction.apply( value ) ); + } + }; + } + }; + } + + public static List> fields( final RecordAccessor map, final Function mapFunction ) + { + int size = map.keys().size(); + switch ( size ) + { + case 0: + return emptyList(); + + case 1: + { + String key = map.keys().iterator().next(); + Value value = map.value( key ); + return singletonList( InternalField.of( key, 0, mapFunction.apply( value ) ) ); + } + + default: + { + List> list = new ArrayList<>( size ); + List keys = map.keys(); + for ( int i = 0; i < size; i++ ) + { + String key = keys.get( i ); + Value value = map.value( i ); + list.add( InternalField.of( key, i, mapFunction.apply( value ) ) ); + } + return unmodifiableList( list ); + } + } + } +} diff --git a/driver/src/main/java/org/neo4j/driver/internal/util/Format.java b/driver/src/main/java/org/neo4j/driver/internal/util/Format.java new file mode 100644 index 0000000000..225b7cc44c --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/util/Format.java @@ -0,0 +1,134 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.util; + +import java.util.Iterator; + +import org.neo4j.driver.internal.InternalField; +import org.neo4j.driver.internal.InternalProperty; +import org.neo4j.driver.v1.Field; +import org.neo4j.driver.v1.Function; +import org.neo4j.driver.v1.Property; + +public abstract class Format +{ + private Format() + { + throw new UnsupportedOperationException(); + } + + public static String formatProperties( Function printValue, + int propertyCount, + Iterable> properties ) + { + switch ( propertyCount ) { + case 0: + return "{}"; + + case 1: + { + return String.format( "{%s}", internalProperty( properties.iterator().next() ).toString( printValue ) ); + } + + default: + { + StringBuilder builder = new StringBuilder(); + builder.append( "{" ); + Iterator> iterator = properties.iterator(); + builder.append( internalProperty( iterator.next() ).toString( printValue ) ); + while ( iterator.hasNext() ) + { + builder.append( ',' ); + builder.append( ' ' ); + builder.append( internalProperty( iterator.next() ).toString( printValue ) ); + } + builder.append( "}" ); + return builder.toString(); + } + } + } + + @SuppressWarnings("unchecked") + private static InternalProperty internalProperty( Property property ) + { + return (InternalProperty) property; + } + + public static String formatFields( Function printValue, + int propertyCount, + Iterable> fields ) + { + switch ( propertyCount ) { + case 0: + return "{}"; + + case 1: + { + return String.format( "{%s}", internalField( fields.iterator().next() ).toString( printValue ) ); + } + + default: + { + StringBuilder builder = new StringBuilder(); + builder.append( "{" ); + Iterator> iterator = fields.iterator(); + builder.append( internalField( iterator.next() ).toString( printValue ) ); + while ( iterator.hasNext() ) + { + builder.append( ',' ); + builder.append( ' ' ); + builder.append( internalField( iterator.next() ).toString( printValue ) ); + } + builder.append( "}" ); + return builder.toString(); + } + } + } + + @SuppressWarnings("unchecked") + private static InternalField internalField( Field property ) + { + return (InternalField) property; + } + + public static String formatElements( Function printValue, V[] elements ) + { + int elementCount = elements.length; + switch ( elementCount ) { + case 0: + return "[]"; + + case 1: + return String.format( "[%s]", printValue.apply( elements[0] ) ); + + default: + StringBuilder builder = new StringBuilder(); + builder.append("["); + builder.append( printValue.apply( elements[0] ) ); + for (int i = 1; i < elementCount; i++ ) + { + builder.append( ',' ); + builder.append( ' ' ); + builder.append( printValue.apply( elements[i] ) ); + } + builder.append("]"); + return builder.toString(); + } + } +} diff --git a/driver/src/main/java/org/neo4j/driver/internal/util/Iterables.java b/driver/src/main/java/org/neo4j/driver/internal/util/Iterables.java new file mode 100644 index 0000000000..8c3e6937c1 --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/util/Iterables.java @@ -0,0 +1,90 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.neo4j.driver.v1.Function; + +public class Iterables +{ + public static int count( Iterable it ) + { + if ( it instanceof Collection ) { return ((Collection) it).size(); } + int size = 0; + for ( Object o : it ) + { + size++; + } + return size; + } + + public static List asList( Iterable it ) + { + if ( it instanceof List ) { return (List) it; } + List list = new ArrayList<>(); + for ( T t : it ) + { + list.add( t ); + } + return list; + } + + public static Iterable map(final Iterable it, final Function f) + { + return new Iterable() + { + @Override + public Iterator iterator() + { + final Iterator aIterator = it.iterator(); + return new Iterator() + { + @Override + public boolean hasNext() + { + return aIterator.hasNext(); + } + + @Override + public B next() + { + return f.apply( aIterator.next() ); + } + }; + } + }; + } + + public static Map mapValues( Map map, Function f ) + { + HashMap transformed = new HashMap<>( map.size() ); + for ( Entry entry : map.entrySet() ) + { + transformed.put( entry.getKey(), f.apply( entry.getValue() ) ); + } + return transformed; + } +} diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/value/BooleanValue.java b/driver/src/main/java/org/neo4j/driver/internal/value/BooleanValue.java similarity index 61% rename from driver/src/main/java/org/neo4j/driver/v1/internal/value/BooleanValue.java rename to driver/src/main/java/org/neo4j/driver/internal/value/BooleanValue.java index c93fc7eaf0..868af1e9c2 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/value/BooleanValue.java +++ b/driver/src/main/java/org/neo4j/driver/internal/value/BooleanValue.java @@ -16,27 +16,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.value; +package org.neo4j.driver.internal.value; +import org.neo4j.driver.internal.types.InternalTypeSystem; import org.neo4j.driver.v1.Type; -import org.neo4j.driver.v1.internal.types.StandardTypeSystem; -import org.neo4j.driver.v1.internal.types.TypeConstructor; -public abstract class BooleanValue extends ValueAdapter +public abstract class BooleanValue extends ScalarValueAdapter { private BooleanValue() { //do nothing } - @Override - public TypeConstructor typeConstructor() - { - return TypeConstructor.BOOLEAN_TyCon; - } - public static BooleanValue TRUE = new TrueValue(); - public static BooleanValue FALSE = new FalseValue(); public static BooleanValue fromBoolean( boolean value ) @@ -45,57 +37,44 @@ public static BooleanValue fromBoolean( boolean value ) } @Override - public boolean isBoolean() - { - return true; - } + public abstract Boolean asObject(); @Override public Type type() { - return StandardTypeSystem.TYPE_SYSTEM.BOOLEAN(); + return InternalTypeSystem.TYPE_SYSTEM.BOOLEAN(); } @Override public int hashCode() { - return javaBoolean() ? 1231 : 1237; + return Boolean.hashCode( asBoolean() ); } private static class TrueValue extends BooleanValue { - @Override - public boolean javaBoolean() - { - return true; - } @Override - public String javaString() - { - return"true"; - } - @Override - public int javaInteger() + public Boolean asObject() { - return 1; + return Boolean.TRUE; } @Override - public long javaLong() + public boolean asBoolean() { - return 1L; + return true; } @Override - public float javaFloat() + public boolean isTrue() { - return 1f; + return true; } @Override - public double javaDouble() + public boolean isFalse() { - return 1d; + return false; } @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") @@ -104,42 +83,38 @@ public boolean equals( Object obj ) { return obj == TRUE; } - } - private static class FalseValue extends BooleanValue { @Override - public boolean javaBoolean() + public String asLiteralString() { - return false; + return "TRUE"; } + } + private static class FalseValue extends BooleanValue + { @Override - public String javaString() - { - return "false"; - } - @Override - public int javaInteger() + public Boolean asObject() { - return 0; + return Boolean.FALSE; } @Override - public long javaLong() + public boolean asBoolean() { - return 0L; + return false; } @Override - public float javaFloat() + public boolean isTrue() { - return 0f; + return false; } @Override - public double javaDouble() + public boolean isFalse() { - return 0d; + return true; } @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") @@ -148,5 +123,11 @@ public boolean equals( Object obj ) { return obj == FALSE; } + + @Override + public String asLiteralString() + { + return "FALSE"; + } } } diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/util/Iterables.java b/driver/src/main/java/org/neo4j/driver/internal/value/EntityValueAdapter.java similarity index 54% rename from driver/src/main/java/org/neo4j/driver/v1/internal/util/Iterables.java rename to driver/src/main/java/org/neo4j/driver/internal/value/EntityValueAdapter.java index a3e7e1377e..aa24474c41 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/util/Iterables.java +++ b/driver/src/main/java/org/neo4j/driver/internal/value/EntityValueAdapter.java @@ -16,33 +16,38 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.util; +package org.neo4j.driver.internal.value; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import org.neo4j.driver.v1.Entity; +import org.neo4j.driver.v1.Value; -public class Iterables +public abstract class EntityValueAdapter extends GraphValueAdapter { - public static int count( Iterable it ) + protected EntityValueAdapter( V adapted ) { - if ( it instanceof Collection ) { return ((Collection) it).size(); } - int size = 0; - for ( Object o : it ) - { - size++; - } - return size; + super( adapted ); } - public static List toList( Iterable it ) + public V asEntity() { - if ( it instanceof List ) { return (List) it; } - List list = new ArrayList<>(); - for ( T t : it ) - { - list.add( t ); - } - return list; + return asObject(); + } + + @Override + public int propertyCount() + { + return asEntity().propertyCount(); + } + + @Override + public Iterable keys() + { + return asEntity().keys(); + } + + @Override + public Value value( String key ) + { + return asEntity().value( key ); } } diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/value/FloatValue.java b/driver/src/main/java/org/neo4j/driver/internal/value/FloatValue.java similarity index 53% rename from driver/src/main/java/org/neo4j/driver/v1/internal/value/FloatValue.java rename to driver/src/main/java/org/neo4j/driver/internal/value/FloatValue.java index f9c2e9aca3..13c53a9321 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/value/FloatValue.java +++ b/driver/src/main/java/org/neo4j/driver/internal/value/FloatValue.java @@ -16,13 +16,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.value; +package org.neo4j.driver.internal.value; +import org.neo4j.driver.internal.types.InternalTypeSystem; import org.neo4j.driver.v1.Type; -import org.neo4j.driver.v1.internal.types.StandardTypeSystem; -import org.neo4j.driver.v1.internal.types.TypeConstructor; +import org.neo4j.driver.v1.exceptions.value.LossyCoercion; -public class FloatValue extends ValueAdapter +public class FloatValue extends NumberValueAdapter { private final double val; @@ -32,63 +32,80 @@ public FloatValue( double val ) } @Override - public String javaString() + public Type type() { - return Double.toString( val ); + return InternalTypeSystem.TYPE_SYSTEM.FLOAT(); } @Override - public int javaInteger() + public Double asNumber() { - return (int) val; + return val; } @Override - public long javaLong() + public long asLong() { - return (long) val; - } + long longVal = (long) val; + if ((double) longVal != val) + { + throw new LossyCoercion( type().name(), "Java long" ); + } - @Override - public float javaFloat() - { - return (float) val; + return longVal; } @Override - public boolean javaBoolean() + public int asInt() { - return val != 0; - } + int intVal = (int) val; + if ((double) intVal != val) + { + throw new LossyCoercion( type().name(), "Java int" ); + } - @Override - public TypeConstructor typeConstructor() - { - return TypeConstructor.FLOAT_TyCon; + return intVal; } @Override - public double javaDouble() + public short asShort() { - return val; + short shortVal = (short) val; + if ((double) shortVal != val) + { + throw new LossyCoercion( type().name(), "Java short" ); + } + + return shortVal; } @Override - public boolean isFloat() + public byte asByte() { - return true; + byte byteVal = (byte) val; + if ((double) byteVal != val) + { + throw new LossyCoercion( type().name(), "Java byte" ); + } + + return byteVal; } - @Override - public Type type() + public double asDouble() { - return StandardTypeSystem.TYPE_SYSTEM.FLOAT(); + return val; } @Override - public String toString() + public float asFloat() { - return "float<" + val + ">"; + float floatVal = (float) val; + if ((double) floatVal != val) + { + throw new LossyCoercion( type().name(), "Java float" ); + } + + return floatVal; } @Override @@ -104,9 +121,7 @@ public boolean equals( Object o ) } FloatValue values = (FloatValue) o; - return Double.compare( values.val, val ) == 0; - } @Override @@ -115,4 +130,10 @@ public int hashCode() long temp = Double.doubleToLongBits( val ); return (int) (temp ^ (temp >>> 32)); } + + @Override + public String asLiteralString() + { + return Double.toString( val ); + } } diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/value/PathValue.java b/driver/src/main/java/org/neo4j/driver/internal/value/GraphValueAdapter.java similarity index 62% rename from driver/src/main/java/org/neo4j/driver/v1/internal/value/PathValue.java rename to driver/src/main/java/org/neo4j/driver/internal/value/GraphValueAdapter.java index 7d30df56a0..5c3f14b64d 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/value/PathValue.java +++ b/driver/src/main/java/org/neo4j/driver/internal/value/GraphValueAdapter.java @@ -16,50 +16,39 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.value; +package org.neo4j.driver.internal.value; -import org.neo4j.driver.v1.Path; -import org.neo4j.driver.v1.Type; -import org.neo4j.driver.v1.internal.types.StandardTypeSystem; -import org.neo4j.driver.v1.internal.types.TypeConstructor; +import static java.lang.String.format; -public class PathValue extends ValueAdapter +public abstract class GraphValueAdapter extends ValueAdapter { - private final Path adapted; + private final V adapted; - public PathValue( Path adapted ) + protected GraphValueAdapter( V adapted ) { + if ( adapted == null ) + { + throw new IllegalArgumentException( format( "Cannot construct %s from null", getClass().getSimpleName() ) ); + } this.adapted = adapted; } @Override - public Path asPath() - { - return adapted; - } - - @Override - public boolean isPath() + public int size() { - return true; + return propertyCount(); } @Override - public long size() + public V asObject() { - return adapted.length(); - } - - @Override - public TypeConstructor typeConstructor() - { - return TypeConstructor.PATH_TyCon; + return adapted; } @Override - public Type type() + public String toString( Format valueFormat ) { - return StandardTypeSystem.TYPE_SYSTEM.PATH(); + return maybeWithType( valueFormat.includeType(), adapted.toString() ); } @Override @@ -74,8 +63,7 @@ public boolean equals( Object o ) return false; } - PathValue values = (PathValue) o; - + GraphValueAdapter values = (GraphValueAdapter) o; return adapted.equals( values.adapted ); } diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/value/IdentityValue.java b/driver/src/main/java/org/neo4j/driver/internal/value/IdentityValue.java similarity index 67% rename from driver/src/main/java/org/neo4j/driver/v1/internal/value/IdentityValue.java rename to driver/src/main/java/org/neo4j/driver/internal/value/IdentityValue.java index 1385e6bfb9..8a69eb24f4 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/value/IdentityValue.java +++ b/driver/src/main/java/org/neo4j/driver/internal/value/IdentityValue.java @@ -16,33 +16,35 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.value; +package org.neo4j.driver.internal.value; +import org.neo4j.driver.internal.types.InternalTypeSystem; import org.neo4j.driver.v1.Identity; import org.neo4j.driver.v1.Type; -import org.neo4j.driver.v1.internal.types.StandardTypeSystem; -import org.neo4j.driver.v1.internal.types.TypeConstructor; -public class IdentityValue extends ValueAdapter +public class IdentityValue extends ScalarValueAdapter { private final Identity val; public IdentityValue( Identity val ) { - assert val != null; + if ( val == null ) + { + throw new IllegalArgumentException( "Cannot construct IdentityValue from null" ); + } this.val = val; } @Override - public boolean javaBoolean() + public Type type() { - return true; + return InternalTypeSystem.TYPE_SYSTEM.IDENTITY(); } @Override - public String javaString() + public Identity asObject() { - return val.toString(); + return asIdentity(); } @Override @@ -52,25 +54,7 @@ public Identity asIdentity() } @Override - public TypeConstructor typeConstructor() - { - return TypeConstructor.IDENTITY_TyCon; - } - - @Override - public boolean isIdentity() - { - return true; - } - - @Override - public Type type() - { - return StandardTypeSystem.TYPE_SYSTEM.INTEGER(); - } - - @Override - public String toString() + public String asLiteralString() { return val.toString(); } @@ -88,8 +72,7 @@ public boolean equals( Object o ) } IdentityValue values = (IdentityValue) o; - - return val.equals( values.val ); + return val == values.val || val.equals( values.val ); } diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/value/IntegerValue.java b/driver/src/main/java/org/neo4j/driver/internal/value/IntegerValue.java similarity index 58% rename from driver/src/main/java/org/neo4j/driver/v1/internal/value/IntegerValue.java rename to driver/src/main/java/org/neo4j/driver/internal/value/IntegerValue.java index bb67c8532c..7976f9311f 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/value/IntegerValue.java +++ b/driver/src/main/java/org/neo4j/driver/internal/value/IntegerValue.java @@ -16,13 +16,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.value; +package org.neo4j.driver.internal.value; +import org.neo4j.driver.internal.types.InternalTypeSystem; import org.neo4j.driver.v1.Type; -import org.neo4j.driver.v1.internal.types.StandardTypeSystem; -import org.neo4j.driver.v1.internal.types.TypeConstructor; +import org.neo4j.driver.v1.exceptions.value.LossyCoercion; -public class IntegerValue extends ValueAdapter +public class IntegerValue extends NumberValueAdapter { private final long val; @@ -32,63 +32,74 @@ public IntegerValue( long val ) } @Override - public String javaString() + public Type type() { - return Long.toString( val ); + return InternalTypeSystem.TYPE_SYSTEM.INTEGER(); } @Override - public int javaInteger() + public Long asNumber() { - return (int) val; + return val; } @Override - public float javaFloat() + public long asLong() { - return (float) val; + return val; } @Override - public boolean javaBoolean() + public int asInt() { - return val != 0; + if (val > Integer.MAX_VALUE || val < Integer.MIN_VALUE) + { + throw new LossyCoercion( type().name(), "Java int" ); + } + return (int) val; } @Override - public TypeConstructor typeConstructor() + public short asShort() { - return TypeConstructor.INTEGER_TyCon; + if (val > Short.MAX_VALUE || val < Short.MIN_VALUE) + { + throw new LossyCoercion( type().name(), "Java short" ); + } + return (short) val; } - @Override - public long javaLong() + public byte asByte() { - return val; + if (val > Byte.MAX_VALUE || val < Byte.MIN_VALUE) + { + throw new LossyCoercion( type().name(), "Java byte" ); + } + return (byte) val; } @Override - public boolean isInteger() + public double asDouble() { - return true; - } + double doubleVal = (double) val; + if ( (long) doubleVal != val) + { + throw new LossyCoercion( type().name(), "Java double" ); + } - @Override - public double javaDouble() - { return (double) val; } @Override - public Type type() + public float asFloat() { - return StandardTypeSystem.TYPE_SYSTEM.INTEGER(); + return (float) val; } @Override - public String toString() + public String asLiteralString() { - return "integer<" + val + ">"; + return Long.toString( val ); } @Override @@ -104,9 +115,7 @@ public boolean equals( Object o ) } IntegerValue values = (IntegerValue) o; - return val == values.val; - } @Override diff --git a/driver/src/main/java/org/neo4j/driver/internal/value/InternalValue.java b/driver/src/main/java/org/neo4j/driver/internal/value/InternalValue.java new file mode 100644 index 0000000000..728048afad --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/value/InternalValue.java @@ -0,0 +1,52 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.value; + +import org.neo4j.driver.internal.AsValue; +import org.neo4j.driver.internal.types.TypeConstructor; +import org.neo4j.driver.v1.Function; +import org.neo4j.driver.v1.Value; + +public interface InternalValue extends Value, AsValue +{ + TypeConstructor typeConstructor(); + String toString( Format valueFormat ); + + enum Format implements Function + { + VALUE_ONLY, + VALUE_WITH_TYPE; + + public boolean includeType() + { + return this != VALUE_ONLY; + } + + public Format inner() + { + return VALUE_ONLY; + } + + @Override + public String apply( Value value ) + { + return ( (InternalValue) value ).toString( this ); + } + } +} diff --git a/driver/src/main/java/org/neo4j/driver/internal/value/ListValue.java b/driver/src/main/java/org/neo4j/driver/internal/value/ListValue.java new file mode 100644 index 0000000000..7e40d69646 --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/value/ListValue.java @@ -0,0 +1,249 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.value; + +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import org.neo4j.driver.internal.types.InternalTypeSystem; +import org.neo4j.driver.internal.util.Extract; +import org.neo4j.driver.v1.Function; +import org.neo4j.driver.v1.Type; +import org.neo4j.driver.v1.Value; +import org.neo4j.driver.v1.Values; + +import static org.neo4j.driver.internal.util.Format.formatElements; +import static org.neo4j.driver.internal.value.InternalValue.Format.VALUE_ONLY; +import static org.neo4j.driver.v1.Values.valueAsObject; + +public class ListValue extends ValueAdapter +{ + private final Value[] values; + + public ListValue( Value... values ) + { + if ( values == null ) + { + throw new IllegalArgumentException( "Cannot construct ListValue from null" ); + } + this.values = values; + } + + @Override + public boolean isEmpty() + { + return values.length == 0; + } + + @Override + public List asObject() + { + return asList( valueAsObject() ); + } + + @Override + public List asList() + { + return Extract.list( values ); + } + + @Override + public List asList( Function mapFunction ) + { + return Extract.list( values, mapFunction ); + } + + @Override + public Value[] asArray() + { + int size = size(); + Value[] result = new Value[size]; + System.arraycopy( values, 0, result, 0, size ); + return result; + } + + @SuppressWarnings("unchecked") + @Override + public T[] asArray( Class clazz, Function mapFunction ) + { + int size = size(); + T[] result = (T[]) Array.newInstance( clazz, size ); + for ( int i = 0; i < size; i++ ) + { + result[i] = mapFunction.apply( values[i] ); + } + return result; + } + + @Override + public long[] asLongArray() + { + long[] result = new long[ size() ]; + for ( int i = 0; i < values.length; i++ ) + { + result[i] = values[i].asLong(); + } + return result; + } + + @Override + public int[] asIntArray() + { + int[] result = new int[ size() ]; + for ( int i = 0; i < values.length; i++ ) + { + result[i] = values[i].asInt(); + } + return result; + } + + @Override + public short[] asShortArray() + { + short[] result = new short[ size() ]; + for ( int i = 0; i < values.length; i++ ) + { + result[i] = values[i].asShort(); + } + return result; + } + + @Override + public byte[] asByteArray() + { + byte[] result = new byte[ size() ]; + for ( int i = 0; i < values.length; i++ ) + { + result[i] = values[i].asByte(); + } + return result; + } + + @Override + public double[] asDoubleArray() + { + double[] result = new double[ size() ]; + for ( int i = 0; i < values.length; i++ ) + { + result[i] = values[i].asDouble(); + } + return result; + } + + @Override + public float[] asFloatArray() + { + float[] result = new float[ size() ]; + for ( int i = 0; i < values.length; i++ ) + { + result[i] = values[i].asFloat(); + } + return result; + } + + @Override + public int size() + { + return values.length; + } + + @Override + public Value value( int index ) + { + return index >= 0 && index < values.length ? values[index] : Values.NULL; + } + + @Override + public Iterable values( final Function mapFunction ) + { + return new Iterable() + { + @Override + public Iterator iterator() + { + return new Iterator() + { + private int cursor = 0; + + @Override + public boolean hasNext() + { + return cursor < values.length; + } + + @Override + public T next() + { + return mapFunction.apply( values[cursor++] ); + } + + @Override + public void remove() + { + } + }; + } + }; + } + + @Override + public String asLiteralString() + { + return toString( VALUE_ONLY ); + } + + @Override + public Type type() + { + return InternalTypeSystem.TYPE_SYSTEM.LIST(); + } + + @Override + public String toString( Format valueFormat ) + { + return maybeWithType( + valueFormat.includeType(), + formatElements( valueFormat.inner(), values ) + ); + } + + @Override + public boolean equals( Object o ) + { + if ( this == o ) + { + return true; + } + if ( o == null || getClass() != o.getClass() ) + { + return false; + } + + ListValue otherValues = (ListValue) o; + return Arrays.equals( values, otherValues.values ); + } + + @Override + public int hashCode() + { + return Arrays.hashCode( values ); + } +} diff --git a/driver/src/main/java/org/neo4j/driver/internal/value/MapValue.java b/driver/src/main/java/org/neo4j/driver/internal/value/MapValue.java new file mode 100644 index 0000000000..29860155fb --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/value/MapValue.java @@ -0,0 +1,155 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.value; + +import java.util.Map; + +import org.neo4j.driver.internal.types.InternalTypeSystem; +import org.neo4j.driver.internal.util.Extract; +import org.neo4j.driver.v1.Function; +import org.neo4j.driver.v1.Type; +import org.neo4j.driver.v1.Value; +import org.neo4j.driver.v1.Values; + +import static org.neo4j.driver.internal.util.Format.formatProperties; +import static org.neo4j.driver.internal.value.InternalValue.Format.VALUE_ONLY; +import static org.neo4j.driver.v1.Values.valueAsObject; + +public class MapValue extends ValueAdapter +{ + private final Map val; + + public MapValue( Map val ) + { + if ( val == null ) + { + throw new IllegalArgumentException( "Cannot construct MapValue from null" ); + } + this.val = val; + } + + @Override + public boolean isEmpty() + { + return val.isEmpty(); + } + + @Override + public Map asObject() + { + return asMap( valueAsObject() ); + } + + @Override + public Map asMap() + { + return Extract.map( val ); + } + + @Override + public Map asMap( Function mapFunction ) + { + return Extract.map( val, mapFunction ); + } + + @Override + public int size() + { + return propertyCount(); + } + + @Override + public int propertyCount() + { + return val.size(); + } + + @Override + public boolean containsKey( String key ) + { + return val.containsKey( key ); + } + + @Override + public Iterable keys() + { + return val.keySet(); + } + + @Override + public Iterable values() + { + return val.values(); + } + + @Override + public Iterable values( Function mapFunction ) + { + return Extract.map( val, mapFunction ).values(); + } + + @Override + public Value value( String key ) + { + return val.getOrDefault( key, Values.NULL ); + } + + @Override + public String asLiteralString() + { + return toString( VALUE_ONLY ); + } + + @Override + public String toString( Format valueFormat ) + { + return maybeWithType( + valueFormat.includeType(), + formatProperties( valueFormat.inner(), propertyCount(), properties() ) + ); + } + + @Override + public Type type() + { + return InternalTypeSystem.TYPE_SYSTEM.MAP(); + } + + @Override + public boolean equals( Object o ) + { + if ( this == o ) + { + return true; + } + if ( o == null || getClass() != o.getClass() ) + { + return false; + } + + MapValue values = (MapValue) o; + return val.equals( values.val ); + } + + @Override + public int hashCode() + { + return val.hashCode(); + } +} diff --git a/driver/src/main/java/org/neo4j/driver/internal/value/NodeValue.java b/driver/src/main/java/org/neo4j/driver/internal/value/NodeValue.java new file mode 100644 index 0000000000..4826267456 --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/value/NodeValue.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.value; + +import org.neo4j.driver.internal.types.InternalTypeSystem; +import org.neo4j.driver.v1.Node; +import org.neo4j.driver.v1.Type; + +public class NodeValue extends EntityValueAdapter +{ + public NodeValue( Node adapted ) + { + super( adapted ); + } + + @Override + public Node asNode() + { + return asEntity(); + } + + @Override + public Type type() + { + return InternalTypeSystem.TYPE_SYSTEM.NODE(); + } +} diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/value/NullValue.java b/driver/src/main/java/org/neo4j/driver/internal/value/NullValue.java similarity index 72% rename from driver/src/main/java/org/neo4j/driver/v1/internal/value/NullValue.java rename to driver/src/main/java/org/neo4j/driver/internal/value/NullValue.java index 775475ee44..3ca7d91071 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/value/NullValue.java +++ b/driver/src/main/java/org/neo4j/driver/internal/value/NullValue.java @@ -16,27 +16,42 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.value; +package org.neo4j.driver.internal.value; +import org.neo4j.driver.internal.types.InternalTypeSystem; import org.neo4j.driver.v1.Type; import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.types.StandardTypeSystem; -import org.neo4j.driver.v1.internal.types.TypeConstructor; -public class NullValue extends ValueAdapter +public final class NullValue extends ScalarValueAdapter { public static Value NULL = new NullValue(); + private NullValue() + { + } + @Override - public TypeConstructor typeConstructor() + public boolean isNull() { - return TypeConstructor.NULL_TyCon; + return true; + } + + @Override + public Object asObject() + { + return null; + } + + @Override + public String asString() + { + return "null"; } @Override public Type type() { - return StandardTypeSystem.TYPE_SYSTEM.NULL(); + return InternalTypeSystem.TYPE_SYSTEM.NULL(); } @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") @@ -53,8 +68,8 @@ public int hashCode() } @Override - public boolean isNull() + public String asLiteralString() { - return true; + return "NULL"; } } diff --git a/driver/src/main/java/org/neo4j/driver/internal/value/NumberValueAdapter.java b/driver/src/main/java/org/neo4j/driver/internal/value/NumberValueAdapter.java new file mode 100644 index 0000000000..b66fedab88 --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/value/NumberValueAdapter.java @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.value; + +public abstract class NumberValueAdapter extends ScalarValueAdapter +{ + @Override + public final V asObject() + { + return asNumber(); + } + + @Override + public abstract V asNumber(); +} diff --git a/driver/src/main/java/org/neo4j/driver/internal/value/PathValue.java b/driver/src/main/java/org/neo4j/driver/internal/value/PathValue.java new file mode 100644 index 0000000000..e793a1a525 --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/value/PathValue.java @@ -0,0 +1,49 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.value; + +import org.neo4j.driver.internal.types.InternalTypeSystem; +import org.neo4j.driver.v1.Path; +import org.neo4j.driver.v1.Type; + +public class PathValue extends GraphValueAdapter +{ + public PathValue( Path adapted ) + { + super( adapted ); + } + + public Path asPath() + { + return asObject(); + } + + @Override + public int size() + { + return asObject().length(); + } + + @Override + public Type type() + { + return InternalTypeSystem.TYPE_SYSTEM.PATH(); + } + +} diff --git a/driver/src/main/java/org/neo4j/driver/internal/value/RelationshipValue.java b/driver/src/main/java/org/neo4j/driver/internal/value/RelationshipValue.java new file mode 100644 index 0000000000..f368c029bf --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/value/RelationshipValue.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.value; + +import org.neo4j.driver.internal.types.InternalTypeSystem; +import org.neo4j.driver.v1.Relationship; +import org.neo4j.driver.v1.Type; + +public class RelationshipValue extends EntityValueAdapter +{ + public RelationshipValue( Relationship adapted ) + { + super( adapted ); + } + + @Override + public Relationship asRelationship() + { + return asEntity(); + } + + @Override + public Type type() + { + return InternalTypeSystem.TYPE_SYSTEM.RELATIONSHIP(); + } +} diff --git a/driver/src/main/java/org/neo4j/driver/internal/value/ScalarValueAdapter.java b/driver/src/main/java/org/neo4j/driver/internal/value/ScalarValueAdapter.java new file mode 100644 index 0000000000..b5a5c793b1 --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/value/ScalarValueAdapter.java @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.value; + +public abstract class ScalarValueAdapter extends ValueAdapter +{ + @Override + public abstract String asLiteralString(); + + @Override + public String toString( Format valueFormat ) + { + return maybeWithType( valueFormat.includeType(), asLiteralString() ); + } +} diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/value/StringValue.java b/driver/src/main/java/org/neo4j/driver/internal/value/StringValue.java similarity index 56% rename from driver/src/main/java/org/neo4j/driver/v1/internal/value/StringValue.java rename to driver/src/main/java/org/neo4j/driver/internal/value/StringValue.java index 3240c0e9e7..c57af263df 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/value/StringValue.java +++ b/driver/src/main/java/org/neo4j/driver/internal/value/StringValue.java @@ -16,64 +16,81 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.value; +package org.neo4j.driver.internal.value; +import org.neo4j.driver.internal.types.InternalTypeSystem; import org.neo4j.driver.v1.Type; -import org.neo4j.driver.v1.internal.types.StandardTypeSystem; -import org.neo4j.driver.v1.internal.types.TypeConstructor; +import org.neo4j.driver.v1.exceptions.value.Unrepresentable; -public class StringValue extends ValueAdapter +public class StringValue extends ScalarValueAdapter { private final String val; public StringValue( String val ) { - assert val != null; + if ( val == null ) + { + throw new IllegalArgumentException( "Cannot construct StringValue from null" ); + } this.val = val; } @Override - public boolean javaBoolean() + public boolean isEmpty() { - return !val.isEmpty(); + return val.isEmpty(); } @Override - public String javaString() + public int size() { - return val; + return val.length(); } @Override - public boolean isString() + public String asObject() { - return true; + return asString(); } @Override - public long size() + public String asString() { - return val.length(); + return val; } @Override - public TypeConstructor typeConstructor() + public String asLiteralString() { - return TypeConstructor.STRING_TyCon; + return String.format( "\"%s\"", val.replace( "\"", "\\\"" ) ); } @Override - public Type type() + public char[] asCharArray() { - return StandardTypeSystem.TYPE_SYSTEM.STRING(); + return val.toCharArray(); } @Override - public String toString() + public char asChar() { - return val; + if ( val.length() == 1 ) + { + return val.charAt( 0 ); + } + else + { + throw new Unrepresentable( "Only a STRING of exactly one character can be represented as a Java char" ); + } } + @Override + public Type type() + { + return InternalTypeSystem.TYPE_SYSTEM.STRING(); + } + + @SuppressWarnings("StringEquality") @Override public boolean equals( Object o ) { @@ -87,9 +104,7 @@ public boolean equals( Object o ) } StringValue values = (StringValue) o; - - return val.equals( values.val ); - + return val == values.val || val.equals( values.val ); } @Override diff --git a/driver/src/main/java/org/neo4j/driver/internal/value/ValueAdapter.java b/driver/src/main/java/org/neo4j/driver/internal/value/ValueAdapter.java new file mode 100644 index 0000000000..44336cad75 --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/internal/value/ValueAdapter.java @@ -0,0 +1,351 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.value; + +import java.util.List; +import java.util.Map; + +import org.neo4j.driver.internal.InternalProperty; +import org.neo4j.driver.internal.types.TypeConstructor; +import org.neo4j.driver.internal.types.TypeRepresentation; +import org.neo4j.driver.internal.util.Extract; +import org.neo4j.driver.v1.Entity; +import org.neo4j.driver.v1.Function; +import org.neo4j.driver.v1.Identity; +import org.neo4j.driver.v1.Node; +import org.neo4j.driver.v1.Path; +import org.neo4j.driver.v1.Property; +import org.neo4j.driver.v1.Relationship; +import org.neo4j.driver.v1.Type; +import org.neo4j.driver.v1.Value; +import org.neo4j.driver.v1.exceptions.value.NotMultiValued; +import org.neo4j.driver.v1.exceptions.value.Uncoercible; +import org.neo4j.driver.v1.exceptions.value.Unsizable; + +import static java.lang.String.format; +import static java.util.Collections.emptyList; + +import static org.neo4j.driver.internal.value.InternalValue.Format.VALUE_WITH_TYPE; +import static org.neo4j.driver.v1.Values.valueAsIs; + +public abstract class ValueAdapter implements InternalValue +{ + @Override + public Value asValue() + { + return this; + } + + @Override + public boolean hasType( Type type ) + { + return type.isTypeOf( this ); + } + + @Override + public boolean isTrue() + { + return false; + } + + @Override + public boolean isFalse() + { + return false; + } + + @Override + public boolean isNull() + { + return false; + } + + public boolean containsKey( String key ) + { + throw new NotMultiValued( type().name() + " is not a keyed collection" ); + } + + @Override + public String asString() + { + throw new Uncoercible( type().name(), "Java String" ); + } + + public String asLiteralString() + { + throw new Uncoercible( type().name(), "Java String representation of Cypher literal" ); + } + + @Override + public char asChar() + { + throw new Uncoercible( type().name(), "Java char" ); + } + + @Override + public long asLong() + { + throw new Uncoercible( type().name(), "Java long" ); + } + + @Override + public int asInt() + { + throw new Uncoercible( type().name(), "Java int" ); + } + + @Override + public short asShort() + { + throw new Uncoercible( type().name(), "Java short" ); + } + + @Override + public byte asByte() + { + throw new Uncoercible( type().name(), "Java byte" ); + } + + @Override + public float asFloat() + { + throw new Uncoercible( type().name(), "Java float" ); + } + + @Override + public double asDouble() + { + throw new Uncoercible( type().name(), "Java double" ); + } + + @Override + public boolean asBoolean() + { + throw new Uncoercible( type().name(), "Java boolean" ); + } + + @Override + public List asList() + { + return asList( valueAsIs() ); + } + + @Override + public List asList( Function mapFunction ) + { + throw new Uncoercible( type().name(), "Java List" ); + } + + @Override + public Map asMap() + { + return asMap( valueAsIs() ); + } + + @Override + public Map asMap( Function mapFunction ) + { + throw new Uncoercible( type().name(), "Java Map" ); + } + + @Override + public Object asObject() + { + throw new Uncoercible( type().name(), "Java Object" ); + } + + @Override + public Value[] asArray() + { + return asArray( Value.class, valueAsIs() ); + } + + @Override + public T[] asArray( Class clazz, Function mapFunction ) + { + throw new Uncoercible( type().name(), "Java T[]" ); + } + + @Override + public char[] asCharArray() + { + throw new Uncoercible( type().name(), "Java char[]" ); + } + + @Override + public long[] asLongArray() + { + throw new Uncoercible( type().name(), "Java long[]" ); + } + + @Override + public int[] asIntArray() + { + throw new Uncoercible( type().name(), "Java int[]" ); + } + + @Override + public short[] asShortArray() + { + throw new Uncoercible( type().name(), "Java short[]" ); + } + + @Override + public byte[] asByteArray() + { + throw new Uncoercible( type().name(), "Java byte[]" ); + } + + @Override + public double[] asDoubleArray() + { + return new double[0]; + } + + @Override + public float[] asFloatArray() + { + return new float[0]; + } + + @Override + public Number asNumber() + { + throw new Uncoercible( type().name(), "Java Number" ); + } + + @Override + public Identity asIdentity() + { + throw new Uncoercible( type().name(), "Identity" ); + } + + @Override + public Entity asEntity() + { + throw new Uncoercible( type().name(), "Entity" ); + } + + @Override + public Node asNode() + { + throw new Uncoercible( type().name(), "Node" ); + } + + @Override + public Path asPath() + { + throw new Uncoercible( type().name(), "Path" ); + } + + @Override + public Relationship asRelationship() + { + throw new Uncoercible( type().name(), "Relationship" ); + } + + @Override + public Value value( int index ) + { + throw new NotMultiValued( type().name() + " is not an indexed collection" ); + } + + @Override + public Value value( String key ) + { + throw new NotMultiValued( type().name() + " is not a keyed collection" ); + } + + @Override + public int size() + { + throw new Unsizable( type().name() + " does not have size" ); + } + + @Override + public Iterable keys() + { + return emptyList(); + } + + @Override + public boolean isEmpty() + { + return ! values().iterator().hasNext(); + } + + @Override + public Iterable values() + { + return values( valueAsIs() ); + } + + @Override + public Iterable values( Function mapFunction ) + { + throw new NotMultiValued( type().name() + " is not iterable" ); + } + + @Override + public int propertyCount() + { + throw new NotMultiValued( type().name() + " is not a property map" ); + } + + @Override + public Property property( String key ) + { + return InternalProperty.of( key, value( key ) ); + } + + @Override + public Iterable> properties() + { + return properties( valueAsIs() ); + } + + @Override + public Iterable> properties( final Function mapFunction ) + { + return Extract.properties( this, mapFunction ); + } + + public String toString() + { + return toString( VALUE_WITH_TYPE ); + } + + protected String maybeWithType( boolean includeType, String text ) + { + return includeType ? withType( text ) : text; + } + + private String withType( String text ) + { + return format( "%s :: %s", text, type().name() ); + } + + @Override + public final TypeConstructor typeConstructor() + { + return ( (TypeRepresentation) type() ).constructor(); + } +} + + diff --git a/driver/src/main/java/org/neo4j/driver/v1/Config.java b/driver/src/main/java/org/neo4j/driver/v1/Config.java index 33e5938a3e..9936f15d72 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/Config.java +++ b/driver/src/main/java/org/neo4j/driver/v1/Config.java @@ -21,10 +21,10 @@ import java.io.File; import java.util.logging.Level; -import org.neo4j.driver.v1.internal.logging.JULogging; -import org.neo4j.driver.v1.internal.spi.Logging; +import org.neo4j.driver.internal.logging.JULogging; +import org.neo4j.driver.internal.spi.Logging; -import static org.neo4j.driver.v1.Config.TlsAuthenticationConfig.*; +import static org.neo4j.driver.v1.Config.TlsAuthenticationConfig.usingKnownCerts; /** * A configuration class to config driver properties. @@ -39,6 +39,7 @@ * } * */ +@Immutable public class Config { public static final String SCHEME = "bolt"; diff --git a/driver/src/main/java/org/neo4j/driver/v1/Directed.java b/driver/src/main/java/org/neo4j/driver/v1/Directed.java index f8cfd273fc..cf44fc7764 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/Directed.java +++ b/driver/src/main/java/org/neo4j/driver/v1/Directed.java @@ -24,6 +24,7 @@ * * @param the type of the objects at the start and end of this directed item */ +@Immutable public interface Directed { /** @return the start item from this directed sequence */ diff --git a/driver/src/main/java/org/neo4j/driver/v1/Driver.java b/driver/src/main/java/org/neo4j/driver/v1/Driver.java index cc2e6e1460..5b529135cd 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/Driver.java +++ b/driver/src/main/java/org/neo4j/driver/v1/Driver.java @@ -20,10 +20,9 @@ import java.net.URI; -import org.neo4j.driver.v1.internal.StandardSession; -import org.neo4j.driver.v1.internal.pool.StandardConnectionPool; -import org.neo4j.driver.v1.internal.spi.ConnectionPool; -import org.neo4j.driver.v1.internal.types.StandardTypeSystem; +import org.neo4j.driver.internal.InternalSession; +import org.neo4j.driver.internal.pool.InternalConnectionPool; +import org.neo4j.driver.internal.spi.ConnectionPool; /** * A Neo4j database driver, through which you can create {@link Session sessions} to run statements against the database. @@ -53,7 +52,7 @@ * List names = new LinkedList<>(); * while( result.next() ) * { - * names.add( result.get("n.name").javaString() ); + * names.add( result.value("n.name").asString() ); * } * * // Sessions are pooled, to avoid the overhead of creating new connections - this means @@ -79,7 +78,7 @@ public class Driver implements AutoCloseable public Driver( URI url, Config config ) { this.url = url; - this.connections = new StandardConnectionPool( config ); + this.connections = new InternalConnectionPool( config ); } /** @@ -89,21 +88,13 @@ public Driver( URI url, Config config ) */ public Session session() { - return new StandardSession( connections.acquire( url ) ); + return new InternalSession( connections.acquire( url ) ); // TODO a ConnectionPool per URL - // ConnectionPool connections = new StandardConnectionPool( logging, url ); - // And to get a connection from the pool could be + // ConnectionPool connections = new InternalConnectionPool( logging, url ); + // And to value a connection from the pool could be // connections.acquire(); } - /** - * @return type system used by this driver for classifying values - */ - public TypeSystem typeSystem() - { - return StandardTypeSystem.TYPE_SYSTEM; - } - /** * Close all the resources assigned to this driver * @throws Exception any error that might happen when releasing all resources diff --git a/driver/src/main/java/org/neo4j/driver/v1/Entity.java b/driver/src/main/java/org/neo4j/driver/v1/Entity.java index db054ff25a..0a703380f9 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/Entity.java +++ b/driver/src/main/java/org/neo4j/driver/v1/Entity.java @@ -21,7 +21,8 @@ /** * A uniquely identifiable property container that can form part of a Neo4j graph. */ -public interface Entity +@Immutable +public interface Entity extends PropertyMapAccessor { /** * A unique {@link Identity identity} for this Entity. Identities are guaranteed @@ -32,27 +33,4 @@ public interface Entity * @return an identity object */ Identity identity(); - - /** - * Return all property keys. - * - * @return a property key Collection - */ - Iterable propertyKeys(); - - /** - * Number of properties in this entity. - * - * @return the number of properties this entity contains. - */ - int propertyCount(); - - /** - * Return a specific property {@link Value}. If no value could be found with the specified key, - * null will be returned. - * - * @param key a property key - * @return the property value or null - */ - Value property( String key ); } diff --git a/driver/src/main/java/org/neo4j/driver/v1/Field.java b/driver/src/main/java/org/neo4j/driver/v1/Field.java new file mode 100644 index 0000000000..86a60402d2 --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/v1/Field.java @@ -0,0 +1,49 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.v1; + +/** + * A field is a property of an ordered map or record + * + * @param the type of value stored + * + * @see Property + * @see PropertyMapAccessor + * @see RecordAccessor + */ +@Immutable +public interface Field +{ + /** + * @return the property key + */ + String key(); + + /** + * @return the property value + */ + V value(); + + /** + * @return the index of the field in the original record + */ + int index(); + + Property asProperty(); +} diff --git a/driver/src/main/java/org/neo4j/driver/v1/Identity.java b/driver/src/main/java/org/neo4j/driver/v1/Identity.java index 6fdde4bac0..6cd06cedb9 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/Identity.java +++ b/driver/src/main/java/org/neo4j/driver/v1/Identity.java @@ -26,6 +26,7 @@ * stable 'ids' for your entities, you may choose to add an 'id' property with a {@link java.util.UUID} or similar * unique value. */ +@Immutable public interface Identity { // Force implementation diff --git a/driver/src/main/java/org/neo4j/driver/v1/Immutable.java b/driver/src/main/java/org/neo4j/driver/v1/Immutable.java new file mode 100644 index 0000000000..ed5bb43d1f --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/v1/Immutable.java @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.v1; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Indicates that instances of an annotated class are immutable + */ +@Inherited +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Target( { ElementType.TYPE } ) +public @interface Immutable +{ +} diff --git a/driver/src/main/java/org/neo4j/driver/v1/InputPosition.java b/driver/src/main/java/org/neo4j/driver/v1/InputPosition.java index c043c27f21..58b951d11d 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/InputPosition.java +++ b/driver/src/main/java/org/neo4j/driver/v1/InputPosition.java @@ -21,6 +21,7 @@ /** * An input position refers to a specific character in a statement. */ +@Immutable public interface InputPosition { /** @@ -28,19 +29,19 @@ public interface InputPosition * * @return the offset of this position. */ - public int offset(); + int offset(); /** * The line number referred to by the position; line numbers start at 1. * * @return the line number of this position. */ - public int line(); + int line(); /** * The column number referred to by the position; column numbers start at 1. * * @return the column number of this position. */ - public int column(); + int column(); } diff --git a/driver/src/main/java/org/neo4j/driver/v1/ListAccessor.java b/driver/src/main/java/org/neo4j/driver/v1/ListAccessor.java new file mode 100644 index 0000000000..15fd74c4ff --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/v1/ListAccessor.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.v1; + +import org.neo4j.driver.v1.exceptions.ClientException; + +/** + * Access an underlying list of values by index + * + * This provides only read methods. Subclasses may chose to provide additional methods + * for changing the underlying list. + * * + * @see Value + */ +public interface ListAccessor +{ + /** + * Retrieve the value at the given index + * + * @param index the index of the value + * @return the value or a {@link org.neo4j.driver.internal.value.NullValue} if the index is out of bounds + * @throws ClientException if record has not been initialized + */ + Value value( int index ); +} + + diff --git a/driver/src/main/java/org/neo4j/driver/v1/MapAccessor.java b/driver/src/main/java/org/neo4j/driver/v1/MapAccessor.java new file mode 100644 index 0000000000..2962060efa --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/v1/MapAccessor.java @@ -0,0 +1,55 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.v1; + +import org.neo4j.driver.internal.value.NullValue; +import org.neo4j.driver.v1.exceptions.ClientException; + +/** + * Access the keys, properties and values of an underlying unordered map by key + * + * This provides only read methods. Subclasses may chose to provide additional methods + * for changing the underlying map. + */ +public interface MapAccessor +{ + /** + * Retrieve the keys of the underlying map + * + * @return all map keys in unspecified order + */ + Iterable keys(); + + /** + * Check if the list of keys contains the given key + * + * @param key the key + * @return true if this map keys contains the given key otherwise false + */ + boolean containsKey( String key ); + + /** + * Retrieve the value of the property with the given key + * + * @param key the key of the property + * @return the property's value or a {@link NullValue} if no such key exists + * @throws ClientException if record has not been initialized + */ + Value value( String key ); +} diff --git a/driver/src/main/java/org/neo4j/driver/v1/Node.java b/driver/src/main/java/org/neo4j/driver/v1/Node.java index d213309c26..604d099b23 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/Node.java +++ b/driver/src/main/java/org/neo4j/driver/v1/Node.java @@ -29,4 +29,12 @@ public interface Node extends Entity * @return a label Collection */ Iterable labels(); + + /** + * Test if this node has a given label + * + * @param label the label + * @return true if this node has the label otherwise false + */ + boolean hasLabel( String label ); } diff --git a/driver/src/main/java/org/neo4j/driver/v1/Notification.java b/driver/src/main/java/org/neo4j/driver/v1/Notification.java index e78e16698c..1995d6a757 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/Notification.java +++ b/driver/src/main/java/org/neo4j/driver/v1/Notification.java @@ -23,6 +23,7 @@ * * A notification can be visualized in a client pinpointing problems or other information about the statement. */ +@Immutable public interface Notification { /** diff --git a/driver/src/main/java/org/neo4j/driver/v1/Path.java b/driver/src/main/java/org/neo4j/driver/v1/Path.java index 99454bbddd..90db7afac7 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/Path.java +++ b/driver/src/main/java/org/neo4j/driver/v1/Path.java @@ -36,6 +36,7 @@ * } * */ +@Immutable public interface Path extends Iterable { /** @@ -61,7 +62,7 @@ interface Segment extends Directed Node end(); /** @return the number of segments in this path, which will be the same as the number of relationships */ - long length(); + int length(); /** * @param node the node to check for diff --git a/driver/src/main/java/org/neo4j/driver/v1/Plan.java b/driver/src/main/java/org/neo4j/driver/v1/Plan.java index 92afebb77e..3509f3ae18 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/Plan.java +++ b/driver/src/main/java/org/neo4j/driver/v1/Plan.java @@ -33,6 +33,7 @@ * * For a simple view of a plan, the {@code toString} method will give a human-readable rendering of the tree. */ +@Immutable public interface Plan { /** diff --git a/driver/src/main/java/org/neo4j/driver/v1/Property.java b/driver/src/main/java/org/neo4j/driver/v1/Property.java new file mode 100644 index 0000000000..57dd57abe5 --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/v1/Property.java @@ -0,0 +1,39 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.v1; + +/** + * Immutable pair of a key and a value + * + * @see PropertyMapAccessor + * @param the Java type of the contained value + */ +@Immutable +public interface Property +{ + /** + * @return the property key + */ + String key(); + + /** + * @return the property value + */ + V value(); +} diff --git a/driver/src/main/java/org/neo4j/driver/v1/PropertyMapAccessor.java b/driver/src/main/java/org/neo4j/driver/v1/PropertyMapAccessor.java new file mode 100644 index 0000000000..0995cf61cd --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/v1/PropertyMapAccessor.java @@ -0,0 +1,77 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.v1; + +/** + * Access the properties of an underlying unordered map + * + * This provides only read methods. Subclasses may chose to provide additional methods + * for changing the underlying map. + */ +public interface PropertyMapAccessor extends MapAccessor +{ + /** + * Retrieve all values of the underlying collection + * + * @return all values in unspecified order + */ + Iterable values(); + + /** + * Map and retrieve all values of the underlying collection + * + * @param mapFunction a function to map from Value to T. See {@link Values} for some predefined functions, such + * as {@link Values#valueAsBoolean()}, {@link Values#valueAsList(Function)}. + * @param the target type of mapping + * @return the result of mapping all values in unspecified order + */ + Iterable values( Function mapFunction ); + + /** + * @return number of properties in this property map + */ + int propertyCount(); + + /** + * Retrieve the property for the given key + * + * @param key the key of the property + * @return the property for the given key or a property with a null value if the key is unknown + */ + Property property( String key ); + + /** + * Retrieve all properties of the underlying map + * + * @see Property + * @return all properties in unspecified order + */ + Iterable> properties(); + + /** + * Retrieve all properties of the underlying map + * + * @see Property + * @param mapFunction a function to map from Value to T. See {@link Values} for some predefined functions, such + * as {@link Values#valueAsBoolean()}, {@link Values#valueAsList(Function)}. + * @param the target type of mapping + * @return all mapped properties in unspecified order + */ + Iterable> properties( Function mapFunction ); +} diff --git a/driver/src/main/java/org/neo4j/driver/v1/Record.java b/driver/src/main/java/org/neo4j/driver/v1/Record.java index 30c93ac015..6e7ffe40ec 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/Record.java +++ b/driver/src/main/java/org/neo4j/driver/v1/Record.java @@ -18,34 +18,35 @@ */ package org.neo4j.driver.v1; +import java.util.Map; + /** - * A record is a collection of named fields, and is what makes up the individual items in a {@link - * Result} + * A record is an immutable copy of an ordered map + * + * @see Result#record() + * @see Result#retain() */ -public interface Record +@Immutable +public interface Record extends RecordAccessor { /** - * From the current record the result is pointing to, retrieve the value in the specified field. - * - * @param fieldIndex the field index into the current record - * @return the value in the specified field + * @return the value as a value map */ - Value get( int fieldIndex ); + Map asMap(); /** - * From the current record the result is pointing to, retrieve the value in the specified field. - * If no value could be found in the specified filed, null will be returned. - * - * @param fieldName the field to retrieve the value from - * @return the value in the specified field or null if no value could be found in the field. + * @param mapFunction a function to map from Value to T. See {@link Values} for some predefined functions, such + * as {@link Values#valueAsBoolean()}, {@link Values#valueAsList(Function)}. + * @param the type of map values + * @return the value as a map from string keys to values of type T */ - Value get( String fieldName ); + Map asMap( Function mapFunction ); - /** - * Get an ordered sequence of the field names in this result. - * - * @return field names - */ - Iterable fieldNames(); + // Force implementation + @Override + boolean equals( Object other ); + // Force implementation + @Override + int hashCode(); } diff --git a/driver/src/main/java/org/neo4j/driver/v1/RecordAccessor.java b/driver/src/main/java/org/neo4j/driver/v1/RecordAccessor.java new file mode 100644 index 0000000000..dc41225d4e --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/v1/RecordAccessor.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.v1; + +import java.util.List; + +import org.neo4j.driver.v1.exceptions.ClientException; + +/** + * Access an underlying record (which is an ordered map of fields) + * + * This provides only read methods. Subclasses may chose to provide additional methods + * for changing the underlying record. + * + * @see Field + */ +public interface RecordAccessor extends ListAccessor, MapAccessor +{ + @Override + List keys(); + + /** + * Retrieve the key of the field for the given index + * + * @param index the index of the key + * @return the key of the field for the given index + */ + String key( int index ); + + /** + * Retrieve the index of the field with the given key + * + * @throws java.util.NoSuchElementException if the given key is not from {@link #keys()} + * @param key the give key + * @return the index of the field as used by {@link #value(int)} + */ + int index( String key ); + + /** + * Retrieve the field for the given key + * + * @param key the key + * @return the field for the given key + */ + Field field( String key ); + + /** + * Retrieve the field at the given index + * + * @param index the index + * @return the field at the given index + */ + Field field( int index ); + + /** + * @return number of fields in this record + */ + int fieldCount(); + + /** + * Retrieve all record fields + * + * @return all fields in key order + * @throws ClientException if record has not been initialized. + */ + List> fields(); + + /** + * Map and retrieve all record fields + * + * @param the target type of the map function + * @param mapFunction a function to map from Value to T. See {@link Values} for some predefined functions, such + * as {@link Values#valueAsBoolean()}, {@link Values#valueAsList(Function)}. + * @return the result of mapping all record fields in key order + * @throws ClientException if record has not been initialized. + */ + List> fields( Function mapFunction ); + + /** + * @return an immutable copy of the currently viewed record + */ + Record record(); +} diff --git a/driver/src/main/java/org/neo4j/driver/v1/Records.java b/driver/src/main/java/org/neo4j/driver/v1/Records.java new file mode 100644 index 0000000000..7323b80405 --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/v1/Records.java @@ -0,0 +1,79 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.v1; + +/** + * Static utility methods for retaining records + * + * @see Result#retain() + */ +public abstract class Records +{ + private Records() + { + throw new UnsupportedOperationException(); + } + + public static Function recordAsIs() + { + return RECORD; + } + + public static Function columnAsIs( int index ) + { + return column( index, Values.valueAsIs() ); + } + + public static Function columnAsIs( String key ) + { + return column( key, Values.valueAsIs() ); + } + + public static Function column( final int index, final Function mapFunction ) + { + return new Function() + { + @Override + public T apply( RecordAccessor recordAccessor ) + { + return mapFunction.apply( recordAccessor.value( index ) ); + } + }; + } + public static Function column( final String key, final Function mapFunction ) + { + return new Function() + { + @Override + public T apply( RecordAccessor recordAccessor ) + { + return mapFunction.apply( recordAccessor.value( key ) ); + } + }; + } + + private static final Function RECORD = new Function() + { + @Override + public Record apply( RecordAccessor recordAccessor ) + { + return recordAccessor.record(); + } + }; +} diff --git a/driver/src/main/java/org/neo4j/driver/v1/Relationship.java b/driver/src/main/java/org/neo4j/driver/v1/Relationship.java index cbf803f9b5..267f4776df 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/Relationship.java +++ b/driver/src/main/java/org/neo4j/driver/v1/Relationship.java @@ -29,4 +29,12 @@ public interface Relationship extends Directed, Entity * @return the type name */ String type(); + + /** + * Test if this relationship has the given type + * + * @param relationshipType the give relationship type + * @return true if this relationship has the given relationship type otherwise false + */ + boolean hasType( String relationshipType ); } diff --git a/driver/src/main/java/org/neo4j/driver/v1/ReusableResult.java b/driver/src/main/java/org/neo4j/driver/v1/Resource.java similarity index 51% rename from driver/src/main/java/org/neo4j/driver/v1/ReusableResult.java rename to driver/src/main/java/org/neo4j/driver/v1/Resource.java index 62106d6d1b..0711a3c473 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/ReusableResult.java +++ b/driver/src/main/java/org/neo4j/driver/v1/Resource.java @@ -19,32 +19,24 @@ package org.neo4j.driver.v1; /** - * A {@link Result} that has been fully retrieved and stored from the server. - * It can therefore be kept outside the scope of the current transaction, iterated over multiple times and used while - * other statements are issued. - * For instance: - *

    - * {@code - * for(Record v : session.run( ".." ).retain() ) - * { - * session.run( ".." ); - * } - * } + * A Resource is an {@link AutoCloseable} that allows introspecting if it + * already has been closed through its {@link #isOpen()} method. + * + * Additionally, calling {@link AutoCloseable#close()} twice is expected to fail + * (i.e. is not idempotent). */ -public interface ReusableResult extends Iterable +public interface Resource extends AutoCloseable { /** - * The number of values in this result. + * Detect whether this resource is still open * - * @return the result record count + * @return true if the resource is open */ - long size(); + boolean isOpen(); /** - * Retrieve a record from this result based on its position in the original result stream. - * - * @param index retrieve an item in the result by index - * @return the requested record + * @throws IllegalStateException if already closed */ - Record get( long index ); + @Override + void close(); } diff --git a/driver/src/main/java/org/neo4j/driver/v1/Result.java b/driver/src/main/java/org/neo4j/driver/v1/Result.java index f15a217a7e..dd281ddaf5 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/Result.java +++ b/driver/src/main/java/org/neo4j/driver/v1/Result.java @@ -18,81 +18,109 @@ */ package org.neo4j.driver.v1; +import java.util.List; + import org.neo4j.driver.v1.exceptions.ClientException; + /** - * The result of running a statement, a stream of records. The result interface can be used to iterate over all the - * records in the stream, and for each record to access the fields within it using the {@link #get(int) get} methods. + * The result of running a statement, a stream of records represented as a cursor. + * + * The result cursor can be used to iterate over all the records in the stream and provide access + * to their content. * - * Results are valid until the next statement is run or until the end of the current transaction, whichever comes - * first. + * Results are valid until the next statement is run or until the end of the current transaction, + * whichever comes first. * - * To keep a result around while further statements are run, or to use a result outside the scope of the current - * transaction, see {@link #retain()}. + * Initially, before {@link #next()} has been called at least once, all field values are null. + * + * To keep a result around while further statements are run, or to use a result outside the scope + * of the current transaction, see {@link #retain()}. */ -public interface Result +public interface Result extends RecordAccessor, Resource { /** - * Retrieve and store the entire result stream. This can be used if you want to - * iterate over the stream multiple times or to store the whole result for later use. + * @return an immutable copy of the currently viewed record + * @throws ClientException if no calls has been made to {@link #next()}, {@link #first()}, nor {@link #skip(long)} + */ + @Override + Record record(); + + /** + * Retrieve the zero based position of the cursor in the stream of records. * - * This cannot be used if you have already started iterating through the stream using {@link #next()}. + * Initially, before {@link #next()} has been called at least once, the position is -1. + * + * @return the current position of the cursor + */ + long position(); + + /** + * Test if the cursor is positioned at the last stream record or if the stream is empty. * - * @return {@link ReusableResult} + * @return true if the cursor is at the last record or the stream is empty. */ - ReusableResult retain(); + boolean atEnd(); /** * Move to the next record in the result. * - * @return true if there was another record, false if the stream is exhausted. + * @return true if there was another record, false if the stream is exhausted. */ boolean next(); /** - * From the current record the result is pointing to, retrieve the value in the specified field. + * Advance the cursor as if calling next multiple times. * - * @param fieldIndex the field index into the current record - * @return the value in the specified field + * @throws IllegalArgumentException if records is negative + * @param records amount of records to be skipped + * @return the actual number of records successfully skipped */ - Value get( int fieldIndex ); + long skip( long records ); /** - * From the current record the result is pointing to, retrieve the value in the specified field. - * If no value could be found in the specified filed, null will be returned. + * Move to the first record if possible, otherwise do nothing. * - * @param fieldName the field to retrieve the value from - * @return the value in the specified field or null if no value could be found in the specified filed + * @return true if the cursor is placed on the first record */ - Value get( String fieldName ); + boolean first(); /** - * Get an ordered sequence of the field names in this result. + * Move to the first record if possible and verify that it is the only record. * - * @return field names + * @return true if the cursor was successfully placed at the single first and only record */ - Iterable fieldNames(); + boolean single(); /** - * Retrieve the first field of the next record in the stream, and close the stream. - * - * This is a utility for the common case of statements that are expected to yield a single output value. + * Retrieve and store the entire result stream. + * This can be used if you want to iterate over the stream multiple times or to store the + * whole result for later use. * - *

    -     * {@code
    -     * Record record = statement.run( "MATCH (n:User {uid:..}) RETURN n.name" ).single();
    -     * }
    -     * 
    + * Calling this method exhausts the result cursor and moves it to the last record + * @throws ClientException if the cursor can't be positioned at the first record + * @return list of all immutable records + */ + List retain(); + + /** + * Retrieve and store a projection of the entire result stream. + * This can be used if you want to iterate over the stream multiple times or to store the + * whole result for later use. * - * @return a single record from the stream - * @throws ClientException if the stream is empty + * Calling this method exhausts the result cursor and moves it to the last record + * @throws ClientException if the cursor can't be positioned at the first record + * @param mapFunction a function to map from Value to T. See {@link Values} for some predefined functions, such + * as {@link Values#valueAsBoolean()}, {@link Values#valueAsList(Function)}. + * @param the type of result list elements + * @return list of all mapped immutable records */ - Record single(); + List retain( Function mapFunction ); /** - * Summarize the result + * Summarize the result. * - * Any remaining (unprocessed) result records will be consumed. + * Calling this method exhausts the result cursor and moves it to the last record. * *
          * {@code
    diff --git a/driver/src/main/java/org/neo4j/driver/v1/ResultSummary.java b/driver/src/main/java/org/neo4j/driver/v1/ResultSummary.java
    index b659fb8a94..17e394fa66 100644
    --- a/driver/src/main/java/org/neo4j/driver/v1/ResultSummary.java
    +++ b/driver/src/main/java/org/neo4j/driver/v1/ResultSummary.java
    @@ -29,6 +29,7 @@
      *
      * Keeping the result summary around does not influence the lifecycle of any associated session and/or transaction.
      */
    +@Immutable
     public interface ResultSummary
     {
         /**
    @@ -78,7 +79,9 @@ public interface ResultSummary
          * A list of notifications that might arise when executing the statement.
          * Notifications can be warnings about problematic statements or other valuable information that can be presented
          * in a client.
    +     *
          * Unlike failures or errors, notifications do not affect the execution of a statement.
    +     *
          * @return a list of notifications produced while executing the statement. The list will be empty if no
          * notifications produced while executing the statement.
          */
    diff --git a/driver/src/main/java/org/neo4j/driver/v1/Session.java b/driver/src/main/java/org/neo4j/driver/v1/Session.java
    index b9d81f6e4e..1feb6d42d5 100644
    --- a/driver/src/main/java/org/neo4j/driver/v1/Session.java
    +++ b/driver/src/main/java/org/neo4j/driver/v1/Session.java
    @@ -30,7 +30,7 @@
      * Session objects are not thread safe, if you want to run concurrent operations against the database,
      * simply create multiple sessions objects.
      */
    -public interface Session extends AutoCloseable, StatementRunner
    +public interface Session extends Resource, StatementRunner
     {
         /**
          * Begin a new transaction in this session. A session can have at most one transaction running at a time, if you
    @@ -46,7 +46,4 @@ public interface Session extends AutoCloseable, StatementRunner
          * @return a new transaction
          */
         Transaction beginTransaction();
    -
    -    @Override
    -    void close();
     }
    diff --git a/driver/src/main/java/org/neo4j/driver/v1/Statement.java b/driver/src/main/java/org/neo4j/driver/v1/Statement.java
    index 93d67c3778..06eb9ac27b 100644
    --- a/driver/src/main/java/org/neo4j/driver/v1/Statement.java
    +++ b/driver/src/main/java/org/neo4j/driver/v1/Statement.java
    @@ -22,7 +22,7 @@
     import java.util.HashMap;
     import java.util.Map;
     
    -import org.neo4j.driver.v1.internal.ParameterSupport;
    +import org.neo4j.driver.internal.ParameterSupport;
     
     import static java.lang.String.format;
     
    @@ -35,30 +35,31 @@
      * @see Result#summarize()
      * @see ResultSummary
      */
    +@Immutable
     public class Statement
     {
    -    private final String text;
    +    private final String template;
         private final Map parameters;
     
    -    public Statement( String text, Map parameters )
    +    public Statement( String template, Map parameters )
         {
    -        this.text = text;
    +        this.template = template;
             this.parameters = parameters == null || parameters.isEmpty()
                 ? ParameterSupport.NO_PARAMETERS
                 : Collections.unmodifiableMap( parameters );
         }
     
    -    public Statement( String text )
    +    public Statement( String template )
         {
    -        this( text, null );
    +        this( template, null );
         }
     
         /**
    -     * @return the statement's text
    +     * @return the statement's template
          */
    -    public String text()
    +    public String template()
         {
    -        return text;
    +        return template;
         }
     
         /**
    @@ -70,12 +71,12 @@ public Map parameters()
         }
     
         /**
    -     * @param newText the new statement's text
    -     * @return a new statement with updated text
    +     * @param newTemplate the new statement's template
    +     * @return a new statement with updated template
          */
    -    public Statement withText( String newText )
    +    public Statement withTemplate( String newTemplate )
         {
    -        return new Statement( newText, parameters );
    +        return new Statement( newTemplate, parameters );
         }
     
         /**
    @@ -84,7 +85,7 @@ public Statement withText( String newText )
          */
         public Statement withParameters( Map newParameters )
         {
    -        return new Statement( text, newParameters );
    +        return new Statement( template, newParameters );
         }
     
         /**
    @@ -137,14 +138,14 @@ public boolean equals( Object o )
             }
     
             Statement statement = (Statement) o;
    -        return text.equals( statement.text ) && parameters.equals( statement.parameters );
    +        return template.equals( statement.template ) && parameters.equals( statement.parameters );
     
         }
     
         @Override
         public int hashCode()
         {
    -        int result = text.hashCode();
    +        int result = template.hashCode();
             result = 31 * result + parameters.hashCode();
             return result;
         }
    @@ -152,6 +153,6 @@ public int hashCode()
         @Override
         public String toString()
         {
    -        return format( "Statement{text='%s', parameters=%s}", text, parameters );
    +        return format( "Statement{template='%s', parameters=%s}", template, parameters );
         }
     }
    diff --git a/driver/src/main/java/org/neo4j/driver/v1/StatementRunner.java b/driver/src/main/java/org/neo4j/driver/v1/StatementRunner.java
    index 75ee7055d7..e5fc57a1a4 100644
    --- a/driver/src/main/java/org/neo4j/driver/v1/StatementRunner.java
    +++ b/driver/src/main/java/org/neo4j/driver/v1/StatementRunner.java
    @@ -39,24 +39,24 @@ public interface StatementRunner
          * 

    Example

    *
          * {@code
    -     * Result res = session.run( "MATCH (n) WHERE n.name = {myNameParam} RETURN (n)",
    -     *              Values.parameters( "myNameParam", "Bob" ) );
    +     * Result cursor = session.run( "MATCH (n) WHERE n.name = {myNameParam} RETURN (n)",
    +     *                              Values.parameters( "myNameParam", "Bob" ) );
          * }
          * 
    * - * @param statementText text of a Neo4j statement - * @param parameters input data for the statement, see {@link Values#parameters(Object...)} + * @param statementTemplate template of a Neo4j statement + * @param statementParameters input data for the statement, see {@link Values#parameters(Object...)} * @return a stream of result values and associated metadata */ - Result run( String statementText, Map parameters ); + Result run( String statementTemplate, Map statementParameters ); /** * Run a statement and return a result stream. * - * @param statementText text of a Neo4j statement + * @param statementTemplate template of a Neo4j statement * @return a stream of result values and associated metadata */ - Result run( String statementText ); + Result run( String statementTemplate ); /** * Run a statement and return a result stream. @@ -64,7 +64,7 @@ public interface StatementRunner *
          * {@code
          * Statement statement = new Statement( "MATCH (n) WHERE n.name={myNameParam} RETURN n.age" );
    -     * Result res = session.run( statement.withParameters( Values.parameters( "myNameParam", "Bob" )  ) );
    +     * Result cursor = session.run( statement.withParameters( Values.parameters( "myNameParam", "Bob" )  ) );
          * }
          * 
    * @@ -74,9 +74,7 @@ public interface StatementRunner Result run( Statement statement ); /** - * Detect whether this statement runner can be used, of if it has been closed. - * - * @return true if you can currently {@link #run(String) run} statements with this + * @return type system used by this statement runner for classifying values */ - boolean isOpen(); + TypeSystem typeSystem(); } diff --git a/driver/src/main/java/org/neo4j/driver/v1/Transaction.java b/driver/src/main/java/org/neo4j/driver/v1/Transaction.java index 5fac14d457..73bab2155c 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/Transaction.java +++ b/driver/src/main/java/org/neo4j/driver/v1/Transaction.java @@ -37,7 +37,7 @@ * } *
    */ -public interface Transaction extends AutoCloseable, StatementRunner +public interface Transaction extends Resource, StatementRunner { /** * Mark this transaction as successful. You must call this method before calling {@link #close()} to have your @@ -46,7 +46,7 @@ public interface Transaction extends AutoCloseable, StatementRunner void success(); /** - * Mark this transaction as failed. When you call {@link #close()}, the transaction will get rolled back. + * Mark this transaction as failed. When you call {@link #close()}, the transaction will value rolled back. * * After this method has been called, there is nothing that can be done to "un-mark" it. This is a safety feature * to make sure no other code calls {@link #success()} and makes a transaction commit that was meant to be rolled @@ -65,7 +65,4 @@ public interface Transaction extends AutoCloseable, StatementRunner * */ void failure(); - - @Override - void close(); } diff --git a/driver/src/main/java/org/neo4j/driver/v1/Type.java b/driver/src/main/java/org/neo4j/driver/v1/Type.java index 2d2bdd2b4d..4031ec15b8 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/Type.java +++ b/driver/src/main/java/org/neo4j/driver/v1/Type.java @@ -21,6 +21,7 @@ /** * The type of a {@link Value} as defined by the Cypher language */ +@Immutable public interface Type { /** diff --git a/driver/src/main/java/org/neo4j/driver/v1/TypeSystem.java b/driver/src/main/java/org/neo4j/driver/v1/TypeSystem.java index 3ac5d31902..2898beaa03 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/TypeSystem.java +++ b/driver/src/main/java/org/neo4j/driver/v1/TypeSystem.java @@ -18,6 +18,7 @@ */ package org.neo4j.driver.v1; +@Immutable public interface TypeSystem { Type ANY(); diff --git a/driver/src/main/java/org/neo4j/driver/v1/UpdateStatistics.java b/driver/src/main/java/org/neo4j/driver/v1/UpdateStatistics.java index 3c408fb947..2ec053a71b 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/UpdateStatistics.java +++ b/driver/src/main/java/org/neo4j/driver/v1/UpdateStatistics.java @@ -21,6 +21,7 @@ /** * Contains counters for the number of update operations performed by a statement. */ +@Immutable public interface UpdateStatistics { /** diff --git a/driver/src/main/java/org/neo4j/driver/v1/Value.java b/driver/src/main/java/org/neo4j/driver/v1/Value.java index 6e621fcd08..afc9e126f8 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/Value.java +++ b/driver/src/main/java/org/neo4j/driver/v1/Value.java @@ -21,6 +21,9 @@ import java.util.List; import java.util.Map; +import org.neo4j.driver.v1.exceptions.value.LossyCoercion; +import org.neo4j.driver.v1.exceptions.value.Uncoercible; + /** * Represents a value from Neo4j. * @@ -54,7 +57,7 @@ * *
      * {@code
    - * String username = value.get("users").get(1).get("name").javaString();
    + * String username = value.value("users").value(1).value("name").asString();
      * }
      * 
    * @@ -63,155 +66,285 @@ *
      * {@code
      * List names = new LinkedList<>();
    - * for(Value user : value.get("users") )
    + * for(Value user : value.value("users").values() )
      * {
    - *     names.add(user.get("name").javaString());
    + *     names.add(user.value("name").asString());
      * }
      * }
      * 
    */ -public interface Value extends Iterable +@Immutable +public interface Value extends PropertyMapAccessor, ListAccessor { - /** @return the value as a Java String, if possible. */ - String javaString(); + /** + * If the underlying value is a collection type, return the number of values in the collection. + *

    + * For {@link TypeSystem#LIST()} list} values, this will return the size of the list. + *

    + * For {@link TypeSystem#MAP() map} values, this will return the number of entries in the map. + *

    + * For {@link TypeSystem#NODE() node} and {@link TypeSystem#RELATIONSHIP()} relationship} values, + * this will return the number of properties. + *

    + * For {@link TypeSystem#PATH() path} values, this returns the length (number of relationships) in the path. + * + * @return the number of values in an underlying collection + */ + int size(); + + /** + * Test if the underlying collection is empty + * + * @return true if size() is 0, otherwise false + */ + boolean isEmpty(); - /** @return the value as a Java int, if possible. */ - int javaInteger(); + /** + * If the underlying value supports {@link #value(String) key-based indexing}, return an iterable of the keys in the + * map, this applies to {@link TypeSystem#MAP() map}, {@link #asNode() node} and {@link + * TypeSystem#RELATIONSHIP()} relationship} values. + * + * @return the keys in the value + */ + @Override + Iterable keys(); + + /** @return The type of this value as defined in the Neo4j type system */ + Type type(); + + /** + * Test if this value is a value of the given type + * + * @param type the given type + * @return type.isTypeOf( this ) + */ + boolean hasType( Type type ); + + /** + * @return true if the value is a Boolean value and has the value True. + */ + boolean isTrue(); - /** @return the value as a Java long, if possible. */ - long javaLong(); + /** + * @return true if the value is a Boolean value and has the value False. + */ + boolean isFalse(); - /** @return the value as a Java float, if possible. */ - float javaFloat(); + /** + * @return true if the value is a Null, otherwise false + */ + boolean isNull(); - /** @return the value as a Java double, if possible. */ - double javaDouble(); + /** @return the value as a Java Object */ + Object asObject(); /** - * If the value represents a number, this method will return true if the number is not equals to 0. - * If the value represents a collection, this method will return true if the collection is not empty. - * If the value represents a string, this method will return true, if the string is not empty. * @return the value as a Java boolean, if possible. + * @throws Uncoercible if value types are incompatible. */ - boolean javaBoolean(); + boolean asBoolean(); /** - * @param mapFunction a function to map from Value to T. See {@link Values} for some predefined functions, such - * as {@link Values#valueToBoolean()}, {@link Values#valueToList(Function)}. - * @param the type of list elements - * @return the value as a list of T, if possible + * @return the value as a Java String, if possible. + * @throws Uncoercible if value types are incompatible. */ - List javaList( Function mapFunction ); + String asString(); /** - * @param mapFunction a function to map from Value to T. See {@link Values} for some predefined functions, such - * as {@link Values#valueToBoolean()}, {@link Values#valueToList(Function)}. - * @param the type of map values - * @return the value as a map from string keys to values of type T, if possible + * @return the value as a Cypher literal, if possible + * @throws Uncoercible if value types are incompatible. */ - Map javaMap( Function mapFunction ); + String asLiteralString(); - /** @return the value as an {@link Identity}, if possible. */ - Identity asIdentity(); + /** + * @return the value as a Java char, if possible. + * @throws Uncoercible if value types are incompatible. + */ + char asChar(); - /** @return the value as a {@link Node}, if possible. */ - Node asNode(); + /** + * @return the value as a Java Number, if possible. + * @throws Uncoercible if value types are incompatible. + */ + Number asNumber(); - /** @return the value as a {@link Relationship}, if possible. */ - Relationship asRelationship(); + /** + * Returns a Java long if no precision is lost in the conversion. + * + * @return the value as a Java long. + * @throws LossyCoercion if it is not possible to convert the value without loosing precision. + * @throws Uncoercible if value types are incompatible. + */ + long asLong(); - /** @return the value as a {@link Path}, if possible. */ - Path asPath(); + /** + * Returns a Java int if no precision is lost in the conversion. + * + * @return the value as a Java int. + * @throws LossyCoercion if it is not possible to convert the value without loosing precision. + * @throws Uncoercible if value types are incompatible. + */ + int asInt(); /** - * Retrieve an inner value by index. This can be used for {@link #isList() lists}. + * Returns a Java short if no precision is lost in the conversion. * - * @param index the index to look up a value by - * @return the value at the specified index + * @return the value as a Java short. + * @throws LossyCoercion if it is not possible to convert the value without loosing precision. + * @throws Uncoercible if value types are incompatible. */ - Value get( long index ); + short asShort(); /** - * Retrieve an inner value by key. This can be used for {@link #isMap() maps}, - * {@link #isNode() nodes} and {@link #isRelationship() relationships}. For nodes and relationships, this method - * returns property values. If no value could be found with the specified key, then null will be returned. + * Returns a Java byte if no precision is lost in the conversion. * - * @param key the key to find a value by - * @return the value with the specified key or null if no value could be found with the key + * @return the value as a Java byte. + * @throws LossyCoercion if it is not possible to convert the value without loosing precision. + * @throws Uncoercible if value types are incompatible. */ - Value get( String key ); + byte asByte(); /** - * If the underlying value is a collection type, return the number of values in the collection. - *

    - * For {@link #isList() list} values, this will return the size of the list. - *

    - * For {@link #isMap() map} values, this will return the number of entries in the map. - *

    - * For {@link #isNode() node} and {@link #isRelationship() relationship} values, - * this will return the number of properties. - *

    - * For {@link #isPath() path} values, this returns the length (number of relationships) in the path. + * Returns a Java double if no precision is lost in the conversion. * - * @return the number of values in an underlying collection + * @return the value as a Java double. + * @throws LossyCoercion if it is not possible to convert the value without loosing precision. + * @throws Uncoercible if value types are incompatible. */ - long size(); + double asDouble(); /** - * If the underlying value supports {@link #get(String) key-based indexing}, return an iterable of the keys in the - * map, this applies to {@link #isMap() map}, {@link #asNode() node} and {@link - * #isRelationship() relationship} values. + * Returns a Java float if no precision is lost in the conversion. * - * @return the keys in the value + * @return the value as a Java float. + * @throws LossyCoercion if it is not possible to convert the value without loosing precision. + * @throws Uncoercible if value types are incompatible. */ - Iterable keys(); + float asFloat(); - boolean isNull(); + /** + * @return the value as an {@link Identity}, if possible. + * @throws Uncoercible if value types are incompatible. + */ + Identity asIdentity(); - /** @return true if the underlying value is a Neo4j string value */ - boolean isString(); + /** + * @return the value as a Java list of values, if possible + */ + List asList(); - /** @return if the underlying value is a Neo4j 64-bit integer */ - boolean isInteger(); + /** + * @param mapFunction a function to map from Value to T. See {@link Values} for some predefined functions, such + * as {@link Values#valueAsBoolean()}, {@link Values#valueAsList(Function)}. + * @param the type of target list elements + * @return the value as a list of T obtained by mapping from the list elements, if possible + */ + List asList( Function mapFunction ); - /** @return if the underlying value is a Neo4j 64-bit float */ - boolean isFloat(); + /** + * If the Value is for example a List, returns the value as an array of values instead. + * @return an array of Values. + * @throws Uncoercible if the Value cannot be turned into an array. + */ + Value[] asArray(); - /** @return if the underlying value is a Neo4j boolean */ - boolean isBoolean(); - /** @return if the underlying value is a Neo4j identity */ - boolean isIdentity(); + /** + * Map the value with provided function. See {@link Values} for some predefined functions, such + * as {@link Values#valueAsBoolean()}, {@link Values#valueAsList(Function)}. + * + * @param clazz the class of T + * @param mapFunction a function mapping Values into T + * @param The type of the array + * @return an array of T + * @throws Uncoercible if the Value cannot be turned into an array. + */ + T[] asArray( Class clazz, Function mapFunction ); - /** @return if the underlying value is a Neo4j node */ - boolean isNode(); + /** + * @return the value as an array of chars. + * @throws Uncoercible if the value cannot be coerced to a char array. + */ + char[] asCharArray(); - /** @return if the underlying value is a Neo4j path */ - boolean isPath(); + /** + * @return the value as an array of longs. + * @throws Uncoercible if the value cannot be coerced to a long array. + */ + long[] asLongArray(); - /** @return if the underlying value is a Neo4j relationship */ - boolean isRelationship(); + /** + * @return the value as an array of ints. + * @throws Uncoercible if the value cannot be coerced to a int array. + */ + int[] asIntArray(); /** - * Lists are an ordered collection of values. You can {@link #iterator() iterate} over a list as well as - * access specific values {@link #get(long) by index}. - *

    - * {@link #size()} will give you the number of entries in the list. - * - * @return if the underlying value is a Neo4j list + * @return the value as an array of shorts. + * @throws Uncoercible if the value cannot be coerced to a short array. */ - boolean isList(); + short[] asShortArray(); /** - * Maps are key/value objects, similar to {@link java.util.Map java maps}. You can use {@link #get(String)} to - * retrive values from the map, {@link #keys()} to list keys and {@link #iterator()} to iterate over the values. - *

    - * {@link #size()} will give you the number of entries in the map. - * - * @return if the underlying value is a Neo4j map + * @return the value as an array of bytes. + * @throws Uncoercible if the value cannot be coerced to a byte array. */ - boolean isMap(); + byte[] asByteArray(); - /** @return The type of this value as defined in the Cypher language */ - Type type(); + /** + * @return the value as an array of doubles. + * @throws Uncoercible if the value cannot be coerced to a double array. + */ + double[] asDoubleArray(); + + /** + * @return the value as an array of floats. + * @throws Uncoercible if the value cannot be coerced to a float array. + */ + float[] asFloatArray(); + + /** + * @return the value as a Java value map, if possible + */ + Map asMap(); + + /** + * @param mapFunction a function to map from Value to T. See {@link Values} for some predefined functions, such + * as {@link Values#valueAsBoolean()}, {@link Values#valueAsList(Function)}. + * @param the type of map values + * @return the value as a map from string keys to values of type T obtained from mapping he original map values, if possible + */ + Map asMap( Function mapFunction ); + + /** + * @return the value as a {@link Entity}, if possible. + * @throws Uncoercible if value types are incompatible. + */ + Entity asEntity(); + + /** + * @return the value as a {@link Node}, if possible. + * @throws Uncoercible if value types are incompatible. + */ + Node asNode(); + + /** + * @return the value as a {@link Relationship}, if possible. + * @throws Uncoercible if value types are incompatible. + */ + Relationship asRelationship(); + + /** + * @return the value as a {@link Path}, if possible. + * @throws Uncoercible if value types are incompatible. + */ + Path asPath(); + + // Force implementation + @Override + boolean equals( Object other ); + + // Force implementation + @Override + int hashCode(); } diff --git a/driver/src/main/java/org/neo4j/driver/v1/Values.java b/driver/src/main/java/org/neo4j/driver/v1/Values.java index 7c15b7913c..6d7df4f18c 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/Values.java +++ b/driver/src/main/java/org/neo4j/driver/v1/Values.java @@ -26,148 +26,153 @@ import java.util.List; import java.util.Map; +import org.neo4j.driver.internal.AsValue; +import org.neo4j.driver.internal.value.BooleanValue; +import org.neo4j.driver.internal.value.FloatValue; +import org.neo4j.driver.internal.value.IntegerValue; +import org.neo4j.driver.internal.value.ListValue; +import org.neo4j.driver.internal.value.MapValue; +import org.neo4j.driver.internal.value.NullValue; +import org.neo4j.driver.internal.value.StringValue; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.value.BooleanValue; -import org.neo4j.driver.v1.internal.value.FloatValue; -import org.neo4j.driver.v1.internal.value.IdentityValue; -import org.neo4j.driver.v1.internal.value.IntegerValue; -import org.neo4j.driver.v1.internal.value.ListValue; -import org.neo4j.driver.v1.internal.value.MapValue; -import org.neo4j.driver.v1.internal.value.NodeValue; -import org.neo4j.driver.v1.internal.value.NullValue; -import org.neo4j.driver.v1.internal.value.PathValue; -import org.neo4j.driver.v1.internal.value.RelationshipValue; -import org.neo4j.driver.v1.internal.value.StringValue; /** * Utility for wrapping regular Java types and exposing them as {@link Value} * objects. */ -public class Values +public abstract class Values { public static final Value EmptyMap = value( Collections.emptyMap() ); public static Value NULL = NullValue.NULL; + private Values() + { + throw new UnsupportedOperationException(); + } + @SuppressWarnings("unchecked") public static Value value( Object value ) { if ( value == null ) { return NullValue.NULL; } - if ( value instanceof Value ) { return (Value) value; } - - if ( value instanceof Identity ) { return new IdentityValue( (Identity) value ); } - if ( value instanceof Node ) { return new NodeValue( (Node) value ); } - if ( value instanceof Relationship ) { return new RelationshipValue( (Relationship) value ); } - if ( value instanceof Path ) { return new PathValue( (Path) value ); } - - if ( value instanceof Map ) { return value( (Map) value ); } - if ( value instanceof Collection ) { return value( (List) value ); } - if ( value instanceof Iterable ) { return value( (Iterable) value ); } - if ( value instanceof String ) { return value( (String) value ); } + if ( value instanceof AsValue ) { return ( (AsValue) value ).asValue(); } if ( value instanceof Boolean ) { return value( (boolean) value ); } - if ( value instanceof Byte ) { return value( (byte) value ); } + if ( value instanceof String ) { return value( (String) value ); } if ( value instanceof Character ) { return value( (char) value ); } + if ( value instanceof Long ) { return value( (long) value ); } if ( value instanceof Short ) { return value( (short) value ); } + if ( value instanceof Byte ) { return value( (byte) value ); } if ( value instanceof Integer ) { return value( (int) value ); } - if ( value instanceof Long ) { return value( (long) value ); } - if ( value instanceof Float ) { return value( (float) value ); } if ( value instanceof Double ) { return value( (double) value ); } + if ( value instanceof Float ) { return value( (float) value ); } + + if ( value instanceof Collection ) { return value( (List) value ); } + if ( value instanceof Iterable ) { return value( (Iterable) value ); } + if ( value instanceof Map ) { return value( (Map) value ); } - if ( value instanceof String[] ) { return value( (String[]) value ); } if ( value instanceof boolean[] ) { return value( (boolean[]) value ); } + if ( value instanceof String[] ) { return value( (String[]) value ); } if ( value instanceof char[] ) { return value( (char[]) value ); } - if ( value instanceof short[] ) { return value( (short[]) value ); } - if ( value instanceof int[] ) { return value( (int[]) value ); } if ( value instanceof long[] ) { return value( (long[]) value ); } - if ( value instanceof float[] ) { return value( (float[]) value ); } + if ( value instanceof int[] ) { return value( (int[]) value ); } + if ( value instanceof short[] ) { return value( (short[]) value ); } if ( value instanceof double[] ) { return value( (double[]) value ); } + if ( value instanceof float[] ) { return value( (float[]) value ); } + if ( value instanceof Value[] ) { return value( (Value[]) value ); } if ( value instanceof Object[] ) { return value( Arrays.asList( (Object[]) value )); } throw new ClientException( "Unable to convert " + value.getClass().getName() + " to Neo4j Value." ); } - public static Value value( short[] val ) + public static Value[] values( final Object... input ) { - Value[] values = new Value[val.length]; - for ( int i = 0; i < val.length; i++ ) + Value[] values = new Value[input.length]; + for ( int i = 0; i < input.length; i++ ) { - values[i] = value( val[i] ); + values[i] = value( input[i] ); } - return new ListValue( values ); + return values; } - public static Value value( int[] val ) + public static Value value( Value... input ) { - Value[] values = new Value[val.length]; - for ( int i = 0; i < val.length; i++ ) - { - values[i] = value( val[i] ); - } + int size = input.length; + Value[] values = new Value[size]; + System.arraycopy( input, 0, values, 0, size ); return new ListValue( values ); } - public static Value value( long[] val ) + public static Value value( String... input ) { - Value[] values = new Value[val.length]; - for ( int i = 0; i < val.length; i++ ) + StringValue[] values = new StringValue[input.length]; + for ( int i = 0; i < input.length; i++ ) { - values[i] = value( val[i] ); + values[i] = new StringValue( input[i] ); } return new ListValue( values ); } - public static Value value( boolean[] val ) + public static Value value( char... input ) { - Value[] values = new Value[val.length]; - for ( int i = 0; i < val.length; i++ ) + return new StringValue( String.valueOf( input ) ); + } + + public static Value value( boolean... input ) + { + Value[] values = new Value[input.length]; + for ( int i = 0; i < input.length; i++ ) { - values[i] = value( val[i] ); + values[i] = value( input[i] ); } return new ListValue( values ); } - - public static Value value( float[] val ) + public static Value value( long... input ) { - Value[] values = new Value[val.length]; - for ( int i = 0; i < val.length; i++ ) + Value[] values = new Value[input.length]; + for ( int i = 0; i < input.length; i++ ) { - values[i] = value( val[i] ); + values[i] = value( input[i] ); } return new ListValue( values ); } - public static Value value( double[] val ) + public static Value value( int... input ) { - Value[] values = new Value[val.length]; - for ( int i = 0; i < val.length; i++ ) + Value[] values = new Value[input.length]; + for ( int i = 0; i < input.length; i++ ) { - values[i] = value( val[i] ); + values[i] = value( input[i] ); } return new ListValue( values ); } - public static Value value( char[] val ) + public static Value value( short... input ) { - return new StringValue( new String( val ) ); + Value[] values = new Value[input.length]; + for ( int i = 0; i < input.length; i++ ) + { + values[i] = value( input[i] ); + } + return new ListValue( values ); } - public static Value value( String[] val ) + public static Value value( double... input ) { - StringValue[] values = new StringValue[val.length]; - for ( int i = 0; i < val.length; i++ ) + Value[] values = new Value[input.length]; + for ( int i = 0; i < input.length; i++ ) { - values[i] = new StringValue( val[i] ); + values[i] = value( input[i] ); } return new ListValue( values ); } - public static Value value( Object[] val ) + public static Value value( float... input ) { - Value[] values = new Value[val.length]; - for ( int i = 0; i < val.length; i++ ) + Value[] values = new Value[input.length]; + for ( int i = 0; i < input.length; i++ ) { - values[i] = value( val[i] ); + values[i] = value( input[i] ); } return new ListValue( values ); } @@ -192,29 +197,44 @@ public static Value value( Iterable val ) return new ListValue( values.toArray( new Value[values.size()] ) ); } + public static Value value( final String val ) + { + return new StringValue( val ); + } + + public static Value value( final char val ) + { + return new StringValue( Character.toString( val ) ); + } + public static Value value( final long val ) { return new IntegerValue( val ); } - public static Value value( final double val ) + public static Value value( final int val ) { - return new FloatValue( val ); + return new IntegerValue( val ); } - public static Value value( final boolean val ) + public static Value value( final short val ) { - return BooleanValue.fromBoolean( val ); + return new IntegerValue( val ); } - public static Value value( final char val ) + public static Value value( final byte val ) { - return new StringValue( Character.toString( val ) ); + return new IntegerValue( val ); } - public static Value value( final String val ) + public static Value value( final double val ) { - return new StringValue( val ); + return new FloatValue( val ); + } + + public static Value value( final boolean val ) + { + return BooleanValue.fromBoolean( val ); } public static Value value( final Map val ) @@ -227,16 +247,6 @@ public static Value value( final Map val ) return new MapValue( asValues ); } - public static Value[] values( final Object... vals ) - { - Value[] values = new Value[vals.length]; - for ( int i = 0; i < vals.length; i++ ) - { - values[i] = value( vals[i] ); - } - return values; - } - /** * Helper function for creating a map of parameters, this can be used when you {@link * StatementRunner#run(String, Map) run} statements. @@ -271,48 +281,104 @@ public static Function valueAsIs() return VALUE; } - public static Function valueToString() + public static Function valueAsObject() + { + return OBJECT; + } + + public static Function valueAsNumber() + { + return NUMBER; + } + + public static Function valueAsString() { return STRING; } - public static Function valueToInt() + public static Function valueAsLiteral() + { + return LITERAL_STRING; + } + + public static Function valueToString() + { + return TO_STRING; + } + + public static Function valueAsInteger() { return INTEGER; } - public static Function valueToLong() + public static Function valueAsLong() { return LONG; } - public static Function valueToFloat() + public static Function valueAsFloat() { return FLOAT; } - public static Function valueToDouble() + public static Function valueAsDouble() { return DOUBLE; } - public static Function valueToBoolean() + public static Function valueAsBoolean() { return BOOLEAN; } - public static Function> valueToList( final Function innerMap ) + public static Function> valueAsMap() + { + return MAP; + } + + public static Function valueAsEntity() + { + return ENTITY; + } + + public static Function valueAsEntityIdentity() + { + return ENTITY_IDENTITY; + } + + public static Function valueAsNode() + { + return NODE; + } + + public static Function valueAsRelationship() + { + return RELATIONSHIP; + } + + public static Function valueAsPath() + { + return PATH; + } + + public static Function> valueAsList( final Function innerMap ) { return new Function>() { @Override public List apply( Value value ) { - return value.javaList( innerMap ); + return value.asList( innerMap ); } }; } - + private static final Function OBJECT = new Function() + { + public Object apply( Value val ) + { + return val.asObject(); + } + }; private static final Function VALUE = new Function() { public Value apply( Value val ) @@ -320,49 +386,109 @@ public Value apply( Value val ) return val; } }; - + private static final Function NUMBER = new Function() + { + public Number apply( Value val ) + { + return val.asNumber(); + } + }; private static final Function STRING = new Function() { public String apply( Value val ) { - return val.javaString(); + return val.asString(); + } + }; + private static final Function LITERAL_STRING = new Function() + { + public String apply( Value val ) + { + return val.asLiteralString(); + } + }; + private static final Function TO_STRING = new Function() + { + public String apply( Value val ) + { + return val.toString(); } }; - private static final Function INTEGER = new Function() { public Integer apply( Value val ) { - return val.javaInteger(); + return val.asInt(); } }; private static final Function LONG = new Function() { public Long apply( Value val ) { - return val.javaLong(); + return val.asLong(); } }; private static final Function FLOAT = new Function() { public Float apply( Value val ) { - return val.javaFloat(); + return val.asFloat(); } }; private static final Function DOUBLE = new Function() { public Double apply( Value val ) { - return val.javaDouble(); + return val.asDouble(); } }; private static final Function BOOLEAN = new Function() { public Boolean apply( Value val ) { - return val.javaBoolean(); + return val.asBoolean(); + } + }; + private static final Function> MAP = new Function>() + { + public Map apply( Value val ) + { + return val.asMap(); + } + }; + private static final Function ENTITY_IDENTITY = new Function() + { + public Identity apply( Value val ) + { + return val.asEntity().identity(); + } + }; + private static final Function ENTITY = new Function() + { + public Entity apply( Value val ) + { + return val.asEntity(); + } + }; + private static final Function NODE = new Function() + { + public Node apply( Value val ) + { + return val.asNode(); + } + }; + private static final Function RELATIONSHIP = new Function() + { + public Relationship apply( Value val ) + { + return val.asRelationship(); + } + }; + private static final Function PATH = new Function() + { + public Path apply( Value val ) + { + return val.asPath(); } }; - } diff --git a/driver/src/main/java/org/neo4j/driver/v1/exceptions/Neo4jException.java b/driver/src/main/java/org/neo4j/driver/v1/exceptions/Neo4jException.java index 634c397699..39944769a8 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/exceptions/Neo4jException.java +++ b/driver/src/main/java/org/neo4j/driver/v1/exceptions/Neo4jException.java @@ -23,6 +23,8 @@ */ public abstract class Neo4jException extends RuntimeException { + private static final long serialVersionUID = -80579062276712566L; + private final String code; public Neo4jException( String message ) diff --git a/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/LossyCoercion.java b/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/LossyCoercion.java new file mode 100644 index 0000000000..5662c011c1 --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/LossyCoercion.java @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.v1.exceptions.value; + +import static java.lang.String.format; + +public class LossyCoercion extends ValueException +{ + private static final long serialVersionUID = -6259981390929065201L; + + public LossyCoercion( String sourceTypeName, String destinationTypeName ) + { + super( format( "Cannot coerce %s to %s without loosing precision", sourceTypeName, destinationTypeName ) ); + } + +} diff --git a/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/NotMultiValued.java b/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/NotMultiValued.java index 459754c962..1149d089ef 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/NotMultiValued.java +++ b/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/NotMultiValued.java @@ -20,6 +20,7 @@ public class NotMultiValued extends ValueException { + private static final long serialVersionUID = -7380569883011364090L; public NotMultiValued( String message ) { diff --git a/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/Uncoercible.java b/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/Uncoercible.java index 7e88dbe3ce..e803b52df8 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/Uncoercible.java +++ b/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/Uncoercible.java @@ -22,6 +22,7 @@ public class Uncoercible extends ValueException { + private static final long serialVersionUID = -6259981390929065201L; public Uncoercible( String sourceTypeName, String destinationTypeName ) { diff --git a/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/Unrepresentable.java b/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/Unrepresentable.java new file mode 100644 index 0000000000..d05c84079e --- /dev/null +++ b/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/Unrepresentable.java @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.v1.exceptions.value; + +public class Unrepresentable extends ValueException +{ + private static final long serialVersionUID = 6561876319966967485L; + + public Unrepresentable( String message ) + { + super( message ); + } +} diff --git a/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/Unsizable.java b/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/Unsizable.java index cf0354062e..cd26a5989b 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/Unsizable.java +++ b/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/Unsizable.java @@ -20,10 +20,10 @@ public class Unsizable extends ValueException { + private static final long serialVersionUID = 741487155344252339L; public Unsizable( String message ) { super( message ); } - } diff --git a/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/ValueException.java b/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/ValueException.java index ab2b0eaaf4..1ef5e79284 100644 --- a/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/ValueException.java +++ b/driver/src/main/java/org/neo4j/driver/v1/exceptions/value/ValueException.java @@ -22,10 +22,10 @@ public class ValueException extends ClientException { + private static final long serialVersionUID = -1269336313727174998L; public ValueException( String message ) { super( message ); } - } diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/SimpleRecord.java b/driver/src/main/java/org/neo4j/driver/v1/internal/SimpleRecord.java deleted file mode 100644 index fcdc272220..0000000000 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/SimpleRecord.java +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Copyright (c) 2002-2015 "Neo Technology," - * Network Engine for Objects in Lund AB [http://neotechnology.com] - * - * This file is part of Neo4j. - * - * Licensed 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.neo4j.driver.v1.internal; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import org.neo4j.driver.v1.Record; -import org.neo4j.driver.v1.Value; - -public class SimpleRecord implements Record -{ - private final Map fieldLookup; - private final Value[] fields; - - public static Record record( Object... alternatingFieldNameValue ) - { - Map lookup = new HashMap<>(); - Value[] fields = new Value[alternatingFieldNameValue.length / 2]; - for ( int i = 0; i < alternatingFieldNameValue.length; i += 2 ) - { - lookup.put( alternatingFieldNameValue[i].toString(), i / 2 ); - fields[i / 2] = (Value) alternatingFieldNameValue[i + 1]; - } - return new SimpleRecord( lookup, fields ); - } - - public SimpleRecord( Map fieldLookup, Value[] fields ) - { - this.fieldLookup = fieldLookup; - this.fields = fields; - } - - @Override - public Value get( int fieldIndex ) - { - return fields[fieldIndex]; - } - - @Override - public Value get( String fieldName ) - { - Integer fieldIndex = fieldLookup.get( fieldName ); - - if ( fieldIndex == null ) - { - return null; - } - else - { - return fields[fieldIndex]; - } - } - - @Override - public Iterable fieldNames() - { - return fieldLookup.keySet(); - } - - @Override - public boolean equals( Object o ) - { - if ( this == o ) - { - return true; - } - if ( o == null || getClass() != o.getClass() ) - { - return false; - } - - SimpleRecord that = (SimpleRecord) o; - - if ( !fieldLookup.equals( that.fieldLookup ) ) - { - return false; - } - if ( !Arrays.equals( fields, that.fields ) ) - { - return false; - } - - return true; - } - - @Override - public int hashCode() - { - int result = fieldLookup.hashCode(); - result = 31 * result + Arrays.hashCode( fields ); - return result; - } -} diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/SimpleResult.java b/driver/src/main/java/org/neo4j/driver/v1/internal/SimpleResult.java deleted file mode 100644 index 42fe9da602..0000000000 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/SimpleResult.java +++ /dev/null @@ -1,137 +0,0 @@ -/** - * Copyright (c) 2002-2015 "Neo Technology," - * Network Engine for Objects in Lund AB [http://neotechnology.com] - * - * This file is part of Neo4j. - * - * Licensed 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.neo4j.driver.v1.internal; - -import java.util.Iterator; -import java.util.List; - -import org.neo4j.driver.v1.Record; -import org.neo4j.driver.v1.Result; -import org.neo4j.driver.v1.ResultSummary; -import org.neo4j.driver.v1.ReusableResult; -import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.exceptions.ClientException; - -public class SimpleResult implements Result -{ - private final Iterable fieldNames; - private final List body; - private final Iterator iter; - private final ResultSummary summary; - - private Record current = null; - - public SimpleResult( Iterable fieldNames, List body, ResultSummary summary ) - { - this.fieldNames = fieldNames; - this.body = body; - this.iter = body.iterator(); - this.summary = summary; - } - - @Override - public ReusableResult retain() - { - return new StandardReusableResult( body ); - } - - @Override - public Record single() - { - return iter.next(); - } - - @SuppressWarnings("StatementWithEmptyBody") - @Override - public ResultSummary summarize() - { - while (next()) ; - return summary; - } - - @Override - public boolean next() - { - if ( iter.hasNext() ) - { - current = iter.next(); - return true; - } - else - { - return false; - } - } - - @Override - public Value get( int fieldIndex ) - { - return current.get( fieldIndex ); - } - - @Override - public Value get( String fieldName ) - { - if( current == null ) - { - throw new ClientException( - "In order to access fields of a record in a result, " + - "you must first call next() to point the result to the next record in the result stream." ); - } - return current.get( fieldName ); - } - - @Override - public Iterable fieldNames() - { - return fieldNames; - } - - private static class StandardReusableResult implements ReusableResult - { - private final List body; - - private StandardReusableResult( List body ) - { - this.body = body; - } - - @Override - public long size() - { - return body.size(); - } - - @Override - public Record get( long index ) - { - if ( index < 0 || index >= body.size() ) - { - throw new ClientException( "Value " + index + " does not exist" ); - } - return body.get( (int) index ); - } - - @Override - public Iterator iterator() - { - return body.iterator(); - } - } -} diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/types/StandardTypeSystem.java b/driver/src/main/java/org/neo4j/driver/v1/internal/types/StandardTypeSystem.java deleted file mode 100644 index 427ba52395..0000000000 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/types/StandardTypeSystem.java +++ /dev/null @@ -1,148 +0,0 @@ -/** - * Copyright (c) 2002-2015 "Neo Technology," - * Network Engine for Objects in Lund AB [http://neotechnology.com] - * - * This file is part of Neo4j. - * - * Licensed 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.neo4j.driver.v1.internal.types; - -import org.neo4j.driver.v1.Type; -import org.neo4j.driver.v1.TypeSystem; -import org.neo4j.driver.v1.Value; - -import static org.neo4j.driver.v1.internal.types.TypeConstructor.ANY_TyCon; -import static org.neo4j.driver.v1.internal.types.TypeConstructor.BOOLEAN_TyCon; -import static org.neo4j.driver.v1.internal.types.TypeConstructor.FLOAT_TyCon; -import static org.neo4j.driver.v1.internal.types.TypeConstructor.IDENTITY_TyCon; -import static org.neo4j.driver.v1.internal.types.TypeConstructor.INTEGER_TyCon; -import static org.neo4j.driver.v1.internal.types.TypeConstructor.LIST_TyCon; -import static org.neo4j.driver.v1.internal.types.TypeConstructor.MAP_TyCon; -import static org.neo4j.driver.v1.internal.types.TypeConstructor.NODE_TyCon; -import static org.neo4j.driver.v1.internal.types.TypeConstructor.NULL_TyCon; -import static org.neo4j.driver.v1.internal.types.TypeConstructor.NUMBER_TyCon; -import static org.neo4j.driver.v1.internal.types.TypeConstructor.PATH_TyCon; -import static org.neo4j.driver.v1.internal.types.TypeConstructor.RELATIONSHIP_TyCon; -import static org.neo4j.driver.v1.internal.types.TypeConstructor.STRING_TyCon; - -/** - * Utility class for determining and working with the Cypher types of values - * - * @see Value - * @see Type - */ -public final class StandardTypeSystem implements TypeSystem -{ - public static StandardTypeSystem TYPE_SYSTEM = new StandardTypeSystem(); - - private StandardTypeSystem() - { - } - - /** the Cypher type ANY */ - @Override - public Type ANY() - { - return constructType( ANY_TyCon ); - } - - /** the Cypher type BOOLEAN */ - @Override - public Type BOOLEAN() - { - return constructType( BOOLEAN_TyCon ); - } - - /** the Cypher type STRING */ - @Override - public Type STRING() - { - return constructType( STRING_TyCon ); - } - - /** the Cypher type NUMBER */ - @Override - public Type NUMBER() - { - return constructType( NUMBER_TyCon ); - } - - /** the Cypher type INTEGER */ - @Override - public Type INTEGER() - { - return constructType( INTEGER_TyCon ); - } - - /** the Cypher type FLOAT */ - @Override - public Type FLOAT() - { - return constructType( FLOAT_TyCon ); - } - - /** the Cypher type LIST */ - @Override - public Type LIST() - { - return constructType( LIST_TyCon ); - } - - /** the Cypher type MAP */ - @Override - public Type MAP() - { - return constructType( MAP_TyCon ); - } - - /** the Cypher type IDENTITY */ - @Override - public Type IDENTITY() - { - return constructType( IDENTITY_TyCon ); - } - - /** the Cypher type NODE */ - @Override - public Type NODE() - { - return constructType( NODE_TyCon ); - } - - /** the Cypher type RELATIONSHIP */ - @Override - public Type RELATIONSHIP() - { - return constructType( RELATIONSHIP_TyCon ); - } - - /** the Cypher type PATH */ - @Override - public Type PATH() - { - return constructType( PATH_TyCon ); - } - - /** the Cypher type NULL */ - @Override - public Type NULL() - { - return constructType( NULL_TyCon ); - } - - private TypeRepresentation constructType( TypeConstructor tyCon ) - { - return new TypeRepresentation( tyCon ); - } -} diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/value/ListValue.java b/driver/src/main/java/org/neo4j/driver/v1/internal/value/ListValue.java deleted file mode 100644 index 7044332a1f..0000000000 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/value/ListValue.java +++ /dev/null @@ -1,143 +0,0 @@ -/** - * Copyright (c) 2002-2015 "Neo Technology," - * Network Engine for Objects in Lund AB [http://neotechnology.com] - * - * This file is part of Neo4j. - * - * Licensed 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.neo4j.driver.v1.internal.value; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import org.neo4j.driver.v1.Function; -import org.neo4j.driver.v1.Type; -import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.types.StandardTypeSystem; -import org.neo4j.driver.v1.internal.types.TypeConstructor; - -public class ListValue extends ValueAdapter -{ - private final Value[] values; - - public ListValue( Value... values ) - { - this.values = values; - } - - @Override - public boolean javaBoolean() - { - return values.length > 0; - } - - @Override - public List javaList( Function mapFunction ) - { - List list = new ArrayList<>( values.length ); - for ( Value value : values ) - { - list.add( mapFunction.apply( value ) ); - } - return list; - } - - @Override - public boolean isList() - { - return true; - } - - @Override - public long size() - { - return values.length; - } - - @Override - public TypeConstructor typeConstructor() - { - return TypeConstructor.LIST_TyCon; - } - - @Override - public Value get( long index ) - { - return values[(int) index]; - } - - @Override - public Iterator iterator() - { - return new Iterator() - { - private int cursor = 0; - - @Override - public boolean hasNext() - { - return cursor < values.length; - } - - @Override - public Value next() - { - return values[cursor++]; - } - - @Override - public void remove() - { - } - }; - } - - @Override - public Type type() - { - return StandardTypeSystem.TYPE_SYSTEM.LIST(); - } - - @Override - public String toString() - { - return "ListValue" + Arrays.toString( values ) + ""; - } - - @Override - public boolean equals( Object o ) - { - if ( this == o ) - { - return true; - } - if ( o == null || getClass() != o.getClass() ) - { - return false; - } - - ListValue values1 = (ListValue) o; - - return Arrays.equals( values, values1.values ); - - } - - @Override - public int hashCode() - { - return Arrays.hashCode( values ); - } -} diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/value/MapValue.java b/driver/src/main/java/org/neo4j/driver/v1/internal/value/MapValue.java deleted file mode 100644 index cc2dab1da9..0000000000 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/value/MapValue.java +++ /dev/null @@ -1,161 +0,0 @@ -/** - * Copyright (c) 2002-2015 "Neo Technology," - * Network Engine for Objects in Lund AB [http://neotechnology.com] - * - * This file is part of Neo4j. - * - * Licensed 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.neo4j.driver.v1.internal.value; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.neo4j.driver.v1.Function; -import org.neo4j.driver.v1.Type; -import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.types.StandardTypeSystem; -import org.neo4j.driver.v1.internal.types.TypeConstructor; - -public class MapValue extends ValueAdapter -{ - private final Map val; - - public MapValue( Map val ) - { - this.val = val; - } - - @Override - public boolean javaBoolean() - { - return !val.isEmpty(); - } - - @Override - public List javaList( Function mapFunction ) - { - List list = new ArrayList<>( val.size() ); - for ( Value value : val.values() ) - { - list.add( mapFunction.apply( value ) ); - } - return list; - } - - @Override - public Map javaMap( Function mapFunction ) - { - Map map = new HashMap<>( val.size() ); - for ( Map.Entry entry : val.entrySet() ) - { - map.put( entry.getKey(), mapFunction.apply( entry.getValue() ) ); - } - return map; - } - - @Override - public long size() - { - return val.size(); - } - - @Override - public Iterable keys() - { - return val.keySet(); - } - - @Override - public TypeConstructor typeConstructor() - { - return TypeConstructor.MAP_TyCon; - } - - @Override - public boolean isMap() - { - return true; - } - - @Override - public Iterator iterator() - { - final Iterator raw = val.values().iterator(); - return new Iterator() - { - @Override - public boolean hasNext() - { - return raw.hasNext(); - } - - @Override - public Value next() - { - return raw.next(); - } - - @Override - public void remove() - { - } - }; - } - - @Override - public Value get( String key ) - { - return val.get( key ); - } - - - @Override - public Type type() - { - return StandardTypeSystem.TYPE_SYSTEM.MAP(); - } - - @Override - public String toString() - { - return String.format( "map<%s>", val.toString() ); - } - - @Override - public boolean equals( Object o ) - { - if ( this == o ) - { - return true; - } - if ( o == null || getClass() != o.getClass() ) - { - return false; - } - - MapValue values = (MapValue) o; - - return !(val != null ? !val.equals( values.val ) : values.val != null); - - } - - @Override - public int hashCode() - { - return val != null ? val.hashCode() : 0; - } -} diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/value/NodeValue.java b/driver/src/main/java/org/neo4j/driver/v1/internal/value/NodeValue.java deleted file mode 100644 index 4bc0a3ba2d..0000000000 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/value/NodeValue.java +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Copyright (c) 2002-2015 "Neo Technology," - * Network Engine for Objects in Lund AB [http://neotechnology.com] - * - * This file is part of Neo4j. - * - * Licensed 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.neo4j.driver.v1.internal.value; - -import org.neo4j.driver.v1.Node; -import org.neo4j.driver.v1.Type; -import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.types.StandardTypeSystem; -import org.neo4j.driver.v1.internal.types.TypeConstructor; - -public class NodeValue extends ValueAdapter -{ - private final Node adapted; - - public NodeValue( Node adapted ) - { - this.adapted = adapted; - } - - @Override - public Node asNode() - { - return adapted; - } - - @Override - public boolean isNode() - { - return true; - } - - @Override - public long size() - { - int count = 0; - for ( String ignore : adapted.propertyKeys() ) { count++; } - return count; - } - - @Override - public Iterable keys() - { - return adapted.propertyKeys(); - } - - @Override - public TypeConstructor typeConstructor() - { - return TypeConstructor.NODE_TyCon; - } - - @Override - public Value get( String key ) - { - return adapted.property( key ); - } - - @Override - public boolean equals( Object o ) - { - if ( this == o ) - { - return true; - } - if ( o == null || getClass() != o.getClass() ) - { - return false; - } - - NodeValue values = (NodeValue) o; - - return !(adapted != null ? !adapted.equals( values.adapted ) : values.adapted != null); - - } - - @Override - public Type type() - { - return StandardTypeSystem.TYPE_SYSTEM.NODE(); - } - - @Override - public int hashCode() - { - return adapted != null ? adapted.hashCode() : 0; - } - - @Override - public String toString() - { - return adapted.toString(); - } -} diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/value/RelationshipValue.java b/driver/src/main/java/org/neo4j/driver/v1/internal/value/RelationshipValue.java deleted file mode 100644 index 4d3e20d2f1..0000000000 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/value/RelationshipValue.java +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Copyright (c) 2002-2015 "Neo Technology," - * Network Engine for Objects in Lund AB [http://neotechnology.com] - * - * This file is part of Neo4j. - * - * Licensed 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.neo4j.driver.v1.internal.value; - -import org.neo4j.driver.v1.Relationship; -import org.neo4j.driver.v1.Type; -import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.types.StandardTypeSystem; -import org.neo4j.driver.v1.internal.types.TypeConstructor; - -public class RelationshipValue extends ValueAdapter -{ - private final Relationship adapted; - - public RelationshipValue( Relationship adapted ) - { - this.adapted = adapted; - } - - @Override - public Relationship asRelationship() - { - return adapted; - } - - @Override - public boolean isRelationship() - { - return true; - } - - @Override - public long size() - { - int count = 0; - for ( String ignore : adapted.propertyKeys() ) { count++; } - return count; - } - - @Override - public Iterable keys() - { - return adapted.propertyKeys(); - } - - @Override - public TypeConstructor typeConstructor() - { - return TypeConstructor.RELATIONSHIP_TyCon; - } - - @Override - public Value get( String key ) - { - return adapted.property( key ); - } - - @Override - public Type type() - { - return StandardTypeSystem.TYPE_SYSTEM.RELATIONSHIP(); - } - - @Override - public boolean equals( Object o ) - { - if ( this == o ) - { - return true; - } - if ( o == null || getClass() != o.getClass() ) - { - return false; - } - - RelationshipValue values = (RelationshipValue) o; - - return !(adapted != null ? !adapted.equals( values.adapted ) : values.adapted != null); - - } - - @Override - public int hashCode() - { - return adapted != null ? adapted.hashCode() : 0; - } - - @Override - public String toString() - { - return adapted.toString(); - } -} diff --git a/driver/src/main/java/org/neo4j/driver/v1/internal/value/ValueAdapter.java b/driver/src/main/java/org/neo4j/driver/v1/internal/value/ValueAdapter.java deleted file mode 100644 index b8427823dd..0000000000 --- a/driver/src/main/java/org/neo4j/driver/v1/internal/value/ValueAdapter.java +++ /dev/null @@ -1,228 +0,0 @@ -/** - * Copyright (c) 2002-2015 "Neo Technology," - * Network Engine for Objects in Lund AB [http://neotechnology.com] - * - * This file is part of Neo4j. - * - * Licensed 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.neo4j.driver.v1.internal.value; - -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.neo4j.driver.v1.Function; -import org.neo4j.driver.v1.Identity; -import org.neo4j.driver.v1.Node; -import org.neo4j.driver.v1.Path; -import org.neo4j.driver.v1.Relationship; -import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.exceptions.value.NotMultiValued; -import org.neo4j.driver.v1.exceptions.value.Uncoercible; -import org.neo4j.driver.v1.exceptions.value.Unsizable; - -import static java.util.Collections.emptyList; - -public abstract class ValueAdapter implements InternalValue -{ - @Override - public boolean isNull() - { - return false; - } - - @Override - public String javaString() - { - throw new Uncoercible( typeName(), "Java String" ); - } - - @Override - public int javaInteger() - { - throw new Uncoercible( typeName(), "Java int" ); - } - - @Override - public long javaLong() - { - throw new Uncoercible( typeName(), "Java long" ); - } - - @Override - public float javaFloat() - { - throw new Uncoercible( typeName(), "Java float" ); - } - - @Override - public double javaDouble() - { - throw new Uncoercible( typeName(), "Java double" ); - } - - @Override - public boolean javaBoolean() - { - throw new Uncoercible( typeName(), "Java boolean" ); - } - - @Override - public List javaList( Function mapFunction ) - { - throw new Uncoercible( typeName(), "Java List" ); - } - - @Override - public Map javaMap( Function mapFunction ) - { - throw new Uncoercible( typeName(), "Java Map" ); - } - - @Override - public Identity asIdentity() - { - throw new Uncoercible( typeName(), "Identity" ); - } - - @Override - public Node asNode() - { - throw new Uncoercible( typeName(), "Node" ); - } - - @Override - public Path asPath() - { - throw new Uncoercible( typeName(), "Path" ); - } - - @Override - public Relationship asRelationship() - { - throw new Uncoercible( typeName(), "Relationship" ); - } - - @Override - public Value get( long index ) - { - throw new NotMultiValued( typeName() + " is not an indexed collection" ); - } - - @Override - public Value get( String key ) - { - throw new NotMultiValued( typeName() + " is not a keyed collection" ); - } - - @Override - public long size() - { - throw new Unsizable( typeName() + " does not have size" ); - } - - @Override - public Iterable keys() - { - return emptyList(); - } - - @Override - public boolean isString() - { - return false; - } - - @Override - public boolean isInteger() - { - return false; - } - - @Override - public boolean isFloat() - { - return false; - } - - @Override - public boolean isBoolean() - { - return false; - } - - @Override - public boolean isIdentity() - { - return false; - } - - @Override - public boolean isNode() - { - return false; - } - - @Override - public boolean isPath() - { - return false; - } - - @Override - public boolean isRelationship() - { - return false; - } - - @Override - public boolean isList() - { - return false; - } - - @Override - public boolean isMap() - { - return false; - } - - @Override - public Iterator iterator() - { - throw new NotMultiValued( typeName() + " is not iterable" ); - } - - @Override - public String toString() - { - return String.format( "%s<>", typeName() ); - } - - protected String typeName() - { - if ( isNull() ) { return "null"; } - if ( isFloat() ) { return "float"; } - if ( isInteger() ) { return "integer"; } - if ( isBoolean() ) { return "boolean"; } - if ( isString() ) { return "string"; } - if ( isList() ) { return "list"; } - if ( isMap() ) { return "map"; } - if ( isIdentity() ) { return "identity"; } - if ( isNode() ) { return "node"; } - if ( isRelationship() ) { return "relationship"; } - if ( isPath() ) { return "path"; } - return "unknown"; - } -} diff --git a/driver/src/main/resources/META-INF/services/org.neo4j.driver.internal.spi.Connector b/driver/src/main/resources/META-INF/services/org.neo4j.driver.internal.spi.Connector new file mode 100644 index 0000000000..a16cb5e170 --- /dev/null +++ b/driver/src/main/resources/META-INF/services/org.neo4j.driver.internal.spi.Connector @@ -0,0 +1 @@ +org.neo4j.driver.internal.connector.socket.SocketConnector diff --git a/driver/src/main/resources/META-INF/services/org.neo4j.driver.v1.internal.spi.Connector b/driver/src/main/resources/META-INF/services/org.neo4j.driver.v1.internal.spi.Connector deleted file mode 100644 index 69775e0455..0000000000 --- a/driver/src/main/resources/META-INF/services/org.neo4j.driver.v1.internal.spi.Connector +++ /dev/null @@ -1 +0,0 @@ -org.neo4j.driver.v1.internal.connector.socket.SocketConnector \ No newline at end of file diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/ConfigTest.java b/driver/src/test/java/org/neo4j/driver/internal/ConfigTest.java similarity index 98% rename from driver/src/test/java/org/neo4j/driver/v1/internal/ConfigTest.java rename to driver/src/test/java/org/neo4j/driver/internal/ConfigTest.java index f66d16ed15..87b14245e1 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/ConfigTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/ConfigTest.java @@ -16,12 +16,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; - -import org.junit.Test; +package org.neo4j.driver.internal; import java.io.File; +import org.junit.Test; + import org.neo4j.driver.v1.Config; import static org.junit.Assert.assertEquals; diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/SummaryBuilderTest.java b/driver/src/test/java/org/neo4j/driver/internal/InternalBuilderTest.java similarity index 88% rename from driver/src/test/java/org/neo4j/driver/v1/internal/SummaryBuilderTest.java rename to driver/src/test/java/org/neo4j/driver/internal/InternalBuilderTest.java index 452961a6bb..aa504c03fd 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/SummaryBuilderTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/InternalBuilderTest.java @@ -16,15 +16,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; +package org.neo4j.driver.internal; import org.junit.Test; +import org.neo4j.driver.internal.summary.InternalUpdateStatistics; +import org.neo4j.driver.internal.summary.SummaryBuilder; import org.neo4j.driver.v1.ResultSummary; import org.neo4j.driver.v1.Statement; import org.neo4j.driver.v1.UpdateStatistics; -import org.neo4j.driver.v1.internal.summary.SimpleUpdateStatistics; -import org.neo4j.driver.v1.internal.summary.SummaryBuilder; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; @@ -32,7 +32,7 @@ import static org.junit.Assert.assertNull; import static org.mockito.Mockito.mock; -public class SummaryBuilderTest +public class InternalBuilderTest { @Test public void shouldReturnEmptyStatisticsIfNotProvided() throws Throwable @@ -45,7 +45,7 @@ public void shouldReturnEmptyStatisticsIfNotProvided() throws Throwable UpdateStatistics stats = summary.updateStatistics(); // Then - assertEquals( stats, new SimpleUpdateStatistics( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ) ); + assertEquals( stats, new InternalUpdateStatistics( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ) ); } diff --git a/driver/src/test/java/org/neo4j/driver/internal/InternalFieldTest.java b/driver/src/test/java/org/neo4j/driver/internal/InternalFieldTest.java new file mode 100644 index 0000000000..e23bd754b8 --- /dev/null +++ b/driver/src/test/java/org/neo4j/driver/internal/InternalFieldTest.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal; + +import org.junit.Test; + +import org.neo4j.driver.v1.Field; +import org.neo4j.driver.v1.Value; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +import static org.neo4j.driver.v1.Values.value; + + +public class InternalFieldTest +{ + @Test + public void testMethods() + { + Field field = InternalField.of( "k", 42, value( "v" ) ); + assertThat(field.key(), equalTo("k")); + assertThat(field.index(), equalTo(42)); + assertThat(field.value(), equalTo(value("v"))); + } + +} diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/SimpleIdentityTest.java b/driver/src/test/java/org/neo4j/driver/internal/InternalIdentityTest.java similarity index 83% rename from driver/src/test/java/org/neo4j/driver/v1/internal/SimpleIdentityTest.java rename to driver/src/test/java/org/neo4j/driver/internal/InternalIdentityTest.java index 022d19027e..2e1573819e 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/SimpleIdentityTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/InternalIdentityTest.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; +package org.neo4j.driver.internal; import org.junit.Test; @@ -26,15 +26,15 @@ import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; -public class SimpleIdentityTest +public class InternalIdentityTest { @Test public void shouldBeAbleToCompareIdentities() throws Throwable { // Given - Identity firstIdentity = new SimpleIdentity( 1 ); - Identity secondIdentity = new SimpleIdentity( 1 ); + Identity firstIdentity = new InternalIdentity( 1 ); + Identity secondIdentity = new InternalIdentity( 1 ); // Then assertThat( firstIdentity, equalTo( secondIdentity ) ); @@ -45,7 +45,7 @@ public void shouldBeAbleToCompareIdentities() throws Throwable public void hashCodeShouldNotBeNull() throws Throwable { // Given - Identity identity = new SimpleIdentity( 1 ); + Identity identity = new InternalIdentity( 1 ); // Then assertThat( identity.hashCode(), notNullValue() ); @@ -56,7 +56,7 @@ public void hashCodeShouldNotBeNull() throws Throwable public void shouldBeAbleToCastIdentityToString() throws Throwable { // Given - Identity identity = new SimpleIdentity( 1 ); + Identity identity = new InternalIdentity( 1 ); // Then assertThat( identity.toString(), equalTo( "#1" ) ); diff --git a/driver/src/test/java/org/neo4j/driver/internal/InternalNodeTest.java b/driver/src/test/java/org/neo4j/driver/internal/InternalNodeTest.java new file mode 100644 index 0000000000..093b252382 --- /dev/null +++ b/driver/src/test/java/org/neo4j/driver/internal/InternalNodeTest.java @@ -0,0 +1,82 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.junit.Test; + +import org.neo4j.driver.v1.Function; +import org.neo4j.driver.v1.Value; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; + +import static org.neo4j.driver.v1.Values.NULL; +import static org.neo4j.driver.v1.Values.value; + +public class InternalNodeTest +{ + @Test + public void extractValuesFromNode() + { + // GIVEN + InternalNode node = createNode(); + Function extractor = new Function() + { + @Override + public Integer apply( Value value ) + { + return value.asInt(); + } + }; + + //WHEN + Iterable values = node.values( extractor ); + + //THEN + Iterator iterator = values.iterator(); + assertThat( iterator.next(), equalTo( 1 ) ); + assertThat( iterator.next(), equalTo( 2 ) ); + assertFalse( iterator.hasNext() ); + } + + @Test + public void accessUnknownKeyShouldBeNull() + { + InternalNode node = createNode(); + + assertThat( node.value( "k1" ), equalTo( value( 1 ) ) ); + assertThat( node.value( "k2" ), equalTo( value( 2 ) ) ); + assertThat( node.value( "k3" ), equalTo( NULL ) ); + } + + private InternalNode createNode() + { + Map props = new HashMap<>(); + props.put( "k1", value( 1 ) ); + props.put( "k2", value( 2 ) ); + return new InternalNode( 42L, Collections.singletonList( "L" ), props ); + } + +} diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/SimplePathTest.java b/driver/src/test/java/org/neo4j/driver/internal/InternalPathTest.java similarity index 57% rename from driver/src/test/java/org/neo4j/driver/v1/internal/SimplePathTest.java rename to driver/src/test/java/org/neo4j/driver/internal/InternalPathTest.java index 41f3ca876d..c23e48c20e 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/SimplePathTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/InternalPathTest.java @@ -16,16 +16,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; +package org.neo4j.driver.internal; + +import java.util.Arrays; +import java.util.List; import org.hamcrest.MatcherAssert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.util.Arrays; -import java.util.List; - import org.neo4j.driver.v1.Node; import org.neo4j.driver.v1.Path; import org.neo4j.driver.v1.Relationship; @@ -34,22 +34,22 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; -public class SimplePathTest +public class InternalPathTest { @Rule public ExpectedException thrown = ExpectedException.none(); // (A)-[AB:KNOWS]->(B)<-[CB:KNOWS]-(C)-[CD:KNOWS]->(D) - private SimplePath testPath() + private InternalPath testPath() { - return new SimplePath( - new SimpleNode( 1 ), - new SimpleRelationship( -1, 1, 2, "KNOWS" ), - new SimpleNode( 2 ), - new SimpleRelationship( -2, 3, 2, "KNOWS" ), - new SimpleNode( 3 ), - new SimpleRelationship( -3, 3, 4, "KNOWS" ), - new SimpleNode( 4 ) + return new InternalPath( + new InternalNode( 1 ), + new InternalRelationship( -1, 1, 2, "KNOWS" ), + new InternalNode( 2 ), + new InternalRelationship( -2, 3, 2, "KNOWS" ), + new InternalNode( 3 ), + new InternalRelationship( -3, 3, 4, "KNOWS" ), + new InternalNode( 4 ) ); } @@ -57,47 +57,47 @@ private SimplePath testPath() public void pathSizeShouldReturnNumberOfRelationships() { // When - SimplePath path = testPath(); + InternalPath path = testPath(); // Then - assertThat( path.length(), equalTo( 3L ) ); + assertThat( path.length(), equalTo( 3 ) ); } @Test public void shouldBeAbleToCreatePathWithSingleNode() { // When - SimplePath path = new SimplePath( new SimpleNode( 1 ) ); + InternalPath path = new InternalPath( new InternalNode( 1 ) ); // Then - assertThat( path.length(), equalTo( 0L ) ); + assertThat( path.length(), equalTo( 0 ) ); } @Test public void shouldBeAbleToIterateOverPathAsSegments() throws Exception { // Given - SimplePath path = testPath(); + InternalPath path = testPath(); // When List segments = Lists.asList( path ); // Then MatcherAssert.assertThat( segments, equalTo( Arrays.asList( (Path.Segment) - new SimplePath.SelfContainedSegment( - new SimpleNode( 1 ), - new SimpleRelationship( -1, 1, 2, "KNOWS" ), - new SimpleNode( 2 ) + new InternalPath.SelfContainedSegment( + new InternalNode( 1 ), + new InternalRelationship( -1, 1, 2, "KNOWS" ), + new InternalNode( 2 ) ), - new SimplePath.SelfContainedSegment( - new SimpleNode( 2 ), - new SimpleRelationship( -2, 3, 2, "KNOWS" ), - new SimpleNode( 3 ) + new InternalPath.SelfContainedSegment( + new InternalNode( 2 ), + new InternalRelationship( -2, 3, 2, "KNOWS" ), + new InternalNode( 3 ) ), - new SimplePath.SelfContainedSegment( - new SimpleNode( 3 ), - new SimpleRelationship( -3, 3, 4, "KNOWS" ), - new SimpleNode( 4 ) + new InternalPath.SelfContainedSegment( + new InternalNode( 3 ), + new InternalRelationship( -3, 3, 4, "KNOWS" ), + new InternalNode( 4 ) ) ) ) ); @@ -107,33 +107,33 @@ public void shouldBeAbleToIterateOverPathAsSegments() throws Exception public void shouldBeAbleToIterateOverPathNodes() throws Exception { // Given - SimplePath path = testPath(); + InternalPath path = testPath(); // When List segments = Lists.asList( path.nodes() ); // Then assertThat( segments, equalTo( Arrays.asList( (Node) - new SimpleNode( 1 ), - new SimpleNode( 2 ), - new SimpleNode( 3 ), - new SimpleNode( 4 ) ) ) ); + new InternalNode( 1 ), + new InternalNode( 2 ), + new InternalNode( 3 ), + new InternalNode( 4 ) ) ) ); } @Test public void shouldBeAbleToIterateOverPathRelationships() throws Exception { // Given - SimplePath path = testPath(); + InternalPath path = testPath(); // When List segments = Lists.asList( path.relationships() ); // Then assertThat( segments, equalTo( Arrays.asList( (Relationship) - new SimpleRelationship( -1, 1, 2, "KNOWS" ), - new SimpleRelationship( -2, 3, 2, "KNOWS" ), - new SimpleRelationship( -3, 3, 4, "KNOWS" ) ) ) ); + new InternalRelationship( -1, 1, 2, "KNOWS" ), + new InternalRelationship( -2, 3, 2, "KNOWS" ), + new InternalRelationship( -3, 3, 4, "KNOWS" ) ) ) ); } @Test @@ -143,7 +143,7 @@ public void shouldNotBeAbleToCreatePathWithNoEntities() thrown.expect( IllegalArgumentException.class ); // When - new SimplePath(); + new InternalPath(); } @@ -154,9 +154,9 @@ public void shouldNotBeAbleToCreatePathWithEvenNumberOfEntities() thrown.expect( IllegalArgumentException.class ); // When - new SimplePath( - new SimpleNode( 1 ), - new SimpleRelationship( 2, 3, 4, "KNOWS" ) ); + new InternalPath( + new InternalNode( 1 ), + new InternalRelationship( 2, 3, 4, "KNOWS" ) ); } @@ -167,9 +167,9 @@ public void shouldNotBeAbleToCreatePathWithNullEntities() thrown.expect( IllegalArgumentException.class ); // When - SimpleNode nullNode = null; + InternalNode nullNode = null; //noinspection ConstantConditions - new SimplePath( nullNode ); + new InternalPath( nullNode ); } @@ -180,10 +180,10 @@ public void shouldNotBeAbleToCreatePathWithNodeThatDoesNotConnect() thrown.expect( IllegalArgumentException.class ); // When - new SimplePath( - new SimpleNode( 1 ), - new SimpleRelationship( 2, 1, 3, "KNOWS" ), - new SimpleNode( 4 ) ); + new InternalPath( + new InternalNode( 1 ), + new InternalRelationship( 2, 1, 3, "KNOWS" ), + new InternalNode( 4 ) ); } @@ -194,10 +194,10 @@ public void shouldNotBeAbleToCreatePathWithRelationshipThatDoesNotConnect() thrown.expect( IllegalArgumentException.class ); // When - new SimplePath( - new SimpleNode( 1 ), - new SimpleRelationship( 2, 3, 4, "KNOWS" ), - new SimpleNode( 3 ) ); + new InternalPath( + new InternalNode( 1 ), + new InternalRelationship( 2, 3, 4, "KNOWS" ), + new InternalNode( 3 ) ); } diff --git a/driver/src/test/java/org/neo4j/driver/internal/InternalRecordTest.java b/driver/src/test/java/org/neo4j/driver/internal/InternalRecordTest.java new file mode 100644 index 0000000000..f1a8adb2d6 --- /dev/null +++ b/driver/src/test/java/org/neo4j/driver/internal/InternalRecordTest.java @@ -0,0 +1,179 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +import org.junit.Test; + +import org.neo4j.driver.internal.value.NullValue; +import org.neo4j.driver.v1.Function; +import org.neo4j.driver.v1.Value; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import static org.neo4j.driver.v1.Values.value; + +public class InternalRecordTest +{ + @Test + public void accessingUnknownKeyShouldBeNull() + { + InternalRecord record = createRecord(); + + assertThat( record.value( "k1" ), equalTo( value( 0 ) ) ); + assertThat( record.value( "k2" ), equalTo( value( 1 ) ) ); + assertThat( record.value( "k3" ), equalTo( NullValue.NULL ) ); + } + + @Test + public void shouldHaveCorrectFieldCount() + { + InternalRecord record = createRecord(); + assertThat( record.fieldCount(), equalTo( 2 ) ); + } + + @Test + public void shouldHaveCorrectFieldIndices() + { + InternalRecord record = createRecord(); + assertThat( record.index( "k1" ), equalTo( 0 ) ); + assertThat( record.index( "k2" ), equalTo( 1 ) ); + } + + @Test + public void shouldThrowWhenAskingForIndexOfUnknownField() + { + InternalRecord record = createRecord(); + try + { + record.index( "BATMAN" ); + fail( "Expected NoSuchElementException to be thrown" ); + } + catch ( NoSuchElementException e ) + { + // yay + } + } + + @Test + public void accessingOutOfBoundsShouldBeNull() + { + InternalRecord record = createRecord(); + + assertThat( record.value( 0 ), equalTo( value( 0 ) ) ); + assertThat( record.value( 1 ), equalTo( value( 1 ) ) ); + assertThat( record.value( 2 ), equalTo( NullValue.NULL ) ); + assertThat( record.value( -37 ), equalTo( NullValue.NULL ) ); + } + + @Test + public void testContainsKey() + { + InternalRecord record = createRecord(); + + assertTrue( record.containsKey( "k1" ) ); + assertTrue( record.containsKey( "k2" ) ); + assertFalse( record.containsKey( "k3" ) ); + } + + @Test + public void testIndex() + { + InternalRecord record = createRecord(); + + assertThat( record.index( "k1" ), equalTo( 0 ) ); + assertThat( record.index( "k2" ), equalTo( 1 ) ); + } + + @Test + public void testField() + { + InternalRecord record = createRecord(); + + assertThat( record.field( "k1" ), equalTo( record.field( 0 ) ) ); + assertThat( record.field( "k2" ), equalTo( record.field( 1 ) ) ); + } + + @Test + public void testAsMap() + { + // GIVEN + InternalRecord record = createRecord(); + + // WHEN + Map map = record.asMap(); + + // THEN + assertThat( map.keySet(), containsInAnyOrder( "k1", "k2" ) ); + assertThat( map.get( "k1" ), equalTo( value( 0 ) ) ); + assertThat( map.get( "k2" ), equalTo( value( 1 ) ) ); + } + + @Test + public void testMapExtraction() + { + // GIVEN + InternalRecord record = createRecord(); + Function addOne = new Function() + { + @Override + public Integer apply( Value value ) + { + return value.asInt() + 1; + } + }; + + // WHEN + Map map = record.asMap( addOne ); + + // THEN + assertThat( map.keySet(), containsInAnyOrder( "k1", "k2" ) ); + assertThat( map.get( "k1" ), equalTo( 1 ) ); + assertThat( map.get( "k2" ), equalTo( 2 ) ); + } + + @Test + public void testToString() + { + InternalRecord record = createRecord(); + + assertThat( record.toString(), equalTo( "Record<{k1: 0 :: INTEGER, k2: 1 :: INTEGER}>" ) ); + } + + + private InternalRecord createRecord() + { + List keys = Arrays.asList( "k1", "k2" ); + HashMap lookup = new HashMap<>(); + lookup.put( "k1", 0 ); + lookup.put( "k2", 1 ); + + return new InternalRecord( keys, lookup, new Value[]{value( 0 ), value( 1 )} ); + } +} diff --git a/driver/src/test/java/org/neo4j/driver/internal/InternalRelationshipTest.java b/driver/src/test/java/org/neo4j/driver/internal/InternalRelationshipTest.java new file mode 100644 index 0000000000..f70d5e187f --- /dev/null +++ b/driver/src/test/java/org/neo4j/driver/internal/InternalRelationshipTest.java @@ -0,0 +1,82 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.junit.Test; + +import org.neo4j.driver.v1.Function; +import org.neo4j.driver.v1.Value; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; + +import static org.neo4j.driver.v1.Values.NULL; +import static org.neo4j.driver.v1.Values.value; + +public class InternalRelationshipTest +{ + @Test + public void extractValuesFromNode() + { + // GIVEN + InternalRelationship relationship = createRelationship(); + Function extractor = new Function() + { + @Override + public Integer apply( Value value ) + { + return value.asInt(); + } + }; + + //WHEN + Iterable values = relationship.values( extractor ); + + //THEN + Iterator iterator = values.iterator(); + assertThat( iterator.next(), equalTo( 1 ) ); + assertThat( iterator.next(), equalTo( 2 ) ); + assertFalse( iterator.hasNext() ); + } + + @Test + public void accessUnknownKeyShouldBeNull() + { + InternalRelationship relationship = createRelationship(); + + assertThat( relationship.value( "k1" ), equalTo( value( 1 ) ) ); + assertThat( relationship.value( "k2" ), equalTo( value( 2 ) ) ); + assertThat( relationship.value( "k3" ), equalTo( NULL ) ); + } + + private InternalRelationship createRelationship() + { + Map props = new HashMap<>(); + props.put( "k1", value( 1 ) ); + props.put( "k2", value( 2 ) ); + + return new InternalRelationship(1L, 0L, 1L, "T", props ); + } + +} diff --git a/driver/src/test/java/org/neo4j/driver/internal/InternalResultTest.java b/driver/src/test/java/org/neo4j/driver/internal/InternalResultTest.java new file mode 100644 index 0000000000..eb2a734a08 --- /dev/null +++ b/driver/src/test/java/org/neo4j/driver/internal/InternalResultTest.java @@ -0,0 +1,296 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal; + + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import org.neo4j.driver.internal.summary.ResultBuilder; +import org.neo4j.driver.internal.value.NullValue; +import org.neo4j.driver.v1.Field; +import org.neo4j.driver.v1.Record; +import org.neo4j.driver.v1.Records; +import org.neo4j.driver.v1.Result; +import org.neo4j.driver.v1.Value; +import org.neo4j.driver.v1.exceptions.ClientException; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import static org.neo4j.driver.v1.Values.value; + +public class InternalResultTest +{ + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Test + public void iterationShouldWorksAsExpected() + { + // GIVEN + Result result = createResult( 3 ); + + // WHEN + assertThat( result.position(), equalTo( -1L ) ); + assertTrue( result.next() ); //-1 -> 0 + assertTrue( result.first() ); + assertFalse( result.atEnd() ); + assertThat( values( result.record() ), equalTo(Arrays.asList(value("v1-1"), value( "v2-1" )))); + + assertThat( result.position(), equalTo( 0L ) ); + assertTrue( result.next() ); //0 -> 1 + assertFalse( result.first() ); + assertFalse( result.atEnd() ); + assertThat( values( result.record() ), equalTo(Arrays.asList(value("v1-2"), value( "v2-2" )))); + + assertThat( result.position(), equalTo( 1L ) ); + assertTrue( result.next() ); //1 -> 2 + + // THEN + assertThat( result.position(), equalTo( 2L ) ); + assertTrue( result.atEnd() ); + assertFalse( result.first() ); + assertThat( values( result.record() ), equalTo(Arrays.asList(value("v1-3"), value( "v2-3" )))); + assertFalse( result.next() ); + } + + @Test + public void firstFalseOnEmptyStream() + { + assertFalse( createResult( 0 ).first() ); + } + + @Test + public void firstMovesCursorOnce() + { + // GIVEN + Result result = createResult( 3 ); + + // WHEN + assertThat( result.position(), equalTo( -1L ) ); + assertTrue( result.first() ); + assertThat( result.position(), equalTo( 0L ) ); + assertTrue( result.first() ); + assertThat( result.position(), equalTo( 0L ) ); + } + + @Test + public void singleShouldWorkAsExpected() + { + assertFalse( createResult( 42 ).single() ); + assertFalse( createResult( 0 ).single() ); + assertTrue( createResult( 1 ).single() ); + } + + @Test + public void skipShouldWorkAsExpected() + { + // GIVEN + Result result = createResult( 42 ); + + // WHEN + assertThat(result.skip( 22 ), equalTo(22L)); + + // THEN + assertThat( result.position(), equalTo( 21L ) ); + assertThat( values( result.record() ), equalTo( Arrays.asList( value( "v1-22" ), value( "v2-22" ) ) )); + } + + @Test + public void skipBeyondNumberOfRecords() + { + // GIVEN + Result result = createResult( 10 ); + + // WHEN + assertThat(result.skip( 20 ), equalTo(10L)); + + // THEN + assertThat( result.position(), equalTo( 9L ) ); + } + + @Test + public void skipThrowsIfNegativeNumber() + { + Result result = createResult( 10 ); + result.skip( 5 ); + + expectedException.expect( IllegalArgumentException.class ); + result.skip( -1 ); + } + + @Test + public void retainShouldWorkAsExpected() + { + // GIVEN + Result result = createResult( 3 ); + + // WHEN + List records = result.retain(); + + // THEN + assertTrue(result.atEnd()); + assertThat(records, hasSize( 3 ) ); + } + + @Test + public void retainAndMapByKeyShouldWorkAsExpected() + { + // GIVEN + Result result = createResult( 3 ); + + // WHEN + List records = result.retain( Records.columnAsIs( "k1" ) ); + + // THEN + assertTrue(result.atEnd()); + assertThat(records, hasSize( 3 ) ); + } + + @Test + public void retainAndMapByIndexShouldWorkAsExpected() + { + // GIVEN + Result result = createResult( 3 ); + + // WHEN + List records = result.retain( Records.columnAsIs( 0 ) ); + + // THEN + assertTrue(result.atEnd()); + assertThat(records, hasSize( 3 ) ); + } + + @Test + public void retainFailsIfItCannotRetainEntireResult() + { + Result result = createResult( 17 ); + result.skip( 5 ); + + expectedException.expect( ClientException.class ); + result.retain(); + } + + @Test + public void accessingOutOfBoundsShouldBeNull() + { + // GIVEN + Result result = createResult( 1 ); + + // WHEN + result.first(); + + // THEN + assertThat( result.value( 0 ), equalTo( value( "v1-1" ) ) ); + assertThat( result.value( 1 ), equalTo( value( "v2-1" ) ) ); + assertThat( result.value( 2 ), equalTo( NullValue.NULL ) ); + assertThat( result.value( -37 ), equalTo( NullValue.NULL ) ); + } + + @Test + public void accessingRecordsWithoutCallingNextShouldFail() + { + // GIVEN + Result result = createResult( 11 ); + + // WHEN + // not calling next, first, nor skip + + // THEN + expectedException.expect( ClientException.class ); + result.record(); + } + + @Test + public void accessingValueWithoutCallingNextShouldFail() + { + // GIVEN + Result result = createResult( 11 ); + + // WHEN + // not calling next, first, nor skip + + // THEN + expectedException.expect( ClientException.class ); + result.value( 1 ); + } + + @Test + public void accessingFieldsWithoutCallingNextShouldFail() + { + // GIVEN + Result result = createResult( 11 ); + + // WHEN + // not calling next, first, nor skip + + // THEN + expectedException.expect( ClientException.class ); + result.fields( ); + } + + @Test + public void accessingKeysWithoutCallingNextShouldNotFail() + { + // GIVEN + Result result = createResult( 11 ); + + // WHEN + // not calling next, first, nor skip + + // THEN + assertThat( result.keys( ), equalTo( Arrays.asList( "k1", "k2" ) ) ); + } + + @Test + public void shouldHaveCorrectFieldCount() + { + assertThat( createResult( 4 ).fieldCount(), equalTo( 2 ) ); + } + + private Result createResult( int numberOfRecords ) + { + ResultBuilder builder = new ResultBuilder( "", ParameterSupport.NO_PARAMETERS ); + builder.keys( new String[]{"k1", "k2"} ); + for ( int i = 1; i <= numberOfRecords; i++ ) + { + builder.record( new Value[]{value( "v1-" + i ), value( "v2-" + i )} ); + } + return builder.build(); + } + + private List values( Record record ) + { + List result = new ArrayList<>( record.keys().size() ); + for ( Field property : record.fields() ) + { + result.add( property.value() ); + } + return result; + } +} diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/StandardSessionTest.java b/driver/src/test/java/org/neo4j/driver/internal/InternalSessionTest.java similarity index 87% rename from driver/src/test/java/org/neo4j/driver/v1/internal/StandardSessionTest.java rename to driver/src/test/java/org/neo4j/driver/internal/InternalSessionTest.java index baa603383e..8fe3c59883 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/StandardSessionTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/InternalSessionTest.java @@ -16,21 +16,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; +package org.neo4j.driver.internal; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.neo4j.driver.internal.spi.Connection; import org.neo4j.driver.v1.Transaction; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.spi.Connection; import static junit.framework.TestCase.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -public class StandardSessionTest +public class InternalSessionTest { @Rule public ExpectedException exception = ExpectedException.none(); @@ -40,7 +40,7 @@ public void shouldSyncOnRun() throws Throwable { // Given Connection mock = mock( Connection.class ); - StandardSession sess = new StandardSession( mock ); + InternalSession sess = new InternalSession( mock ); // When sess.run( "whatever" ); @@ -54,7 +54,7 @@ public void shouldNotAllowNewTxWhileOneIsRunning() throws Throwable { // Given Connection mock = mock( Connection.class ); - StandardSession sess = new StandardSession( mock ); + InternalSession sess = new InternalSession( mock ); sess.beginTransaction(); // Expect @@ -69,7 +69,7 @@ public void shouldBeAbleToOpenTxAfterPreviousIsClosed() throws Throwable { // Given Connection mock = mock( Connection.class ); - StandardSession sess = new StandardSession( mock ); + InternalSession sess = new InternalSession( mock ); sess.beginTransaction().close(); // When diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/StandardTransactionTest.java b/driver/src/test/java/org/neo4j/driver/internal/InternalTransactionTest.java similarity index 73% rename from driver/src/test/java/org/neo4j/driver/v1/internal/StandardTransactionTest.java rename to driver/src/test/java/org/neo4j/driver/internal/InternalTransactionTest.java index 1c4a63cdde..315448c786 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/StandardTransactionTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/InternalTransactionTest.java @@ -16,20 +16,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; +package org.neo4j.driver.internal; + +import java.util.Collections; import org.junit.Test; import org.mockito.InOrder; -import org.neo4j.driver.v1.internal.spi.Connection; +import org.neo4j.driver.internal.spi.Connection; +import org.neo4j.driver.v1.Value; -import static java.util.Collections.EMPTY_MAP; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; -public class StandardTransactionTest +public class InternalTransactionTest { @Test public void shouldRollbackOnNoExplicitSuccess() throws Throwable @@ -37,16 +39,16 @@ public void shouldRollbackOnNoExplicitSuccess() throws Throwable // Given Connection conn = mock( Connection.class ); Runnable cleanup = mock( Runnable.class ); - StandardTransaction tx = new StandardTransaction( conn, cleanup ); + InternalTransaction tx = new InternalTransaction( conn, cleanup ); // When tx.close(); // Then InOrder order = inOrder( conn ); - order.verify( conn ).run( "BEGIN", EMPTY_MAP, null ); + order.verify( conn ).run( "BEGIN", Collections.emptyMap(), null ); order.verify( conn ).discardAll(); - order.verify( conn ).run( "ROLLBACK", EMPTY_MAP, null ); + order.verify( conn ).run( "ROLLBACK", Collections.emptyMap(), null ); order.verify( conn ).discardAll(); verify( cleanup ).run(); verifyNoMoreInteractions( conn, cleanup ); @@ -58,7 +60,7 @@ public void shouldRollbackOnExplicitFailure() throws Throwable // Given Connection conn = mock( Connection.class ); Runnable cleanup = mock( Runnable.class ); - StandardTransaction tx = new StandardTransaction( conn, cleanup ); + InternalTransaction tx = new InternalTransaction( conn, cleanup ); tx.failure(); tx.success(); // even if success is called after the failure call! @@ -68,9 +70,9 @@ public void shouldRollbackOnExplicitFailure() throws Throwable // Then InOrder order = inOrder( conn ); - order.verify( conn ).run( "BEGIN", EMPTY_MAP, null ); + order.verify( conn ).run( "BEGIN", Collections.emptyMap(), null ); order.verify( conn ).discardAll(); - order.verify( conn ).run( "ROLLBACK", EMPTY_MAP, null ); + order.verify( conn ).run( "ROLLBACK", Collections.emptyMap(), null ); order.verify( conn ).discardAll(); verify( cleanup ).run(); verifyNoMoreInteractions( conn, cleanup ); @@ -82,7 +84,7 @@ public void shouldCommitOnSuccess() throws Throwable // Given Connection conn = mock( Connection.class ); Runnable cleanup = mock( Runnable.class ); - StandardTransaction tx = new StandardTransaction( conn, cleanup ); + InternalTransaction tx = new InternalTransaction( conn, cleanup ); tx.success(); @@ -91,9 +93,9 @@ public void shouldCommitOnSuccess() throws Throwable // Then InOrder order = inOrder( conn ); - order.verify( conn ).run( "BEGIN", EMPTY_MAP, null ); + order.verify( conn ).run( "BEGIN", Collections.emptyMap(), null ); order.verify( conn ).discardAll(); - order.verify( conn ).run( "COMMIT", EMPTY_MAP, null ); + order.verify( conn ).run( "COMMIT", Collections.emptyMap(), null ); order.verify( conn ).discardAll(); order.verify( conn ).sync(); verify( cleanup ).run(); diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/SelfContainedNodeTest.java b/driver/src/test/java/org/neo4j/driver/internal/SelfContainedNodeTest.java similarity index 82% rename from driver/src/test/java/org/neo4j/driver/v1/internal/SelfContainedNodeTest.java rename to driver/src/test/java/org/neo4j/driver/internal/SelfContainedNodeTest.java index cc1e007b8b..5bc2e8412f 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/SelfContainedNodeTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/SelfContainedNodeTest.java @@ -16,19 +16,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; - -import org.junit.Test; +package org.neo4j.driver.internal; import java.util.List; +import org.junit.Test; + +import org.neo4j.driver.internal.util.Iterables; import org.neo4j.driver.v1.Node; -import org.neo4j.driver.v1.internal.util.Iterables; import org.neo4j.driver.v1.Values; -import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; + import static org.neo4j.driver.v1.Values.parameters; public class SelfContainedNodeTest @@ -36,7 +38,7 @@ public class SelfContainedNodeTest private Node adamTheNode() { - return new SimpleNode( 1, asList( "Person" ), + return new InternalNode( 1, singletonList( "Person" ), parameters( "name", Values.value( "Adam" ) ) ); } @@ -57,7 +59,7 @@ public void testLabels() Node node = adamTheNode(); // Then - List labels = Iterables.toList( node.labels() ); + List labels = Iterables.asList( node.labels() ); assertThat( labels.size(), equalTo( 1 ) ); assertThat( labels.contains( "Person" ), equalTo( true ) ); } @@ -69,7 +71,7 @@ public void testKeys() Node node = adamTheNode(); // Then - List keys = Iterables.toList( node.propertyKeys() ); + List keys = Iterables.asList( node.keys() ); assertThat( keys.size(), equalTo( 1 ) ); assertThat( keys.contains( "name" ), equalTo( true ) ); } @@ -81,6 +83,6 @@ public void testValue() Node node = adamTheNode(); // Then - assertThat( node.property( "name" ).javaString(), equalTo( "Adam" ) ); + assertThat( node.value( "name" ).asString(), equalTo( "Adam" ) ); } } diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/ValuesTest.java b/driver/src/test/java/org/neo4j/driver/internal/ValuesTest.java similarity index 81% rename from driver/src/test/java/org/neo4j/driver/v1/internal/ValuesTest.java rename to driver/src/test/java/org/neo4j/driver/internal/ValuesTest.java index 5846b12469..c234882d44 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/ValuesTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/ValuesTest.java @@ -16,29 +16,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +package org.neo4j.driver.internal; import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Set; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.neo4j.driver.internal.value.ListValue; +import org.neo4j.driver.internal.value.MapValue; +import org.neo4j.driver.internal.value.StringValue; import org.neo4j.driver.v1.Value; import org.neo4j.driver.v1.Values; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.value.ListValue; -import org.neo4j.driver.v1.internal.value.MapValue; -import org.neo4j.driver.v1.internal.value.StringValue; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; + import static org.neo4j.driver.v1.Values.value; -import static org.neo4j.driver.v1.Values.valueToList; +import static org.neo4j.driver.v1.Values.valueAsList; import static org.neo4j.driver.v1.Values.valueToString; import static org.neo4j.driver.v1.Values.values; @@ -119,19 +123,24 @@ public void shouldMapDriverComplexTypesToListOfJavaPrimitiveTypes() throws Throw map.put( "Cat", new ListValue( values( "meow", "miaow" ) ) ); map.put( "Dog", new ListValue( values( "wow" ) ) ); map.put( "Wrong", new ListValue( values( -1 ) ) ); - MapValue values = new MapValue( map ); + MapValue mapValue = new MapValue( map ); // When - List> list = values.javaList( valueToList( valueToString() ) ); + Iterable> list = mapValue.values( valueAsList( valueToString() ) ); // Then - assertEquals( 3, list.size() ); - int i = 0; - for ( Value value : values ) + assertEquals( 3, mapValue.size() ); + Iterator> listIterator = list.iterator(); + Set setA = new HashSet<>( 3 ); + Set setB = new HashSet<>( 3 ); + for ( Value value : mapValue.values() ) { - assertEquals( value.get( 0 ).javaString(), list.get( i ).get( 0 ) ); - i++; + String a = value.value( 0 ).toString(); + String b = listIterator.next().get( 0 ); + setA.add( a ); + setB.add( b ); } + assertThat( setA, equalTo( setB ) ); } @Test @@ -144,11 +153,11 @@ public void shouldMapDriverMapsToJavaMaps() throws Throwable MapValue values = new MapValue( map ); // When - Map result = values.javaMap( Values.valueToString() ); + Map result = values.asMap( Values.valueToString() ); // Then assertThat( result.size(), equalTo( 2 ) ); - assertThat( result.get( "Dog" ), equalTo( "2" ) ); - assertThat( result.get( "Cat" ), equalTo( "1" ) ); + assertThat( result.get( "Dog" ), equalTo( "2 :: INTEGER" ) ); + assertThat( result.get( "Cat" ), equalTo( "1 :: INTEGER" ) ); } } diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/ChunkedInputTest.java b/driver/src/test/java/org/neo4j/driver/internal/connector/socket/ChunkedInputTest.java similarity index 97% rename from driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/ChunkedInputTest.java rename to driver/src/test/java/org/neo4j/driver/internal/connector/socket/ChunkedInputTest.java index 27fafa99f4..e56ab5615b 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/ChunkedInputTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/connector/socket/ChunkedInputTest.java @@ -16,12 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.mockito.Matchers; +package org.neo4j.driver.internal.connector.socket; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -31,13 +26,18 @@ import java.nio.channels.ReadableByteChannel; import java.util.Arrays; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Matchers; + import org.neo4j.driver.v1.exceptions.ClientException; import org.neo4j.driver.v1.util.RecordingByteChannel; -import static junit.framework.Assert.fail; -import static junit.framework.TestCase.assertEquals; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/ChunkedOutputTest.java b/driver/src/test/java/org/neo4j/driver/internal/connector/socket/ChunkedOutputTest.java similarity index 96% rename from driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/ChunkedOutputTest.java rename to driver/src/test/java/org/neo4j/driver/internal/connector/socket/ChunkedOutputTest.java index 0765ef9dd3..992f2e872d 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/ChunkedOutputTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/connector/socket/ChunkedOutputTest.java @@ -16,12 +16,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; +package org.neo4j.driver.internal.connector.socket; import org.hamcrest.MatcherAssert; import org.junit.Test; -import org.neo4j.driver.v1.internal.util.BytePrinter; +import org.neo4j.driver.internal.util.BytePrinter; import org.neo4j.driver.v1.util.RecordingByteChannel; import static org.hamcrest.CoreMatchers.equalTo; diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/LoggingResponseHandlerTest.java b/driver/src/test/java/org/neo4j/driver/internal/connector/socket/LoggingResponseHandlerTest.java similarity index 82% rename from driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/LoggingResponseHandlerTest.java rename to driver/src/test/java/org/neo4j/driver/internal/connector/socket/LoggingResponseHandlerTest.java index 28083d16c0..ead8553603 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/LoggingResponseHandlerTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/connector/socket/LoggingResponseHandlerTest.java @@ -16,25 +16,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; +package org.neo4j.driver.internal.connector.socket; import java.util.HashMap; import org.junit.Test; +import org.neo4j.driver.internal.logging.DevNullLogger; +import org.neo4j.driver.internal.messaging.AckFailureMessage; +import org.neo4j.driver.internal.messaging.DiscardAllMessage; +import org.neo4j.driver.internal.messaging.FailureMessage; +import org.neo4j.driver.internal.messaging.IgnoredMessage; +import org.neo4j.driver.internal.messaging.InitMessage; +import org.neo4j.driver.internal.messaging.Message; +import org.neo4j.driver.internal.messaging.MessageHandler; +import org.neo4j.driver.internal.messaging.PullAllMessage; +import org.neo4j.driver.internal.messaging.RecordMessage; +import org.neo4j.driver.internal.messaging.RunMessage; +import org.neo4j.driver.internal.messaging.SuccessMessage; import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.logging.DevNullLogger; -import org.neo4j.driver.v1.internal.messaging.AckFailureMessage; -import org.neo4j.driver.v1.internal.messaging.DiscardAllMessage; -import org.neo4j.driver.v1.internal.messaging.FailureMessage; -import org.neo4j.driver.v1.internal.messaging.IgnoredMessage; -import org.neo4j.driver.v1.internal.messaging.InitMessage; -import org.neo4j.driver.v1.internal.messaging.Message; -import org.neo4j.driver.v1.internal.messaging.MessageHandler; -import org.neo4j.driver.v1.internal.messaging.PullAllMessage; -import org.neo4j.driver.v1.internal.messaging.RecordMessage; -import org.neo4j.driver.v1.internal.messaging.RunMessage; -import org.neo4j.driver.v1.internal.messaging.SuccessMessage; import static org.junit.Assert.assertEquals; @@ -72,7 +72,7 @@ public void shouldLogRunMessage() throws Throwable handler.handleRunMessage( "stat", parameters( "value", new String[]{"cat", "cat", "cat"} ) ); // Then - assertEquals( "S: [RUN \"stat\" {value=ListValue[cat, cat, cat]}]", log ); + assertEquals( "S: [RUN \"stat\" {value=[\"cat\", \"cat\", \"cat\"] :: LIST OF ANY?}]", log ); assertEquals( format( new RunMessage( "stat", parameters( "value", new String[]{"cat", "cat", "cat"} ) ) ), log ); } diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/SSLSocketChannelTest.java b/driver/src/test/java/org/neo4j/driver/internal/connector/socket/SSLSocketChannelTest.java similarity index 98% rename from driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/SSLSocketChannelTest.java rename to driver/src/test/java/org/neo4j/driver/internal/connector/socket/SSLSocketChannelTest.java index 307d6b3cd1..9f8a63f088 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/SSLSocketChannelTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/connector/socket/SSLSocketChannelTest.java @@ -16,13 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; - -import junit.framework.TestCase; -import org.junit.BeforeClass; -import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; +package org.neo4j.driver.internal.connector.socket; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; @@ -30,13 +24,20 @@ import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLSession; -import org.neo4j.driver.v1.internal.spi.Logger; -import org.neo4j.driver.v1.internal.util.BytePrinter; +import junit.framework.TestCase; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import org.neo4j.driver.internal.spi.Logger; +import org.neo4j.driver.internal.util.BytePrinter; import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING; import static javax.net.ssl.SSLEngineResult.Status.BUFFER_OVERFLOW; import static javax.net.ssl.SSLEngineResult.Status.BUFFER_UNDERFLOW; import static javax.net.ssl.SSLEngineResult.Status.OK; + import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.fail; import static org.mockito.Matchers.any; @@ -55,13 +56,12 @@ public class SSLSocketChannelTest private static int bufferSize; private static SSLEngine sslEngine; - private static SSLSession session; @BeforeClass public static void setup() { sslEngine = mock( SSLEngine.class ); - session = mock( SSLSession.class ); + SSLSession session = mock( SSLSession.class ); when( sslEngine.getSession() ).thenReturn( session ); // The strategy to enlarge the application buffer: double the size @@ -273,7 +273,7 @@ public SSLEngineResult answer( InvocationOnMock invocation ) throws Throwable return new SSLEngineResult( OK, NOT_HANDSHAKING, 0, 0 ); case 2: // [XX XX] 02 03 -> 02 03 - bufferSize = bufferSize / 2; // so that we could get the same size back + bufferSize = bufferSize / 2; // so that we could value the same size back return new SSLEngineResult( BUFFER_UNDERFLOW, NOT_HANDSHAKING, 0, 0 ); // waiting for more data case 3: // 02 03 00 01 02 03 -> [XX XX XX XX XX XX] diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/SocketClientTest.java b/driver/src/test/java/org/neo4j/driver/internal/connector/socket/SocketClientTest.java similarity index 94% rename from driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/SocketClientTest.java rename to driver/src/test/java/org/neo4j/driver/internal/connector/socket/SocketClientTest.java index 90a877dfdb..79e2a2bdd0 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/SocketClientTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/connector/socket/SocketClientTest.java @@ -16,18 +16,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; +package org.neo4j.driver.internal.connector.socket; + +import java.net.ServerSocket; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.net.ServerSocket; - +import org.neo4j.driver.internal.logging.DevNullLogger; import org.neo4j.driver.v1.Config; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.logging.DevNullLogger; public class SocketClientTest { diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/SocketResponseHandlerTest.java b/driver/src/test/java/org/neo4j/driver/internal/connector/socket/SocketResponseHandlerTest.java similarity index 90% rename from driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/SocketResponseHandlerTest.java rename to driver/src/test/java/org/neo4j/driver/internal/connector/socket/SocketResponseHandlerTest.java index 58a2cfca42..ef427ac6b5 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/SocketResponseHandlerTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/connector/socket/SocketResponseHandlerTest.java @@ -16,31 +16,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; - -import org.junit.Before; -import org.junit.Test; +package org.neo4j.driver.internal.connector.socket; import java.util.Collections; import java.util.Map; +import org.junit.Before; +import org.junit.Test; + +import org.neo4j.driver.internal.spi.StreamCollector; +import org.neo4j.driver.internal.summary.InternalUpdateStatistics; import org.neo4j.driver.v1.Plan; import org.neo4j.driver.v1.StatementType; import org.neo4j.driver.v1.UpdateStatistics; import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.spi.StreamCollector; -import org.neo4j.driver.v1.internal.summary.SimpleUpdateStatistics; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; + import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; + +import static org.neo4j.driver.internal.summary.InternalPlan.plan; import static org.neo4j.driver.v1.Values.parameters; import static org.neo4j.driver.v1.Values.value; import static org.neo4j.driver.v1.Values.values; -import static org.neo4j.driver.v1.internal.summary.SimplePlan.plan; public class SocketResponseHandlerTest { @@ -82,7 +84,7 @@ public void shouldCollectFieldNames() throws Throwable handler.handleSuccessMessage( data ); // Then - verify( collector ).fieldNames( fieldNames ); + verify( collector ).keys( fieldNames ); verifyNoMoreInteractions( collector ); verifyZeroInteractions( otherCollector ); } @@ -98,7 +100,7 @@ public void shouldCollectBasicMetadata() throws Throwable "properties-set", 12 ) ); - UpdateStatistics stats = new SimpleUpdateStatistics( 1, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0); + UpdateStatistics stats = new InternalUpdateStatistics( 1, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0); // When handler.handleSuccessMessage( data ); @@ -135,7 +137,7 @@ public void shouldCollectPlan() throws Throwable ) ); - UpdateStatistics stats = new SimpleUpdateStatistics( 1, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0 ); + UpdateStatistics stats = new InternalUpdateStatistics( 1, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0 ); Plan plan = plan( "ProduceResults", parameters( "KeyNames", "num", "EstimatedRows", 1.0 ), singletonList( "num" ), diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/TrustOnFirstUseTrustManagerTest.java b/driver/src/test/java/org/neo4j/driver/internal/connector/socket/TrustOnFirstUseTrustManagerTest.java similarity index 92% rename from driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/TrustOnFirstUseTrustManagerTest.java rename to driver/src/test/java/org/neo4j/driver/internal/connector/socket/TrustOnFirstUseTrustManagerTest.java index 934af26e51..9a21791c6c 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/connector/socket/TrustOnFirstUseTrustManagerTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/connector/socket/TrustOnFirstUseTrustManagerTest.java @@ -16,11 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.connector.socket; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +package org.neo4j.driver.internal.connector.socket; import java.io.File; import java.io.PrintWriter; @@ -29,9 +25,13 @@ import java.util.Scanner; import javax.xml.bind.DatatypeConverter; -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertTrue; -import static junit.framework.TestCase.fail; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -43,8 +43,6 @@ public class TrustOnFirstUseTrustManagerTest private static int knownServerPort; private static String knownServer; - private static String knownCert; - @BeforeClass public static void setup() throws Throwable { @@ -53,7 +51,7 @@ public static void setup() throws Throwable knownServerIp = "1.2.3.4"; knownServerPort = 100; knownServer = knownServerIp + ":" + knownServerPort; - knownCert = DatatypeConverter.printBase64Binary( "certificate".getBytes() ); + String knownCert = DatatypeConverter.printBase64Binary( "certificate".getBytes() ); PrintWriter writer = new PrintWriter( knownCertsFile ); writer.println( " # I am a comment." ); @@ -61,6 +59,7 @@ public static void setup() throws Throwable writer.close(); } + @SuppressWarnings("ResultOfMethodCallIgnored") @AfterClass public static void teardown() { diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/logging/ConsoleLoggingTest.java b/driver/src/test/java/org/neo4j/driver/internal/logging/ConsoleLoggingTest.java similarity index 94% rename from driver/src/test/java/org/neo4j/driver/v1/internal/logging/ConsoleLoggingTest.java rename to driver/src/test/java/org/neo4j/driver/internal/logging/ConsoleLoggingTest.java index c01b27aed0..7f39e9d701 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/logging/ConsoleLoggingTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/logging/ConsoleLoggingTest.java @@ -16,12 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.logging; - -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +package org.neo4j.driver.internal.logging; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -29,8 +24,13 @@ import java.util.Scanner; import java.util.logging.Level; -import org.neo4j.driver.v1.internal.logging.ConsoleLogging.ConsoleLogger; -import org.neo4j.driver.v1.internal.spi.Logger; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import org.neo4j.driver.internal.logging.ConsoleLogging.ConsoleLogger; +import org.neo4j.driver.internal.spi.Logger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/messaging/MessageFormatTest.java b/driver/src/test/java/org/neo4j/driver/internal/messaging/MessageFormatTest.java similarity index 83% rename from driver/src/test/java/org/neo4j/driver/v1/internal/messaging/MessageFormatTest.java rename to driver/src/test/java/org/neo4j/driver/internal/messaging/MessageFormatTest.java index b52b88c7d9..4822cf17f0 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/messaging/MessageFormatTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/messaging/MessageFormatTest.java @@ -16,11 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.messaging; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +package org.neo4j.driver.internal.messaging; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -28,21 +24,28 @@ import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import org.neo4j.driver.internal.InternalNode; +import org.neo4j.driver.internal.InternalPath; +import org.neo4j.driver.internal.InternalRelationship; +import org.neo4j.driver.internal.connector.socket.ChunkedOutput; +import org.neo4j.driver.internal.packstream.PackStream; +import org.neo4j.driver.internal.util.BytePrinter; import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.SimpleNode; -import org.neo4j.driver.v1.internal.SimplePath; -import org.neo4j.driver.v1.internal.SimpleRelationship; -import org.neo4j.driver.v1.internal.connector.socket.ChunkedOutput; -import org.neo4j.driver.v1.internal.packstream.PackStream; -import org.neo4j.driver.v1.internal.util.BytePrinter; import org.neo4j.driver.v1.util.DumpMessage; import static java.util.Arrays.asList; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.startsWith; + import static org.neo4j.driver.v1.Values.parameters; import static org.neo4j.driver.v1.Values.value; @@ -68,7 +71,7 @@ public void shouldPackAllRequests() throws Throwable @Test public void shouldUnpackAllResponses() throws Throwable { - assertSerializes( new RecordMessage( new Value[]{value( 1337l )} ) ); + assertSerializes( new RecordMessage( new Value[]{value( 1337L )} ) ); assertSerializes( new SuccessMessage( new HashMap() ) ); } @@ -79,23 +82,23 @@ public void shouldUnpackAllValues() throws Throwable assertSerializesValue( value( parameters( "k", 12, "a", "banana" ) ) ); assertSerializesValue( value( asList( "k", 12, "a", "banana" ) ) ); assertSerializesValue( value( - new SimpleNode( 1, asList( "User" ), parameters( "name", "Bob", "age", 45 ) ) ) ); - assertSerializesValue( value( new SimpleNode( 1 ) ) ); + new InternalNode( 1, Collections.singletonList( "User" ), parameters( "name", "Bob", "age", 45 ) ) ) ); + assertSerializesValue( value( new InternalNode( 1 ) ) ); assertSerializesValue( value( - new SimpleRelationship( 1, 1, 1, + new InternalRelationship( 1, 1, 1, "KNOWS", parameters( "name", "Bob", "age", 45 ) ) ) ); assertSerializesValue( value( - new SimplePath( - new SimpleNode( 1 ), - new SimpleRelationship( 1, 1, 1, + new InternalPath( + new InternalNode( 1 ), + new InternalRelationship( 1, 1, 1, "KNOWS", parameters() ), - new SimpleNode( 1 ), - new SimpleRelationship( 2, 1, 1, + new InternalNode( 1 ), + new InternalRelationship( 2, 1, 1, "LIKES", parameters() ), - new SimpleNode( 1 ) + new InternalNode( 1 ) ) ) ); - assertSerializesValue( value( new SimplePath( new SimpleNode( 1 ) ) ) ); + assertSerializesValue( value( new InternalPath( new InternalNode( 1 ) ) ) ); } @Test diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/packstream/PackStreamTest.java b/driver/src/test/java/org/neo4j/driver/internal/packstream/PackStreamTest.java similarity index 99% rename from driver/src/test/java/org/neo4j/driver/v1/internal/packstream/PackStreamTest.java rename to driver/src/test/java/org/neo4j/driver/internal/packstream/PackStreamTest.java index efbe52f1f9..a7fc8fedd4 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/packstream/PackStreamTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/packstream/PackStreamTest.java @@ -16,10 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.packstream; - -import org.hamcrest.MatcherAssert; -import org.junit.Test; +package org.neo4j.driver.internal.packstream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -30,10 +27,14 @@ import java.util.LinkedHashMap; import java.util.Map; -import org.neo4j.driver.v1.internal.util.BytePrinter; +import org.hamcrest.MatcherAssert; +import org.junit.Test; + +import org.neo4j.driver.internal.util.BytePrinter; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Arrays.asList; + import static junit.framework.TestCase.assertFalse; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/pool/ConnectionInvalidationTest.java b/driver/src/test/java/org/neo4j/driver/internal/pool/ConnectionInvalidationTest.java similarity index 97% rename from driver/src/test/java/org/neo4j/driver/v1/internal/pool/ConnectionInvalidationTest.java rename to driver/src/test/java/org/neo4j/driver/internal/pool/ConnectionInvalidationTest.java index e8c779741a..bf7bd87032 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/pool/ConnectionInvalidationTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/pool/ConnectionInvalidationTest.java @@ -16,17 +16,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.pool; +package org.neo4j.driver.internal.pool; + +import java.io.IOException; import org.junit.Test; import org.mockito.Mockito; -import java.io.IOException; - +import org.neo4j.driver.internal.spi.Connection; import org.neo4j.driver.v1.exceptions.ClientException; import org.neo4j.driver.v1.exceptions.Neo4jException; import org.neo4j.driver.v1.exceptions.TransientException; -import org.neo4j.driver.v1.internal.spi.Connection; import static junit.framework.TestCase.assertFalse; import static org.hamcrest.CoreMatchers.equalTo; diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/pool/StandardConnectionPoolTest.java b/driver/src/test/java/org/neo4j/driver/internal/pool/InternalConnectionPoolTest.java similarity index 81% rename from driver/src/test/java/org/neo4j/driver/v1/internal/pool/StandardConnectionPoolTest.java rename to driver/src/test/java/org/neo4j/driver/internal/pool/InternalConnectionPoolTest.java index b5d5e984ef..2ab8d76d90 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/pool/StandardConnectionPoolTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/pool/InternalConnectionPoolTest.java @@ -16,21 +16,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.pool; +package org.neo4j.driver.internal.pool; + +import java.net.URI; +import java.util.Collections; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.net.URI; - +import org.neo4j.driver.internal.spi.Connection; +import org.neo4j.driver.internal.spi.Connector; +import org.neo4j.driver.internal.util.Clock; import org.neo4j.driver.v1.Config; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.spi.Connection; -import org.neo4j.driver.v1.internal.spi.Connector; -import org.neo4j.driver.v1.internal.util.Clock; -import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; + import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -38,7 +40,7 @@ import static org.mockito.Mockito.when; -public class StandardConnectionPoolTest +public class InternalConnectionPoolTest { @Rule @@ -52,7 +54,7 @@ public void shouldThrowExceptionWhenConnectionPoolIsFullWhatever() throws Throwa URI uri = URI.create( "bolt://asd" ); Connector connector = connector( "bolt" ); Config config = Config.build().withConnectionPoolSize( 1 ).toConfig(); - StandardConnectionPool pool = new StandardConnectionPool( asList( connector ), + InternalConnectionPool pool = new InternalConnectionPool( singletonList( connector ), Clock.SYSTEM, config ); // When & Then @@ -73,7 +75,7 @@ public void shouldAcquireAndRelease() throws Throwable URI uri = URI.create( "bolt://asd" ); Connector connector = connector( "bolt" ); Config config = Config.defaultConfig(); - StandardConnectionPool pool = new StandardConnectionPool( asList( connector ), + InternalConnectionPool pool = new InternalConnectionPool( singletonList( connector ), Clock.SYSTEM, config ); Connection conn = pool.acquire( uri ); @@ -89,7 +91,7 @@ public void shouldAcquireAndRelease() throws Throwable private Connector connector( String scheme ) { Connector mock = mock( Connector.class ); - when( mock.supportedSchemes() ).thenReturn( asList( scheme ) ); + when( mock.supportedSchemes() ).thenReturn( Collections.singletonList( scheme ) ); when( mock.connect( any( URI.class ), any( Config.class ) ) ).thenReturn( mock( Connection.class ) ); return mock; } diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/pool/ThreadCachingPoolTest.java b/driver/src/test/java/org/neo4j/driver/internal/pool/ThreadCachingPoolTest.java similarity index 96% rename from driver/src/test/java/org/neo4j/driver/v1/internal/pool/ThreadCachingPoolTest.java rename to driver/src/test/java/org/neo4j/driver/internal/pool/ThreadCachingPoolTest.java index f06f8a5c70..fda9727937 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/pool/ThreadCachingPoolTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/pool/ThreadCachingPoolTest.java @@ -16,12 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.pool; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +package org.neo4j.driver.internal.pool; import java.util.Arrays; import java.util.Collections; @@ -30,9 +25,14 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import org.neo4j.driver.internal.util.Clock; +import org.neo4j.driver.internal.util.Consumer; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.util.Consumer; -import org.neo4j.driver.v1.internal.util.Clock; import static junit.framework.TestCase.fail; import static org.hamcrest.MatcherAssert.assertThat; @@ -179,7 +179,7 @@ public void shouldDisposeOfObjectsThatBecomeInvalidWhileInUse() throws Throwable @Test public void shouldRecoverFromItemCreationFailure() throws Throwable { - // Given a pool where creation will fail from the get-go + // Given a pool where creation will fail from the value-go ThreadCachingPool pool = new ThreadCachingPool<>( 4, trackAllocator, checkInvalidateFlag, Clock.SYSTEM ); @@ -215,7 +215,7 @@ public void shouldRecoverFromItemCreationFailure() throws Throwable @Test public void shouldRecovedDisposedItemReallocationFailing() throws Throwable { - // Given a pool where creation will fail from the get-go + // Given a pool where creation will fail from the value-go ThreadCachingPool pool = new ThreadCachingPool<>( 2, trackAllocator, checkInvalidateFlag, Clock.SYSTEM ); @@ -255,7 +255,7 @@ public void shouldRecovedDisposedItemReallocationFailing() throws Throwable } assertThat( inPool, equalTo( none() ) ); assertThat( inUse, equalTo( items( 2, 3 ) ) ); - // only the first two items get onDispose called, since allocation fails after that + // only the first two items value onDispose called, since allocation fails after that assertThat( disposed, equalTo( items( 0, 1) ) ); } diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/summary/SimplePlanTest.java b/driver/src/test/java/org/neo4j/driver/internal/summary/InternalPlanTest.java similarity index 91% rename from driver/src/test/java/org/neo4j/driver/v1/internal/summary/SimplePlanTest.java rename to driver/src/test/java/org/neo4j/driver/internal/summary/InternalPlanTest.java index d1d010cccf..b6171b08c7 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/summary/SimplePlanTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/summary/InternalPlanTest.java @@ -16,24 +16,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.summary; - -import org.junit.Test; +package org.neo4j.driver.internal.summary; import java.util.Collections; import java.util.List; +import org.junit.Test; + import org.neo4j.driver.v1.Plan; import org.neo4j.driver.v1.Value; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; + import static org.neo4j.driver.v1.Values.parameters; import static org.neo4j.driver.v1.Values.value; import static org.neo4j.driver.v1.Values.values; @SuppressWarnings("unchecked") -public class SimplePlanTest +public class InternalPlanTest { @Test public void shouldConvertFromEmptyMapValue() @@ -42,7 +43,7 @@ public void shouldConvertFromEmptyMapValue() Value value = value( parameters( "operatorType", "X" ) ); // When - Plan plan = SimplePlan.EXPLAIN_PLAN_FROM_VALUE.apply( value ); + Plan plan = InternalPlan.EXPLAIN_PLAN_FROM_VALUE.apply( value ); // Then assertThat( plan.operatorType(), equalTo( "X") ); @@ -63,7 +64,7 @@ public void shouldConvertFromSimpleMapValue() ) ); // When - Plan plan = SimplePlan.EXPLAIN_PLAN_FROM_VALUE.apply( value ); + Plan plan = InternalPlan.EXPLAIN_PLAN_FROM_VALUE.apply( value ); // Then assertThat( plan.operatorType(), equalTo( "X") ); @@ -88,7 +89,7 @@ public void shouldConvertFromNestedMapValue() ) ); // When - Plan plan = SimplePlan.EXPLAIN_PLAN_FROM_VALUE.apply( value ); + Plan plan = InternalPlan.EXPLAIN_PLAN_FROM_VALUE.apply( value ); // Then assertThat( plan.operatorType(), equalTo( "X") ); diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/summary/ResultBuilderTest.java b/driver/src/test/java/org/neo4j/driver/internal/summary/ResultCursorBuilderTest.java similarity index 63% rename from driver/src/test/java/org/neo4j/driver/v1/internal/summary/ResultBuilderTest.java rename to driver/src/test/java/org/neo4j/driver/internal/summary/ResultCursorBuilderTest.java index 6e773c45e6..d9e0ba1326 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/summary/ResultBuilderTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/summary/ResultCursorBuilderTest.java @@ -16,23 +16,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.summary; +package org.neo4j.driver.internal.summary; + +import java.util.List; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.neo4j.driver.internal.ParameterSupport; import org.neo4j.driver.v1.Record; -import org.neo4j.driver.v1.ReusableResult; import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.ParameterSupport; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; + import static org.neo4j.driver.v1.Values.value; -public class ResultBuilderTest +public class ResultCursorBuilderTest { @Rule public ExpectedException exception = ExpectedException.none(); @@ -42,17 +43,17 @@ public void shouldBuildHappyPathResult() { // Given ResultBuilder builder = createResultBuilder(); - builder.fieldNames( new String[]{"a"} ); + builder.keys( new String[]{"a"} ); builder.record( new Value[]{value( "Admin" )} ); // When - ReusableResult result = builder.build().retain(); + List result = builder.build().retain(); // Then - assertThat( result.size(), equalTo( 1l ) ); + assertThat( result.size(), equalTo( 1 ) ); Record record = result.get( 0 ); - assertThat( record.get( 0 ).javaString(), equalTo( "Admin" ) ); + assertThat( record.value( 0 ).asString(), equalTo( "Admin" ) ); } @Test @@ -62,27 +63,10 @@ public void shouldHandleEmptyTable() ResultBuilder builder = createResultBuilder(); // When - ReusableResult result = builder.build().retain(); + List result = builder.build().retain(); // Then - assertThat( result.size(), equalTo( 0l ) ); - } - - @Test - public void shouldThrowNoSuchSomething() - { - // Given - ResultBuilder builder = createResultBuilder(); - builder.fieldNames( new String[]{"a"} ); - builder.record( new Value[]{value( "Admin" )} ); - - ReusableResult result = builder.build().retain(); - - // Expect - exception.expect( ClientException.class ); - - // When - result.get( 2 ); + assertThat( result.size(), equalTo( 0 ) ); } private ResultBuilder createResultBuilder() diff --git a/driver/src/test/java/org/neo4j/driver/internal/util/ExtractTest.java b/driver/src/test/java/org/neo4j/driver/internal/util/ExtractTest.java new file mode 100644 index 0000000000..f87a56fa58 --- /dev/null +++ b/driver/src/test/java/org/neo4j/driver/internal/util/ExtractTest.java @@ -0,0 +1,181 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.util; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import org.neo4j.driver.internal.InternalField; +import org.neo4j.driver.internal.InternalNode; +import org.neo4j.driver.internal.InternalProperty; +import org.neo4j.driver.internal.ParameterSupport; +import org.neo4j.driver.internal.summary.ResultBuilder; +import org.neo4j.driver.v1.Field; +import org.neo4j.driver.v1.Function; +import org.neo4j.driver.v1.Property; +import org.neo4j.driver.v1.Result; +import org.neo4j.driver.v1.Value; + +import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.empty; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; + +import static org.neo4j.driver.v1.Values.value; + +public class ExtractTest +{ + @Rule + public ExpectedException exception = ExpectedException.none(); + + @Test + public void extractEmptyArrayShouldNotBeModifiable() throws Exception + { + List list = Extract.list( new Value[]{} ); + + assertThat( list, empty() ); + exception.expect( UnsupportedOperationException.class ); + list.add( null ); + } + + @Test + public void extractSingletonShouldNotBeModifiable() throws Exception + { + List list = Extract.list( new Value[]{value( 42 )} ); + + assertThat( list, equalTo( singletonList( value( 42 ) ) ) ); + exception.expect( UnsupportedOperationException.class ); + list.add( null ); + } + + @Test + public void extractMultipleShouldNotBeModifiable() throws Exception + { + List list = Extract.list( new Value[]{value( 42 ), value( 43 )} ); + + assertThat( list, equalTo( asList( value( 42 ), value( 43 ) ) ) ); + exception.expect( UnsupportedOperationException.class ); + list.add( null ); + } + + @Test + public void testMapOverList() throws Exception + { + List mapped = Extract.list( new Value[]{value( 42 ), value( 43 )}, integerExtractor() ); + + assertThat( mapped, equalTo( Arrays.asList( 42, 43 ) ) ); + } + + @Test + public void testMapShouldNotBeModifiable() throws Exception + { + // GIVEN + Map map = new HashMap<>(); + map.put( "k1", value( "foo" ) ); + map.put( "k2", value( 42 ) ); + + // WHEN + Map valueMap = Extract.map( map ); + + // THEN + exception.expect( UnsupportedOperationException.class ); + valueMap.put( "foo", value( "bar" ) ); + } + + @Test + public void testMapValues() throws Exception + { + // GIVEN + Map map = new HashMap<>(); + map.put( "k1", value( 43 ) ); + map.put( "k2", value( 42 ) ); + + // WHEN + Map mappedMap = Extract.map( map, integerExtractor() ); + + // THEN + Collection values = mappedMap.values(); + assertThat( values, containsInAnyOrder( 43, 42 ) ); + + } + + @Test + public void testProperties() throws Exception + { + // GIVEN + Map props = new HashMap<>(); + props.put( "k1", value( 43 ) ); + props.put( "k2", value( 42 ) ); + InternalNode node = new InternalNode( 42L, Collections.singletonList( "L" ), props ); + + // WHEN + Iterable> properties = Extract.properties( node, integerExtractor() ); + + // THEN + Iterator> iterator = properties.iterator(); + assertThat( iterator.next(), equalTo( InternalProperty.of( "k1", 43 ) ) ); + assertThat( iterator.next(), equalTo( InternalProperty.of( "k2", 42 ) ) ); + assertFalse( iterator.hasNext() ); + } + + @Test + public void testFields() throws Exception + { + // GIVEN + ResultBuilder builder = new ResultBuilder( "", ParameterSupport.NO_PARAMETERS ); + builder.keys( new String[]{"k1"} ); + builder.record( new Value[]{value(42)} ); + Result result = builder.build(); + result.first(); + + // WHEN + List> fields = Extract.fields( result, integerExtractor() ); + + + // THEN + assertThat( fields, equalTo( Collections.singletonList( InternalField.of( "k1", 0, 42 ) ) ) ); + } + + private Function integerExtractor() + { + return new Function() + { + + @Override + public Integer apply( Value value ) + { + return value.asInt(); + } + }; + } + +} diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/value/BooleanValueTest.java b/driver/src/test/java/org/neo4j/driver/internal/value/BooleanValueTest.java similarity index 62% rename from driver/src/test/java/org/neo4j/driver/v1/internal/value/BooleanValueTest.java rename to driver/src/test/java/org/neo4j/driver/internal/value/BooleanValueTest.java index 20d9c6ecd8..5ea720b5ac 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/value/BooleanValueTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/value/BooleanValueTest.java @@ -16,22 +16,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.value; +package org.neo4j.driver.internal.value; import org.junit.Test; -import org.neo4j.driver.v1.internal.types.TypeConstructor; +import org.neo4j.driver.internal.types.InternalTypeSystem; +import org.neo4j.driver.internal.types.TypeConstructor; +import org.neo4j.driver.v1.TypeSystem; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; -import static org.neo4j.driver.v1.internal.value.BooleanValue.FALSE; -import static org.neo4j.driver.v1.internal.value.BooleanValue.TRUE; +import static org.neo4j.driver.internal.value.BooleanValue.FALSE; +import static org.neo4j.driver.internal.value.BooleanValue.TRUE; public class BooleanValueTest { + TypeSystem typeSystem = InternalTypeSystem.TYPE_SYSTEM; @Test public void testBooleanTrue() throws Exception @@ -40,11 +44,9 @@ public void testBooleanTrue() throws Exception BooleanValue value = TRUE; // Then - assertThat( value.javaBoolean(), equalTo( true ) ); - assertThat( value.javaInteger(), equalTo( 1 ) ); - assertThat( value.javaLong(), equalTo( 1L ) ); - assertThat( value.javaFloat(), equalTo( (float) 1.0 ) ); - assertThat( value.javaDouble(), equalTo( 1.0 ) ); + assertThat( value.asBoolean(), equalTo( true ) ); + assertThat( value.isTrue(), equalTo( true ) ); + assertThat( value.isFalse(), equalTo( false ) ); } @Test @@ -54,11 +56,9 @@ public void testBooleanFalse() throws Exception BooleanValue value = FALSE; // Then - assertThat( value.javaBoolean(), equalTo( false ) ); - assertThat( value.javaInteger(), equalTo( 0 ) ); - assertThat( value.javaLong(), equalTo( 0L ) ); - assertThat( value.javaFloat(), equalTo( (float) 0.0 ) ); - assertThat( value.javaDouble(), equalTo( 0.0 ) ); + assertThat( value.asBoolean(), equalTo( false ) ); + assertThat( value.isTrue(), equalTo( false ) ); + assertThat( value.isFalse(), equalTo( true ) ); } @Test @@ -68,7 +68,7 @@ public void testIsBoolean() throws Exception BooleanValue value = TRUE; // Then - assertThat( value.isBoolean(), equalTo( true ) ); + assertThat( typeSystem.BOOLEAN().isTypeOf( value ), equalTo( true ) ); } @Test @@ -95,14 +95,23 @@ public void testHashCode() throws Exception @Test public void shouldNotBeNull() { - assertFalse( BooleanValue.TRUE.isNull() ); + assertFalse( TRUE.isNull() ); assertFalse( BooleanValue.FALSE.isNull() ); } @Test public void shouldTypeAsBoolean() { - assertThat( BooleanValue.TRUE.typeConstructor(), equalTo( TypeConstructor.BOOLEAN_TyCon ) ); + assertThat( TRUE.typeConstructor(), equalTo( TypeConstructor.BOOLEAN_TyCon ) ); assertThat( BooleanValue.FALSE.typeConstructor(), equalTo( TypeConstructor.BOOLEAN_TyCon ) ); } + + @Test + public void shouldConvertToBooleanAndObject() + { + assertTrue( TRUE.asBoolean()); + assertFalse( BooleanValue.FALSE.asBoolean()); + assertThat( TRUE.asObject(), equalTo( (Object) Boolean.TRUE )); + assertThat( FALSE.asObject(), equalTo( (Object) Boolean.FALSE )); + } } diff --git a/driver/src/test/java/org/neo4j/driver/internal/value/FloatValueTest.java b/driver/src/test/java/org/neo4j/driver/internal/value/FloatValueTest.java new file mode 100644 index 0000000000..d6c7702422 --- /dev/null +++ b/driver/src/test/java/org/neo4j/driver/internal/value/FloatValueTest.java @@ -0,0 +1,185 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.value; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import org.neo4j.driver.internal.types.InternalTypeSystem; +import org.neo4j.driver.internal.types.TypeConstructor; +import org.neo4j.driver.v1.TypeSystem; +import org.neo4j.driver.v1.Value; +import org.neo4j.driver.v1.exceptions.value.LossyCoercion; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; + +public class FloatValueTest +{ + TypeSystem typeSystem = InternalTypeSystem.TYPE_SYSTEM; + + @Rule + public ExpectedException exception = ExpectedException.none(); + + @Test + public void testZeroFloatValue() throws Exception + { + // Given + FloatValue value = new FloatValue( 0 ); + + // Then + assertThat( value.asInt(), equalTo( 0 ) ); + assertThat( value.asLong(), equalTo( 0L ) ); + assertThat( value.asFloat(), equalTo( (float) 0.0 ) ); + assertThat( value.asDouble(), equalTo( 0.0 ) ); + } + + @Test + public void testNonZeroFloatValue() throws Exception + { + // Given + FloatValue value = new FloatValue( 6.28 ); + + // Then + assertThat( value.asDouble(), equalTo( 6.28 ) ); + } + + @Test + public void testIsFloat() throws Exception + { + // Given + FloatValue value = new FloatValue( 6.28 ); + + // Then + assertThat( typeSystem.FLOAT().isTypeOf( value ), equalTo( true ) ); + } + + @Test + public void testEquals() throws Exception + { + // Given + FloatValue firstValue = new FloatValue( 6.28 ); + FloatValue secondValue = new FloatValue( 6.28 ); + + // Then + assertThat( firstValue, equalTo( secondValue ) ); + } + + @Test + public void testHashCode() throws Exception + { + // Given + FloatValue value = new FloatValue( 6.28 ); + + // Then + assertThat( value.hashCode(), notNullValue() ); + } + + @Test + public void shouldNotBeNull() + { + Value value = new FloatValue( 6.28 ); + assertFalse( value.isNull() ); + } + + @Test + public void shouldTypeAsFloat() + { + InternalValue value = new FloatValue( 6.28 ); + assertThat( value.typeConstructor(), equalTo( TypeConstructor.FLOAT_TyCon ) ); + } + + @Test + public void shouldThrowIfFloatContainsDecimalWhenConverting() + { + FloatValue value = new FloatValue( 1.1 ); + + exception.expect( LossyCoercion.class ); + value.asInt(); + } + + @Test + public void shouldThrowIfLargerThanByteMax() + { + FloatValue value1 = new FloatValue( 127 ); + FloatValue value2 = new FloatValue( 128 ); + + assertThat(value1.asByte(), equalTo((byte) 127)); + exception.expect( LossyCoercion.class ); + value2.asByte(); + } + + @Test + public void shouldThrowIfSmallerThanByteMin() + { + FloatValue value1 = new FloatValue( -128 ); + FloatValue value2 = new FloatValue( -129 ); + + assertThat(value1.asByte(), equalTo((byte) -128)); + exception.expect( LossyCoercion.class ); + value2.asByte(); + } + + @Test + public void shouldThrowIfLargerThanShortMax() + { + FloatValue value1 = new FloatValue( Short.MAX_VALUE ); + FloatValue value2 = new FloatValue( Short.MAX_VALUE + 1); + + assertThat(value1.asShort(), equalTo(Short.MAX_VALUE)); + exception.expect( LossyCoercion.class ); + value2.asShort(); + } + + @Test + public void shouldThrowIfSmallerThanShortMin() + { + FloatValue value1 = new FloatValue( Short.MIN_VALUE ); + FloatValue value2 = new FloatValue( Short.MIN_VALUE - 1 ); + + assertThat(value1.asShort(), equalTo(Short.MIN_VALUE)); + exception.expect( LossyCoercion.class ); + value2.asShort(); + } + + @Test + public void shouldThrowIfLargerThanIntegerMax() + { + FloatValue value1 = new FloatValue( Integer.MAX_VALUE ); + FloatValue value2 = new FloatValue( Integer.MAX_VALUE + 1L); + + assertThat(value1.asInt(), equalTo(Integer.MAX_VALUE)); + exception.expect( LossyCoercion.class ); + value2.asInt(); + } + + @Test + public void shouldThrowIfSmallerThanIntegerMin() + { + FloatValue value1 = new FloatValue( Integer.MIN_VALUE ); + FloatValue value2 = new FloatValue( Integer.MIN_VALUE - 1L ); + + assertThat(value1.asInt(), equalTo(Integer.MIN_VALUE)); + exception.expect( LossyCoercion.class ); + value2.asInt(); + } +} diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/value/IdentityValueTest.java b/driver/src/test/java/org/neo4j/driver/internal/value/IdentityValueTest.java similarity index 86% rename from driver/src/test/java/org/neo4j/driver/v1/internal/value/IdentityValueTest.java rename to driver/src/test/java/org/neo4j/driver/internal/value/IdentityValueTest.java index b3f59d1554..a1ca7bbcf9 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/value/IdentityValueTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/value/IdentityValueTest.java @@ -16,14 +16,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.value; +package org.neo4j.driver.internal.value; import org.junit.Test; +import org.neo4j.driver.internal.Identities; +import org.neo4j.driver.internal.types.InternalTypeSystem; +import org.neo4j.driver.internal.types.TypeConstructor; import org.neo4j.driver.v1.Identity; +import org.neo4j.driver.v1.TypeSystem; import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.Identities; -import org.neo4j.driver.v1.internal.types.TypeConstructor; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.notNullValue; @@ -32,6 +34,8 @@ public class IdentityValueTest { + TypeSystem typeSystem = InternalTypeSystem.TYPE_SYSTEM; + @Test public void testValueAsIdentity() throws Exception { @@ -51,7 +55,7 @@ public void testIsIdentity() throws Exception IdentityValue value = new IdentityValue( id ); // Then - assertThat( value.isIdentity(), equalTo( true ) ); + assertThat( typeSystem.IDENTITY().isTypeOf( value ), equalTo( true ) ); } @Test diff --git a/driver/src/test/java/org/neo4j/driver/internal/value/IntegerValueTest.java b/driver/src/test/java/org/neo4j/driver/internal/value/IntegerValueTest.java new file mode 100644 index 0000000000..2bc5596db5 --- /dev/null +++ b/driver/src/test/java/org/neo4j/driver/internal/value/IntegerValueTest.java @@ -0,0 +1,196 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.value; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import org.neo4j.driver.internal.types.InternalTypeSystem; +import org.neo4j.driver.internal.types.TypeConstructor; +import org.neo4j.driver.v1.TypeSystem; +import org.neo4j.driver.v1.Value; +import org.neo4j.driver.v1.exceptions.value.LossyCoercion; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; + +public class IntegerValueTest +{ + TypeSystem typeSystem = InternalTypeSystem.TYPE_SYSTEM; + @Rule + public ExpectedException exception = ExpectedException.none(); + + + @Test + public void testZeroIntegerValue() throws Exception + { + // Given + IntegerValue value = new IntegerValue( 0 ); + + // Then + assertThat( value.asLong(), equalTo( 0L ) ); + assertThat( value.asInt(), equalTo( 0 ) ); + assertThat( value.asShort(), equalTo( (short) 0 ) ); + assertThat( value.asByte(), equalTo( (byte) 0 ) ); + assertThat( value.asDouble(), equalTo( 0.0 ) ); + assertThat( value.asFloat(), equalTo( (float) 0.0 ) ); + assertThat( value.asNumber(), equalTo( (Number) 0L ) ); + } + + @Test + public void testNonZeroIntegerValue() throws Exception + { + // Given + IntegerValue value = new IntegerValue( 1 ); + + // Then + assertThat( value.asLong(), equalTo( 1L ) ); + assertThat( value.asInt(), equalTo( 1 ) ); + assertThat( value.asShort(), equalTo( (short) 1 ) ); + assertThat( value.asByte(), equalTo( (byte) 1 ) ); + assertThat( value.asDouble(), equalTo( 1.0 ) ); + assertThat( value.asFloat(), equalTo( (float) 1.0 ) ); + assertThat( value.asNumber(), equalTo( (Number) 1L ) ); + } + + @Test + public void testIsInteger() throws Exception + { + // Given + IntegerValue value = new IntegerValue( 1L ); + + // Then + assertThat( typeSystem.INTEGER().isTypeOf( value ), equalTo( true ) ); + } + + @Test + public void testEquals() throws Exception + { + // Given + IntegerValue firstValue = new IntegerValue( 1 ); + IntegerValue secondValue = new IntegerValue( 1 ); + + // Then + assertThat( firstValue, equalTo( secondValue ) ); + } + + @Test + public void testHashCode() throws Exception + { + // Given + IntegerValue value = new IntegerValue( 1L ); + + // Then + assertThat( value.hashCode(), notNullValue() ); + } + + @Test + public void shouldNotBeNull() + { + Value value = new IntegerValue( 1L ); + assertFalse( value.isNull() ); + } + + @Test + public void shouldTypeAsInteger() + { + InternalValue value = new IntegerValue( 1L ); + assertThat( value.typeConstructor(), equalTo( TypeConstructor.INTEGER_TyCon ) ); + } + + @Test + public void shouldThrowIfLargerThanByteMax() + { + IntegerValue value1 = new IntegerValue( 127 ); + IntegerValue value2 = new IntegerValue( 128 ); + + assertThat(value1.asByte(), equalTo((byte) 127)); + exception.expect( LossyCoercion.class ); + value2.asByte(); + } + + @Test + public void shouldThrowIfSmallerThanByteMin() + { + IntegerValue value1 = new IntegerValue( -128 ); + IntegerValue value2 = new IntegerValue( -129 ); + + assertThat(value1.asByte(), equalTo((byte) -128)); + exception.expect( LossyCoercion.class ); + value2.asByte(); + } + + @Test + public void shouldThrowIfLargerThanShortMax() + { + IntegerValue value1 = new IntegerValue( Short.MAX_VALUE ); + IntegerValue value2 = new IntegerValue( Short.MAX_VALUE + 1); + + assertThat(value1.asShort(), equalTo(Short.MAX_VALUE)); + exception.expect( LossyCoercion.class ); + value2.asShort(); + } + + @Test + public void shouldThrowIfSmallerThanShortMin() + { + IntegerValue value1 = new IntegerValue( Short.MIN_VALUE ); + IntegerValue value2 = new IntegerValue( Short.MIN_VALUE - 1 ); + + assertThat(value1.asShort(), equalTo(Short.MIN_VALUE)); + exception.expect( LossyCoercion.class ); + value2.asShort(); + } + + @Test + public void shouldThrowIfLargerThanIntegerMax() + { + IntegerValue value1 = new IntegerValue( Integer.MAX_VALUE ); + IntegerValue value2 = new IntegerValue( Integer.MAX_VALUE + 1L); + + assertThat(value1.asInt(), equalTo(Integer.MAX_VALUE)); + exception.expect( LossyCoercion.class ); + value2.asInt(); + } + + @Test + public void shouldThrowIfSmallerThanIntegerMin() + { + IntegerValue value1 = new IntegerValue( Integer.MIN_VALUE ); + IntegerValue value2 = new IntegerValue( Integer.MIN_VALUE - 1L ); + + assertThat(value1.asInt(), equalTo(Integer.MIN_VALUE)); + exception.expect( LossyCoercion.class ); + value2.asInt(); + } + + @Test + public void shouldThrowIfLargerThan() + { + IntegerValue value1 = new IntegerValue( 9007199254740992L); + IntegerValue value2 = new IntegerValue(9007199254740993L ); + + assertThat(value1.asDouble(), equalTo(9007199254740992D)); + exception.expect( LossyCoercion.class ); + value2.asDouble(); + } +} diff --git a/driver/src/test/java/org/neo4j/driver/internal/value/ListValueTest.java b/driver/src/test/java/org/neo4j/driver/internal/value/ListValueTest.java new file mode 100644 index 0000000000..aaf4c9a4d8 --- /dev/null +++ b/driver/src/test/java/org/neo4j/driver/internal/value/ListValueTest.java @@ -0,0 +1,68 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.value; + +import org.junit.Test; + +import org.neo4j.driver.internal.types.InternalTypeSystem; +import org.neo4j.driver.v1.Value; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +import static org.neo4j.driver.v1.Values.value; + +public class ListValueTest +{ + @Test + public void shouldHaveSensibleToString() throws Throwable + { + ListValue listValue = listValue( value( 1 ), value( 2 ), value( 3 ) ); + assertThat( listValue.toString(), equalTo( "[1, 2, 3] :: LIST OF ANY?" ) ); + } + + @Test + public void shouldHaveCorrectType() throws Throwable + { + + ListValue listValue = listValue(); + + assertThat(listValue.type(), equalTo( InternalTypeSystem.TYPE_SYSTEM.LIST() )); + } + + @Test + public void testConversionsFromListValue() throws Throwable + { + ListValue listValue = listValue( value( 1 ), value( 2 ), value( 3 ) ); + + assertThat( listValue.asArray(), equalTo( new Value[]{value( 1 ), value( 2 ), value( 3 )} ) ); + assertThat( listValue.asByteArray(), equalTo( new byte[]{1, 2, 3} ) ); + assertThat( listValue.asDoubleArray(), equalTo( new double[]{1D, 2D, 3D} ) ); + assertThat( listValue.asFloatArray(), equalTo( new float[]{1F, 2F, 3F} ) ); + assertThat( listValue.asIntArray(), equalTo( new int[]{1, 2, 3} ) ); + assertThat( listValue.asLongArray(), equalTo( new long[]{1L, 2L, 3L} ) ); + assertThat( listValue.asShortArray(), equalTo( new short[]{1, 2, 3} ) ); + } + + + private ListValue listValue( Value... values ) + { + return new ListValue( values ); + } +} diff --git a/driver/src/test/java/org/neo4j/driver/internal/value/MapValueTest.java b/driver/src/test/java/org/neo4j/driver/internal/value/MapValueTest.java new file mode 100644 index 0000000000..30eba08015 --- /dev/null +++ b/driver/src/test/java/org/neo4j/driver/internal/value/MapValueTest.java @@ -0,0 +1,74 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.value; + +import java.util.HashMap; + +import org.junit.Test; + +import org.neo4j.driver.internal.types.InternalTypeSystem; +import org.neo4j.driver.v1.Value; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; + +import static org.neo4j.driver.v1.Values.value; + +public class MapValueTest +{ + @Test + public void shouldHaveSensibleToString() throws Throwable + { + MapValue mapValue = mapValue(); + assertThat( mapValue.toString(), equalTo( "{k1: \"v1\", k2: 42} :: MAP" ) ); + } + + @Test + public void shouldHaveCorrectPropertyCount() throws Throwable + { + MapValue mapValue = mapValue(); + assertThat( mapValue.propertyCount(), equalTo( 2 ) ); + } + + @Test + public void shouldHaveCorrectType() throws Throwable + { + + MapValue map = mapValue(); + + assertThat(map.type(), equalTo( InternalTypeSystem.TYPE_SYSTEM.MAP() )); + } + + @Test + public void shouldNotBeNull() throws Throwable + { + MapValue map = mapValue(); + + assertFalse(map.isNull()); + } + + private MapValue mapValue() + { + HashMap map = new HashMap<>(); + map.put( "k1", value( "v1" ) ); + map.put( "k2", value( 42 ) ); + return new MapValue( map ); + } +} diff --git a/driver/src/test/java/org/neo4j/driver/internal/value/NodeValueTest.java b/driver/src/test/java/org/neo4j/driver/internal/value/NodeValueTest.java new file mode 100644 index 0000000000..15f8393486 --- /dev/null +++ b/driver/src/test/java/org/neo4j/driver/internal/value/NodeValueTest.java @@ -0,0 +1,84 @@ +/** + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This file is part of Neo4j. + * + * Licensed 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.neo4j.driver.internal.value; + +import java.util.HashMap; + +import org.junit.Test; + +import org.neo4j.driver.internal.InternalNode; +import org.neo4j.driver.internal.types.InternalTypeSystem; +import org.neo4j.driver.internal.types.TypeConstructor; +import org.neo4j.driver.v1.Value; + +import static java.util.Collections.singletonList; +import static java.util.Collections.singletonMap; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; + +import static org.neo4j.driver.v1.Values.value; + +public class NodeValueTest +{ + @Test + public void shouldHaveSensibleToString() throws Throwable + { + assertEquals( "node<#1234> :: NODE", emptyNodeValue().toString() ); + assertEquals( "node<#1234> :: NODE", filledNodeValue().toString() ); + } + + @Test + public void shouldHaveCorrectPropertyCount() throws Throwable + { + assertEquals( 0, emptyNodeValue().propertyCount()) ; + assertEquals( 1, filledNodeValue().propertyCount()) ; + } + + @Test + public void shouldNotBeNull() + { + assertFalse( emptyNodeValue().isNull() ); + } + + @Test + public void shouldHaveCorrectType() throws Throwable + { + assertThat( emptyNodeValue().type(), equalTo( InternalTypeSystem.TYPE_SYSTEM.NODE() )); + } + + @Test + public void shouldTypeAsNode() + { + InternalValue value = emptyNodeValue(); + assertThat( value.typeConstructor(), equalTo( TypeConstructor.NODE_TyCon ) ); + } + + private NodeValue emptyNodeValue() + { + return new NodeValue( new InternalNode( 1234, singletonList( "User" ), new HashMap() ) ); + } + + private NodeValue filledNodeValue() + { + return new NodeValue( new InternalNode( 1234, singletonList( "User" ), singletonMap( "name", value( "Dodo" ) ) ) ); + } +} diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/value/NullValueTest.java b/driver/src/test/java/org/neo4j/driver/internal/value/NullValueTest.java similarity index 92% rename from driver/src/test/java/org/neo4j/driver/v1/internal/value/NullValueTest.java rename to driver/src/test/java/org/neo4j/driver/internal/value/NullValueTest.java index 48b5544a75..a9aa464ba9 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/value/NullValueTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/value/NullValueTest.java @@ -16,11 +16,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.value; +package org.neo4j.driver.internal.value; import org.junit.Test; -import org.neo4j.driver.v1.internal.types.TypeConstructor; +import org.neo4j.driver.internal.types.TypeConstructor; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/value/NodeValueTest.java b/driver/src/test/java/org/neo4j/driver/internal/value/PathValueTest.java similarity index 61% rename from driver/src/test/java/org/neo4j/driver/v1/internal/value/NodeValueTest.java rename to driver/src/test/java/org/neo4j/driver/internal/value/PathValueTest.java index a39bc0d48b..512161279b 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/value/NodeValueTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/value/PathValueTest.java @@ -16,47 +16,46 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.value; - -import java.util.HashMap; +package org.neo4j.driver.internal.value; import org.junit.Test; +import org.neo4j.driver.internal.InternalNode; +import org.neo4j.driver.internal.InternalPath; +import org.neo4j.driver.internal.InternalRelationship; +import org.neo4j.driver.internal.types.InternalTypeSystem; import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.SimpleNode; -import org.neo4j.driver.v1.internal.types.TypeConstructor; - -import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; -public class NodeValueTest +public class PathValueTest { @Test public void shouldHaveSensibleToString() throws Throwable { - assertEquals("node<#1234>", nodeValue().toString()); - } - - private NodeValue nodeValue() - { - return new NodeValue( new SimpleNode( 1234, singletonList( "User" ), new HashMap() ) ); + assertEquals("path[[(#42)-[#43:T]->(#44)]] :: PATH", pathValue().toString()); } @Test public void shouldNotBeNull() { - Value value = nodeValue(); + Value value = pathValue(); assertFalse( value.isNull() ); } + @Test - public void shouldTypeAsNode() + public void shouldHaveCorrectType() throws Throwable + { + + assertThat(pathValue().type(), equalTo( InternalTypeSystem.TYPE_SYSTEM.PATH() )); + } + + private PathValue pathValue() { - InternalValue value = nodeValue(); - assertThat( value.typeConstructor(), equalTo( TypeConstructor.NODE_TyCon ) ); + return new PathValue( new InternalPath( new InternalNode(42L), new InternalRelationship( 43L, 42L, 44L, "T" ), new InternalNode( 44L ) ) ); } } diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/value/RelationshipValueTest.java b/driver/src/test/java/org/neo4j/driver/internal/value/RelationshipValueTest.java similarity index 54% rename from driver/src/test/java/org/neo4j/driver/v1/internal/value/RelationshipValueTest.java rename to driver/src/test/java/org/neo4j/driver/internal/value/RelationshipValueTest.java index 760d2839ab..56a541f6a8 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/value/RelationshipValueTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/value/RelationshipValueTest.java @@ -16,43 +16,60 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.value; +package org.neo4j.driver.internal.value; import org.junit.Test; +import org.neo4j.driver.internal.InternalRelationship; +import org.neo4j.driver.internal.types.TypeConstructor; import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.SimpleRelationship; -import org.neo4j.driver.v1.internal.types.TypeConstructor; + +import static java.util.Collections.singletonMap; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; +import static org.neo4j.driver.v1.Values.value; + public class RelationshipValueTest { @Test public void shouldHaveSensibleToString() throws Throwable { - assertEquals( "relationship<#1234>", relationshipValue().toString() ); + assertEquals( "relationship<#1234> :: RELATIONSHIP", emptyRelationshipValue().toString() ); + assertEquals( "relationship<#1234> :: RELATIONSHIP", filledRelationshipValue().toString() ); + } + + @Test + public void shouldHaveCorrectPropertyCount() throws Throwable + { + assertEquals( 0, emptyRelationshipValue().propertyCount()) ; + assertEquals( 1, filledRelationshipValue().propertyCount()) ; } @Test public void shouldNotBeNull() { - Value value = relationshipValue(); + Value value = emptyRelationshipValue(); assertFalse( value.isNull() ); } @Test public void shouldTypeAsRelationship() { - InternalValue value = relationshipValue(); + InternalValue value = emptyRelationshipValue(); assertThat( value.typeConstructor(), equalTo( TypeConstructor.RELATIONSHIP_TyCon ) ); } - private RelationshipValue relationshipValue() + private RelationshipValue emptyRelationshipValue() + { + return new RelationshipValue( new InternalRelationship( 1234, 1, 2, "KNOWS" ) ); + } + + private RelationshipValue filledRelationshipValue() { - return new RelationshipValue( new SimpleRelationship( 1234, 1, 2, "KNOWS" ) ); + return new RelationshipValue( new InternalRelationship( 1234, 1, 2, "KNOWS", singletonMap( "name", value( "Dodo" ) ) ) ); } } diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/value/StringValueTest.java b/driver/src/test/java/org/neo4j/driver/internal/value/StringValueTest.java similarity index 54% rename from driver/src/test/java/org/neo4j/driver/v1/internal/value/StringValueTest.java rename to driver/src/test/java/org/neo4j/driver/internal/value/StringValueTest.java index 93c0b920a5..c74ea91e82 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/value/StringValueTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/value/StringValueTest.java @@ -16,20 +16,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.neo4j.driver.v1.internal.value; +package org.neo4j.driver.internal.value; import org.junit.Test; +import org.neo4j.driver.internal.types.InternalTypeSystem; +import org.neo4j.driver.internal.types.TypeConstructor; +import org.neo4j.driver.v1.TypeSystem; import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.types.TypeConstructor; +import org.neo4j.driver.v1.exceptions.value.Unrepresentable; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; public class StringValueTest { + TypeSystem typeSystem = InternalTypeSystem.TYPE_SYSTEM; + @Test public void testStringValue() throws Exception { @@ -37,8 +43,53 @@ public void testStringValue() throws Exception StringValue value = new StringValue( "Spongebob" ); // Then - assertThat( value.javaBoolean(), equalTo( true ) ); - assertThat( value.javaString(), equalTo( "Spongebob" ) ); + assertThat( value.asString(), equalTo( "Spongebob" ) ); + } + + @Test + public void testCharValue() throws Exception + { + // Given + StringValue value = new StringValue( "S" ); + + // Then + assertThat( value.asChar(), equalTo( 'S' ) ); + } + + @Test + public void testLargeNonCharValue() throws Exception + { + // Given + StringValue value = new StringValue( "NOT A CHAR" ); + + // Then + try + { + value.asChar(); + } + catch ( Unrepresentable e ) + { + return; + } + fail( "Expected Unrepresentable to be thrown"); + } + + @Test + public void testEmptyNonCharValue() throws Exception + { + // Given + StringValue value = new StringValue( "" ); + + // Then + try + { + value.asChar(); + } + catch ( Unrepresentable e ) + { + return; + } + fail( "Expected Unrepresentable to be thrown" ); } @Test @@ -48,7 +99,7 @@ public void testIsString() throws Exception StringValue value = new StringValue( "Spongebob" ); // Then - assertThat( value.isString(), equalTo( true ) ); + assertThat( typeSystem.STRING().isTypeOf( value ), equalTo( true ) ); } @Test @@ -85,4 +136,18 @@ public void shouldTypeAsString() InternalValue value = new StringValue( "Spongebob" ); assertThat( value.typeConstructor(), equalTo( TypeConstructor.STRING_TyCon ) ); } + + @Test + public void shouldHaveStringType() + { + InternalValue value = new StringValue( "Spongebob" ); + assertThat( value.type(), equalTo( InternalTypeSystem.TYPE_SYSTEM.STRING() ) ); + } + + @Test + public void testAsCharArray() + { + InternalValue value = new StringValue( "Spongebob" ); + assertThat( value.asCharArray(), equalTo( new char[]{'S', 'p', 'o', 'n', 'g', 'e', 'b', 'o', 'b'} ) ); + } } diff --git a/driver/src/test/java/org/neo4j/driver/v1/DriverDocIT.java b/driver/src/test/java/org/neo4j/driver/v1/DriverDocIT.java index 8d92acdd10..8bcb847368 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/DriverDocIT.java +++ b/driver/src/test/java/org/neo4j/driver/v1/DriverDocIT.java @@ -18,20 +18,22 @@ */ package org.neo4j.driver.v1; +import java.util.LinkedList; +import java.util.List; + import javadoctest.DocSnippet; import javadoctest.DocTestRunner; import org.junit.Rule; import org.junit.runner.RunWith; -import java.util.LinkedList; -import java.util.List; - import org.neo4j.driver.v1.util.TestNeo4jSession; import static java.util.Arrays.asList; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; @RunWith( DocTestRunner.class ) public class DriverDocIT @@ -40,6 +42,7 @@ public class DriverDocIT public TestNeo4jSession session = new TestNeo4jSession(); /** @see Driver */ + @SuppressWarnings("unchecked") public void exampleUsage( DocSnippet snippet ) { // given @@ -50,7 +53,9 @@ public void exampleUsage( DocSnippet snippet ) snippet.run(); // then it should've created a bunch of data - assertEquals( 3, session.run( "MATCH (n) RETURN count(n)" ).single().get( 0 ).javaInteger() ); + Result result = session.run( "MATCH (n) RETURN count(n)" ); + assertTrue( result.single() ); + assertEquals( 3, result.value( 0 ).asInt() ); assertThat( (List)snippet.get( "names" ), equalTo( asList("Bob", "Alice", "Tina")) ); } } diff --git a/driver/src/test/java/org/neo4j/driver/v1/StatementRunnerDocIT.java b/driver/src/test/java/org/neo4j/driver/v1/StatementRunnerDocIT.java index 162803d8a9..128485fcc3 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/StatementRunnerDocIT.java +++ b/driver/src/test/java/org/neo4j/driver/v1/StatementRunnerDocIT.java @@ -43,7 +43,7 @@ public void parameterTest( DocSnippet snippet ) snippet.run(); // then - assertThat( snippet.get( "res" ), notNullValue() ); + assertThat( snippet.get( "cursor" ), notNullValue() ); } public void statementObjectTest( DocSnippet snippet ) @@ -55,6 +55,6 @@ public void statementObjectTest( DocSnippet snippet ) snippet.run(); // then - assertThat( snippet.get( "res" ), notNullValue() ); + assertThat( snippet.get( "cursor" ), notNullValue() ); } } diff --git a/driver/src/test/java/org/neo4j/driver/v1/StatementTest.java b/driver/src/test/java/org/neo4j/driver/v1/StatementTest.java index 149008a2a4..a62765b045 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/StatementTest.java +++ b/driver/src/test/java/org/neo4j/driver/v1/StatementTest.java @@ -25,8 +25,8 @@ import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; +import static org.neo4j.driver.internal.ParameterSupport.NO_PARAMETERS; import static org.neo4j.driver.v1.Values.parameters; -import static org.neo4j.driver.v1.internal.ParameterSupport.NO_PARAMETERS; public class StatementTest { @@ -40,7 +40,7 @@ public void shouldConstructStatementWithParameters() Statement statement = new Statement( text, NO_PARAMETERS ); // then - assertThat( statement.text(), equalTo( text ) ); + assertThat( statement.template(), equalTo( text ) ); assertThat( statement.parameters(), equalTo( NO_PARAMETERS ) ); } @@ -54,7 +54,7 @@ public void shouldConstructStatementWithNoParameters() Statement statement = new Statement( text ); // then - assertThat( statement.text(), equalTo( text ) ); + assertThat( statement.template(), equalTo( text ) ); assertThat( statement.parameters(), equalTo( NO_PARAMETERS ) ); } @@ -68,7 +68,7 @@ public void shouldConstructStatementWithNullParameters() Statement statement = new Statement( text, null ); // then - assertThat( statement.text(), equalTo( text ) ); + assertThat( statement.template(), equalTo( text ) ); assertThat( statement.parameters(), equalTo( NO_PARAMETERS ) ); } @@ -79,10 +79,10 @@ public void shouldUpdateStatementText() // when Statement statement = new Statement( "MATCH (n) RETURN n" ) - .withText( "BOO" ); + .withTemplate( "BOO" ); // then - assertThat( statement.text(), equalTo( "BOO" ) ); + assertThat( statement.template(), equalTo( "BOO" ) ); assertThat( statement.parameters(), equalTo( NO_PARAMETERS ) ); } @@ -96,7 +96,7 @@ public void shouldReplaceStatementParameters() Statement statement = new Statement( "MATCH (n) RETURN n" ).withParameters( initialParameters ); // then - assertThat( statement.text(), equalTo( text ) ); + assertThat( statement.template(), equalTo( text ) ); assertThat( statement.parameters(), equalTo( initialParameters ) ); } @@ -112,7 +112,7 @@ public void shouldUpdateStatementParameters() .withUpdatedParameters( parameters( "a", 0, "b", Values.NULL ) ); // then - assertThat( statement.text(), equalTo( text ) ); + assertThat( statement.template(), equalTo( text ) ); assertThat( statement.parameters(), equalTo( parameters( "a", 0, "c", 3 ) ) ); } } diff --git a/driver/src/test/java/org/neo4j/driver/v1/TransactionDocIT.java b/driver/src/test/java/org/neo4j/driver/v1/TransactionDocIT.java index 984ff448bb..60eac5f4b7 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/TransactionDocIT.java +++ b/driver/src/test/java/org/neo4j/driver/v1/TransactionDocIT.java @@ -26,6 +26,7 @@ import org.neo4j.driver.v1.util.TestNeo4jSession; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; @RunWith( DocTestRunner.class ) public class TransactionDocIT @@ -43,7 +44,9 @@ public void classDoc( DocSnippet snippet ) snippet.run(); // Then a node should've been created - assertEquals( 1, session.run( "MATCH (n) RETURN count(n)" ).single().get( "count(n)" ).javaInteger() ); + Result cursor = session.run( "MATCH (n) RETURN count(n)" ); + assertTrue( cursor.single() ); + assertEquals( 1, cursor.value( "count(n)" ).asInt() ); } /** @see Transaction#failure() */ @@ -56,6 +59,8 @@ public void failure( DocSnippet snippet ) snippet.run(); // Then a node should've been created - assertEquals( 0, session.run( "MATCH (n) RETURN count(n)" ).single().get( "count(n)" ).javaInteger() ); + Result cursor = session.run( "MATCH (n) RETURN count(n)" ); + assertTrue( cursor.single() ); + assertEquals( 0, cursor.value( "count(n)" ).asInt() ); } } diff --git a/driver/src/test/java/org/neo4j/driver/v1/TypeSystemTest.java b/driver/src/test/java/org/neo4j/driver/v1/TypeSystemTest.java index d4399617d6..e6e6c6cc7e 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/TypeSystemTest.java +++ b/driver/src/test/java/org/neo4j/driver/v1/TypeSystemTest.java @@ -18,32 +18,33 @@ */ package org.neo4j.driver.v1; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.junit.Test; - import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; -import org.neo4j.driver.v1.internal.SimpleIdentity; -import org.neo4j.driver.v1.internal.SimpleNode; -import org.neo4j.driver.v1.internal.SimplePath; -import org.neo4j.driver.v1.internal.SimpleRelationship; -import org.neo4j.driver.v1.internal.types.StandardTypeSystem; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.junit.Test; + +import org.neo4j.driver.internal.InternalIdentity; +import org.neo4j.driver.internal.InternalNode; +import org.neo4j.driver.internal.InternalPath; +import org.neo4j.driver.internal.InternalRelationship; +import org.neo4j.driver.internal.types.InternalTypeSystem; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; + +import static org.neo4j.driver.internal.types.InternalTypeSystem.TYPE_SYSTEM; import static org.neo4j.driver.v1.Values.value; -import static org.neo4j.driver.v1.internal.types.StandardTypeSystem.TYPE_SYSTEM; public class TypeSystemTest { - private final SimpleNode node = new SimpleNode( 42L ); - private final SimpleRelationship relationship = new SimpleRelationship( 42L, 42L, 43L, "T" ); + private final InternalNode node = new InternalNode( 42L ); + private final InternalRelationship relationship = new InternalRelationship( 42L, 42L, 43L, "T" ); private Value integerValue = value( 13 ); private Value floatValue = value( 13.1 ); @@ -51,13 +52,13 @@ public class TypeSystemTest private Value nodeValue = value( node ); private Value relationshipValue = value( relationship ); private Value mapValue = value( Collections.singletonMap( "type", "r" ) ); - private Value pathValue = value( new SimplePath( Arrays.asList( node, relationship, node ) ) ); + private Value pathValue = value( new InternalPath( Arrays.asList( node, relationship, node ) ) ); private Value booleanValue = value( true ); private Value listValue = value( Arrays.asList( 1, 2, 3 ) ); private Value nullValue = value( (Object) null ); - private Value identityValue = value( new SimpleIdentity( 42L ) ); + private Value identityValue = value( new InternalIdentity( 42L ) ); - private StandardTypeSystem typeSystem = TYPE_SYSTEM; + private InternalTypeSystem typeSystem = TYPE_SYSTEM; TypeVerifier newTypeVerifierFor( Type type ) { diff --git a/driver/src/test/java/org/neo4j/driver/v1/integration/EntityTypeIT.java b/driver/src/test/java/org/neo4j/driver/v1/integration/EntityTypeIT.java index 0363a22d46..b58c1703fa 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/integration/EntityTypeIT.java +++ b/driver/src/test/java/org/neo4j/driver/v1/integration/EntityTypeIT.java @@ -24,6 +24,7 @@ import org.neo4j.driver.v1.Node; import org.neo4j.driver.v1.Path; import org.neo4j.driver.v1.Relationship; +import org.neo4j.driver.v1.Result; import org.neo4j.driver.v1.util.TestNeo4jSession; import static org.junit.Assert.assertTrue; @@ -37,7 +38,9 @@ public class EntityTypeIT public void shouldReturnIdentitiesOfNodes() throws Throwable { // When - Node node = session.run( "CREATE (n) RETURN n" ).single().get( "n" ).asNode(); + Result cursor = session.run( "CREATE (n) RETURN n" ); + assertTrue( cursor.single() ); + Node node = cursor.value( "n" ).asNode(); // Then assertTrue( node.identity().toString(), node.identity().toString().matches( "#\\d+" ) ); @@ -47,7 +50,9 @@ public void shouldReturnIdentitiesOfNodes() throws Throwable public void shouldReturnIdentitiesOfRelationships() throws Throwable { // When - Relationship rel = session.run( "CREATE ()-[r:T]->() RETURN r" ).single().get( "r" ).asRelationship(); + Result cursor = session.run( "CREATE ()-[r:T]->() RETURN r" ); + assertTrue( cursor.single() ); + Relationship rel = cursor.value( "r" ).asRelationship(); // Then assertTrue( rel.start().toString(), rel.start().toString().matches( "#\\d+" ) ); @@ -59,7 +64,9 @@ public void shouldReturnIdentitiesOfRelationships() throws Throwable public void shouldReturnIdentitiesOfPaths() throws Throwable { // When - Path path = session.run( "CREATE p=()-[r:T]->() RETURN p" ).single().get( "p" ).asPath(); + Result cursor = session.run( "CREATE p=()-[r:T]->() RETURN p" ); + assertTrue( cursor.single() ); + Path path = cursor.value( "p" ).asPath(); // Then assertTrue( path.start().identity().toString(), path.start().identity().toString().matches( "#\\d+" ) ); diff --git a/driver/src/test/java/org/neo4j/driver/v1/integration/ErrorIT.java b/driver/src/test/java/org/neo4j/driver/v1/integration/ErrorIT.java index e7e4a2081c..cbc53ba516 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/integration/ErrorIT.java +++ b/driver/src/test/java/org/neo4j/driver/v1/integration/ErrorIT.java @@ -24,12 +24,14 @@ import org.neo4j.driver.v1.Driver; import org.neo4j.driver.v1.GraphDatabase; +import org.neo4j.driver.v1.Result; import org.neo4j.driver.v1.Transaction; import org.neo4j.driver.v1.exceptions.ClientException; import org.neo4j.driver.v1.util.TestNeo4jSession; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertTrue; public class ErrorIT { @@ -67,7 +69,9 @@ public void shouldNotAllowMoreTxAfterClientException() throws Throwable "because previous statements in the" ); // When - tx.run( "RETURN 1" ).single().get( "1" ).javaInteger(); + Result cursor = tx.run( "RETURN 1" ); + assertTrue( cursor.single() ); + cursor.value( "1" ).asInt(); } @Test @@ -77,7 +81,9 @@ public void shouldAllowNewStatementAfterRecoverableError() throws Throwable try { session.run( "invalid" ); } catch ( ClientException e ) {} // When - int val = session.run( "RETURN 1" ).single().get( "1" ).javaInteger(); + Result cursor = session.run( "RETURN 1" ); + assertTrue( cursor.single() ); + int val = cursor.value( "1" ).asInt(); // Then assertThat( val, equalTo( 1 ) ); @@ -96,7 +102,9 @@ public void shouldAllowNewTransactionAfterRecoverableError() throws Throwable // When try ( Transaction tx = session.beginTransaction() ) { - int val = tx.run( "RETURN 1" ).single().get( "1" ).javaInteger(); + Result cursor = tx.run( "RETURN 1" ); + assertTrue( cursor.single() ); + int val = cursor.value( "1" ).asInt(); // Then assertThat( val, equalTo( 1 ) ); diff --git a/driver/src/test/java/org/neo4j/driver/v1/integration/LoadCSVIT.java b/driver/src/test/java/org/neo4j/driver/v1/integration/LoadCSVIT.java index 3d046dc59d..8a7cc03599 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/integration/LoadCSVIT.java +++ b/driver/src/test/java/org/neo4j/driver/v1/integration/LoadCSVIT.java @@ -18,11 +18,11 @@ */ package org.neo4j.driver.v1.integration; +import java.io.IOException; + import org.junit.Rule; import org.junit.Test; -import java.io.IOException; - import org.neo4j.driver.v1.Driver; import org.neo4j.driver.v1.GraphDatabase; import org.neo4j.driver.v1.Result; @@ -33,6 +33,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; + import static org.neo4j.driver.v1.Values.parameters; public class LoadCSVIT @@ -61,7 +62,7 @@ public void shouldLoadCSV() throws Throwable // Then assertTrue( result.next() ); - assertThat( result.get( "c" ).javaInteger(), equalTo( 150 ) ); + assertThat( result.value( "c" ).asInt(), equalTo( 150 ) ); assertFalse( result.next() ); } diff --git a/driver/src/test/java/org/neo4j/driver/v1/integration/LoggingIT.java b/driver/src/test/java/org/neo4j/driver/v1/integration/LoggingIT.java index fe2172ad33..151731f71a 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/integration/LoggingIT.java +++ b/driver/src/test/java/org/neo4j/driver/v1/integration/LoggingIT.java @@ -18,17 +18,17 @@ */ package org.neo4j.driver.v1.integration; +import java.net.URI; + import org.junit.Rule; import org.junit.Test; -import java.net.URI; - -import org.neo4j.driver.v1.GraphDatabase; +import org.neo4j.driver.internal.spi.Logger; +import org.neo4j.driver.internal.spi.Logging; import org.neo4j.driver.v1.Config; import org.neo4j.driver.v1.Driver; +import org.neo4j.driver.v1.GraphDatabase; import org.neo4j.driver.v1.Session; -import org.neo4j.driver.v1.internal.spi.Logger; -import org.neo4j.driver.v1.internal.spi.Logging; import org.neo4j.driver.v1.util.Neo4jRunner; import org.neo4j.driver.v1.util.TestNeo4j; diff --git a/driver/src/test/java/org/neo4j/driver/v1/integration/ParametersIT.java b/driver/src/test/java/org/neo4j/driver/v1/integration/ParametersIT.java index a51aa761cd..2e1ba7e533 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/integration/ParametersIT.java +++ b/driver/src/test/java/org/neo4j/driver/v1/integration/ParametersIT.java @@ -30,6 +30,7 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; + import static org.neo4j.driver.v1.Values.parameters; public class ParametersIT @@ -50,9 +51,9 @@ public void shouldBeAbleToSetAndReturnBooleanProperty() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isBoolean(), equalTo( true ) ); - assertThat( value.javaBoolean(), equalTo( true ) ); + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().BOOLEAN() ), equalTo( true ) ); + assertThat( value.asBoolean(), equalTo( true ) ); } } @@ -66,11 +67,10 @@ public void shouldBeAbleToSetAndReturnByteProperty() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isInteger(), equalTo( true ) ); - assertThat( value.javaLong(), equalTo( 1L ) ); + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().INTEGER() ), equalTo( true ) ); + assertThat( value.asLong(), equalTo( 1L ) ); } - } @Test @@ -83,11 +83,10 @@ public void shouldBeAbleToSetAndReturnShortProperty() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isInteger(), equalTo( true ) ); - assertThat( value.javaLong(), equalTo( 1L ) ); + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().INTEGER() ), equalTo( true ) ); + assertThat( value.asLong(), equalTo( 1L ) ); } - } @Test @@ -100,9 +99,9 @@ public void shouldBeAbleToSetAndReturnIntegerProperty() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isInteger(), equalTo( true ) ); - assertThat( value.javaLong(), equalTo( 1L ) ); + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().INTEGER() ), equalTo( true ) ); + assertThat( value.asLong(), equalTo( 1L ) ); } } @@ -117,9 +116,9 @@ public void shouldBeAbleToSetAndReturnLongProperty() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isInteger(), equalTo( true ) ); - assertThat( value.javaLong(), equalTo( 1L ) ); + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().INTEGER() ), equalTo( true ) ); + assertThat( value.asLong(), equalTo( 1L ) ); } } @@ -134,9 +133,9 @@ public void shouldBeAbleToSetAndReturnDoubleProperty() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isFloat(), equalTo( true ) ); - assertThat( value.javaDouble(), equalTo( 6.28 ) ); + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().FLOAT() ), equalTo( true ) ); + assertThat( value.asDouble(), equalTo( 6.28 ) ); } } @@ -151,9 +150,9 @@ public void shouldBeAbleToSetAndReturnCharacterProperty() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isString(), equalTo( true ) ); - assertThat( value.javaString(), equalTo( "ö" ) ); + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().STRING() ), equalTo( true ) ); + assertThat( value.asString(), equalTo( "ö" ) ); } } @@ -169,9 +168,9 @@ public void shouldBeAbleToSetAndReturnCharacterArrayProperty() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isString(), equalTo( true ) ); - assertThat( value.javaString(), equalTo( "Mjölnir" ) ); + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().STRING() ), equalTo( true ) ); + assertThat( value.asString(), equalTo( "Mjölnir" ) ); } } @@ -186,9 +185,9 @@ public void shouldBeAbleToSetAndReturnStringProperty() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isString(), equalTo( true ) ); - assertThat( value.javaString(), equalTo( "Mjölnir" ) ); + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().STRING() ), equalTo( true ) ); + assertThat( value.asString(), equalTo( "Mjölnir" ) ); } } @@ -204,13 +203,13 @@ public void shouldBeAbleToSetAndReturnBooleanArrayProperty() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isList(), equalTo( true ) ); - assertThat( value.size(), equalTo( 3L ) ); - for ( Value item : value ) + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().LIST() ), equalTo( true ) ); + assertThat( value.size(), equalTo( 3 ) ); + for ( Value item : value.asList() ) { - assertThat( item.isBoolean(), equalTo( true ) ); - assertThat( item.javaBoolean(), equalTo( true ) ); + assertThat( item.hasType( session.typeSystem().BOOLEAN() ), equalTo( true ) ); + assertThat( item.asBoolean(), equalTo( true ) ); } } @@ -227,13 +226,13 @@ public void shouldBeAbleToSetAndReturnIntegerArrayProperty() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isList(), equalTo( true ) ); - assertThat( value.size(), equalTo( 3L ) ); - for ( Value item : value ) + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().LIST() ), equalTo( true ) ); + assertThat( value.size(), equalTo( 3 ) ); + for ( Value item : value.asList() ) { - assertThat( item.isInteger(), equalTo( true ) ); - assertThat( item.javaLong(), equalTo( 42L ) ); + assertThat( item.hasType( session.typeSystem().INTEGER() ), equalTo( true ) ); + assertThat( item.asLong(), equalTo( 42L ) ); } } @@ -250,13 +249,13 @@ public void shouldBeAbleToSetAndReturnDoubleArrayProperty() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isList(), equalTo( true ) ); - assertThat( value.size(), equalTo( 3L ) ); - for ( Value item : value ) + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().LIST() ), equalTo( true ) ); + assertThat( value.size(), equalTo( 3 ) ); + for ( Value item : value.asList() ) { - assertThat( item.isFloat(), equalTo( true ) ); - assertThat( item.javaDouble(), equalTo( 6.28 ) ); + assertThat( item.hasType( session.typeSystem().FLOAT() ), equalTo( true ) ); + assertThat( item.asDouble(), equalTo( 6.28 ) ); } } } @@ -273,13 +272,13 @@ public void shouldBeAbleToSetAndReturnSpecialStringArrayProperty() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isList(), equalTo( true ) ); - assertThat( value.size(), equalTo( 3L ) ); - for ( Value item : value ) + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().LIST() ), equalTo( true ) ); + assertThat( value.size(), equalTo( 3 ) ); + for ( Value item : value.asList() ) { - assertThat( item.isString(), equalTo( true ) ); - assertThat( item.javaString(), equalTo( "Mjölnir" ) ); + assertThat( item.hasType( session.typeSystem().STRING() ), equalTo( true ) ); + assertThat( item.asString(), equalTo( "Mjölnir" ) ); } } } @@ -295,13 +294,13 @@ public void shouldBeAbleToSetAndReturnStringArrayProperty() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isList(), equalTo( true ) ); - assertThat( value.size(), equalTo( 3L ) ); - for ( Value item : value ) + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().LIST() ), equalTo( true ) ); + assertThat( value.size(), equalTo( 3 ) ); + for ( Value item : value.asList() ) { - assertThat( item.isString(), equalTo( true ) ); - assertThat( item.javaString(), equalTo( "cat" ) ); + assertThat( item.hasType( session.typeSystem().STRING() ), equalTo( true ) ); + assertThat( item.asString(), equalTo( "cat" ) ); } } @@ -318,9 +317,9 @@ public void shouldBeAbleToSetAndReturnBooleanPropertyWithinMap() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isBoolean(), equalTo( true ) ); - assertThat( value.javaBoolean(), equalTo( true ) ); + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().BOOLEAN() ), equalTo( true ) ); + assertThat( value.asBoolean(), equalTo( true ) ); } } @@ -336,9 +335,9 @@ public void shouldBeAbleToSetAndReturnIntegerPropertyWithinMap() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isInteger(), equalTo( true ) ); - assertThat( value.javaLong(), equalTo( 42L ) ); + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().INTEGER() ), equalTo( true ) ); + assertThat( value.asLong(), equalTo( 42L ) ); } } @@ -354,9 +353,9 @@ public void shouldBeAbleToSetAndReturnDoublePropertyWithinMap() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isFloat(), equalTo( true ) ); - assertThat( value.javaDouble(), equalTo( 6.28 ) ); + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().FLOAT() ), equalTo( true ) ); + assertThat( value.asDouble(), equalTo( 6.28 ) ); } } @@ -372,9 +371,9 @@ public void shouldBeAbleToSetAndReturnStringPropertyWithinMap() // Then for ( Record record : result.retain() ) { - Value value = record.get( "a.value" ); - assertThat( value.isString(), equalTo( true ) ); - assertThat( value.javaString(), equalTo( "Mjölnir" ) ); + Value value = record.value( "a.value" ); + assertThat( value.hasType( session.typeSystem().STRING() ), equalTo( true ) ); + assertThat( value.asString(), equalTo( "Mjölnir" ) ); } } diff --git a/driver/src/test/java/org/neo4j/driver/v1/integration/ResultStreamIT.java b/driver/src/test/java/org/neo4j/driver/v1/integration/ResultStreamIT.java index dfd61461c7..d55b5ea5eb 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/integration/ResultStreamIT.java +++ b/driver/src/test/java/org/neo4j/driver/v1/integration/ResultStreamIT.java @@ -22,13 +22,13 @@ import org.junit.Test; import org.neo4j.driver.v1.Result; -import org.neo4j.driver.v1.Value; import org.neo4j.driver.v1.exceptions.ClientException; import org.neo4j.driver.v1.util.TestNeo4jSession; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; + import static org.neo4j.driver.v1.Values.parameters; public class ResultStreamIT @@ -46,7 +46,7 @@ public void shouldAllowIteratingOverResultStream() throws Throwable int idx = 1; while ( res.next() ) { - assertEquals( idx++, res.get( "a" ).javaLong() ); + assertEquals( idx++, res.value( "a" ).asLong() ); } } @@ -57,8 +57,9 @@ public void shouldHaveFieldNamesInResult() Result res = session.run( "CREATE (n:TestNode {name:'test'}) RETURN n" ); // Then - assertEquals( "[n]", res.fieldNames().toString() ); - assertEquals( "[n]", res.single().fieldNames().toString() ); + assertEquals( "[n]", res.keys().toString() ); + assertTrue( res.single() ); + assertEquals( "[n]", res.keys().toString() ); } @Test @@ -70,7 +71,7 @@ public void shouldGiveHelpfulFailureMessageWhenCurrentRecordHasNotBeenSet() thro // When & Then try { - rs.get( "n" ); + rs.value( "n" ); fail( "The test should fail with a proper message to indicate `next` method should be called first" ); } catch( ClientException e ) @@ -90,10 +91,10 @@ public void shouldGiveHelpfulFailureMessageWhenAccessNonExistingField() throws T Result rs = session.run( "CREATE (n:Person {name:{name}}) RETURN n", parameters( "name", "Tom Hanks" ) ); // When - Value m = rs.single().get( "m" ); + assertTrue( rs.single() ); // Then - assertNull( m ); + assertTrue( rs.value( "m" ).isNull() ); } @Test @@ -103,10 +104,9 @@ public void shouldGiveHelpfulFailureMessageWhenAccessNonExistingPropertyOnNode() Result rs = session.run( "CREATE (n:Person {name:{name}}) RETURN n", parameters( "name", "Tom Hanks" ) ); // When - Value n = rs.single().get( "n" ); - Value age = n.get( "age" ); + assertTrue( rs.single() ); // Then - assertNull( age ); + assertTrue( rs.value( "n" ).value( "age" ).isNull() ); } } diff --git a/driver/src/test/java/org/neo4j/driver/v1/integration/SSLSocketChannelIT.java b/driver/src/test/java/org/neo4j/driver/v1/integration/SSLSocketChannelIT.java index d531247df0..f0f29509c3 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/integration/SSLSocketChannelIT.java +++ b/driver/src/test/java/org/neo4j/driver/v1/integration/SSLSocketChannelIT.java @@ -34,14 +34,14 @@ import org.junit.Rule; import org.junit.Test; +import org.neo4j.driver.internal.ConfigTest; +import org.neo4j.driver.internal.connector.socket.SSLSocketChannel; +import org.neo4j.driver.internal.spi.Logger; +import org.neo4j.driver.internal.util.CertificateTool; import org.neo4j.driver.v1.Config; import org.neo4j.driver.v1.Driver; import org.neo4j.driver.v1.GraphDatabase; import org.neo4j.driver.v1.Result; -import org.neo4j.driver.v1.internal.ConfigTest; -import org.neo4j.driver.v1.internal.connector.socket.SSLSocketChannel; -import org.neo4j.driver.v1.internal.spi.Logger; -import org.neo4j.driver.v1.internal.util.CertificateTool; import org.neo4j.driver.v1.util.CertificateToolTest; import org.neo4j.driver.v1.util.Neo4jRunner; import org.neo4j.driver.v1.util.Neo4jSettings; @@ -230,7 +230,7 @@ public void shouldEstablishTLSConnection() throws Throwable Result result = driver.session().run( "RETURN 1" ); assertTrue( result.next() ); - assertEquals( 1, result.get( 0 ).javaInteger() ); + assertEquals( 1, result.value( 0 ).asInt() ); assertFalse( result.next() ); driver.close(); diff --git a/driver/src/test/java/org/neo4j/driver/v1/integration/ScalarTypeIT.java b/driver/src/test/java/org/neo4j/driver/v1/integration/ScalarTypeIT.java index 903eb7d383..b25f2149ef 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/integration/ScalarTypeIT.java +++ b/driver/src/test/java/org/neo4j/driver/v1/integration/ScalarTypeIT.java @@ -18,25 +18,25 @@ */ package org.neo4j.driver.v1.integration; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; - +import org.neo4j.driver.internal.value.ListValue; +import org.neo4j.driver.internal.value.MapValue; +import org.neo4j.driver.v1.Result; import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.value.ListValue; -import org.neo4j.driver.v1.internal.value.MapValue; -import org.neo4j.driver.v1.util.TestNeo4jSession; import org.neo4j.driver.v1.Values; +import org.neo4j.driver.v1.util.TestNeo4jSession; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; - -import static org.neo4j.driver.v1.Values.value; +import static org.junit.Assert.assertTrue; @RunWith(Parameterized.class) public class ScalarTypeIT @@ -71,9 +71,10 @@ public static Collection typesToTest() public void shouldHandleType() throws Throwable { // When - Value value = session.run( statement ).single().get( "v" ); + Result cursor = session.run( statement ); // Then - assertThat( value, equalTo( expectedValue ) ); + assertTrue( cursor.next() ); + assertThat( cursor.value( "v" ), equalTo( expectedValue ) ); } } diff --git a/driver/src/test/java/org/neo4j/driver/v1/integration/ServerKilledIT.java b/driver/src/test/java/org/neo4j/driver/v1/integration/ServerKilledIT.java index d0a3bfafa5..83a6c17a26 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/integration/ServerKilledIT.java +++ b/driver/src/test/java/org/neo4j/driver/v1/integration/ServerKilledIT.java @@ -64,7 +64,7 @@ public void shouldRecoverFromServerRestart() throws Throwable neo4j.restartServerOnEmptyDatabase(); // Then we should be able to start using sessions again, at most O(numSessions) session calls later - // TODO: These should get evicted immediately, not show up as application-loggingLevel errors first + // TODO: These should value evicted immediately, not show up as application-loggingLevel errors first int toleratedFailures = 4; for ( int i = 0; i < 10; i++ ) { diff --git a/driver/src/test/java/org/neo4j/driver/v1/integration/StatementIT.java b/driver/src/test/java/org/neo4j/driver/v1/integration/StatementIT.java index 375fed7542..ea36ef2e60 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/integration/StatementIT.java +++ b/driver/src/test/java/org/neo4j/driver/v1/integration/StatementIT.java @@ -18,19 +18,22 @@ */ package org.neo4j.driver.v1.integration; +import java.util.List; + import org.junit.Rule; import org.junit.Test; import org.neo4j.driver.v1.Record; import org.neo4j.driver.v1.Result; -import org.neo4j.driver.v1.ReusableResult; import org.neo4j.driver.v1.Value; import org.neo4j.driver.v1.Values; import org.neo4j.driver.v1.util.TestNeo4jSession; import static java.util.Arrays.asList; + import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; + import static org.neo4j.driver.v1.Values.parameters; public class StatementIT @@ -42,22 +45,22 @@ public class StatementIT public void shouldRunWithResult() throws Throwable { // When I execute a statement that yields a result - ReusableResult result = session.run( "UNWIND [1,2,3] AS k RETURN k" ).retain(); + List result = session.run( "UNWIND [1,2,3] AS k RETURN k" ).retain(); // Then the result object should contain the returned values - assertThat( result.size(), equalTo( 3l ) ); + assertThat( result.size(), equalTo( 3 ) ); // And it should allow random access - assertThat( result.get( 0 ).get( "k" ).javaLong(), equalTo( 1l ) ); - assertThat( result.get( 1 ).get( "k" ).javaLong(), equalTo( 2l ) ); - assertThat( result.get( 2 ).get( "k" ).javaLong(), equalTo( 3l ) ); + assertThat( result.get( 0 ).value( "k" ).asLong(), equalTo( 1l ) ); + assertThat( result.get( 1 ).value( "k" ).asLong(), equalTo( 2l ) ); + assertThat( result.get( 2 ).value( "k" ).asLong(), equalTo( 3l ) ); // And it should allow iteration long expected = 0; for ( Record value : result ) { expected += 1; - assertThat( value.get( "k" ), equalTo( Values.value( expected ) ) ); + assertThat( value.value( "k" ), equalTo( Values.value( expected ) ) ); } assertThat( expected, equalTo( 3l ) ); } @@ -84,11 +87,11 @@ public void shouldRun() throws Throwable public void shouldRunParameterizedWithResult() throws Throwable { // When - ReusableResult result = + List result = session.run( "UNWIND {list} AS k RETURN k", parameters( "list", asList( 1, 2, 3 ) ) ).retain(); // Then - assertThat( result.size(), equalTo( 3l ) ); + assertThat( result.size(), equalTo( 3 ) ); } @SuppressWarnings({"StatementWithEmptyBody", "ConstantConditions"}) @@ -105,13 +108,13 @@ public void shouldRunSimpleStatement() throws Throwable // And I run a read statement Result result2 = session.run( "MATCH (a) RETURN a.name" ); - // Then I expect to get the name back + // Then I expect to value the name back Value name = null; while ( result2.next() ) { - name = result2.get( "a.name" ); + name = result2.value( "a.name" ); } - assertThat( name.javaString(), equalTo( "Adam" ) ); + assertThat( name.asString(), equalTo( "Adam" ) ); } } diff --git a/driver/src/test/java/org/neo4j/driver/v1/integration/SummaryIT.java b/driver/src/test/java/org/neo4j/driver/v1/integration/SummaryIT.java index 97808b017f..55d467f093 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/integration/SummaryIT.java +++ b/driver/src/test/java/org/neo4j/driver/v1/integration/SummaryIT.java @@ -18,21 +18,21 @@ */ package org.neo4j.driver.v1.integration; -import org.junit.Rule; -import org.junit.Test; - import java.util.List; import java.util.Map; +import org.junit.Rule; +import org.junit.Test; + import org.neo4j.driver.v1.Notification; import org.neo4j.driver.v1.Plan; import org.neo4j.driver.v1.ProfiledPlan; import org.neo4j.driver.v1.Result; import org.neo4j.driver.v1.ResultSummary; +import org.neo4j.driver.v1.StatementType; import org.neo4j.driver.v1.Value; import org.neo4j.driver.v1.Values; import org.neo4j.driver.v1.util.TestNeo4jSession; -import org.neo4j.driver.v1.StatementType; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; @@ -67,7 +67,7 @@ public void shouldContainBasicMetadata() throws Throwable // Then assertFalse( result.next() ); assertThat( summary.statementType(), equalTo( StatementType.READ_ONLY ) ); - assertThat( summary.statement().text(), equalTo( statementText ) ); + assertThat( summary.statement().template(), equalTo( statementText ) ); assertThat( summary.statement().parameters(), equalTo( statementParameters ) ); assertFalse( summary.hasPlan() ); assertFalse( summary.hasProfile() ); diff --git a/driver/src/test/java/org/neo4j/driver/v1/integration/TransactionIT.java b/driver/src/test/java/org/neo4j/driver/v1/integration/TransactionIT.java index 136c944d93..da2e6a6f2a 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/integration/TransactionIT.java +++ b/driver/src/test/java/org/neo4j/driver/v1/integration/TransactionIT.java @@ -52,7 +52,8 @@ public void shouldRunAndCommit() throws Throwable // Then the outcome of both statements should be visible Result result = session.run( "MATCH (n) RETURN count(n)" ); - long nodes = result.single().get( "count(n)" ).javaLong(); + assertTrue( result.single() ); + long nodes = result.value( "count(n)" ).asLong(); assertThat( nodes, equalTo( 2l ) ); } @@ -67,7 +68,9 @@ public void shouldRunAndRollbackByDefault() throws Throwable } // Then there should be no visible effect of the transaction - long nodes = session.run( "MATCH (n) RETURN count(n)" ).single().get( "count(n)" ).javaLong(); + Result cursor = session.run( "MATCH (n) RETURN count(n)" ); + assertTrue( cursor.single() ); + long nodes = cursor.value( "count(n)" ).asLong(); assertThat( nodes, equalTo( 0l ) ); } @@ -83,7 +86,8 @@ public void shouldRetrieveResults() throws Throwable Result res = tx.run( "MATCH (n) RETURN n.name" ); // Then - assertThat( res.single().get( "n.name" ).javaString(), equalTo( "Steve Brook" ) ); + assertTrue( res.single() ); + assertThat( res.value( "n.name" ).asString(), equalTo( "Steve Brook" ) ); } } diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/value/FloatValueTest.java b/driver/src/test/java/org/neo4j/driver/v1/internal/value/FloatValueTest.java deleted file mode 100644 index 58b4463c33..0000000000 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/value/FloatValueTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright (c) 2002-2015 "Neo Technology," - * Network Engine for Objects in Lund AB [http://neotechnology.com] - * - * This file is part of Neo4j. - * - * Licensed 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.neo4j.driver.v1.internal.value; - -import org.junit.Test; - -import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.types.TypeConstructor; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; - -public class FloatValueTest -{ - - @Test - public void testZeroFloatValue() throws Exception - { - // Given - FloatValue value = new FloatValue( 0 ); - - // Then - assertThat( value.javaBoolean(), equalTo( false ) ); - assertThat( value.javaInteger(), equalTo( 0 ) ); - assertThat( value.javaLong(), equalTo( 0L ) ); - assertThat( value.javaFloat(), equalTo( (float) 0.0 ) ); - assertThat( value.javaDouble(), equalTo( 0.0 ) ); - } - - @Test - public void testNonZeroFloatValue() throws Exception - { - // Given - FloatValue value = new FloatValue( 6.28 ); - - // Then - assertThat( value.javaBoolean(), equalTo( true ) ); - assertThat( value.javaInteger(), equalTo( 6 ) ); - assertThat( value.javaLong(), equalTo( 6L ) ); - assertThat( value.javaFloat(), equalTo( (float) 6.28 ) ); - assertThat( value.javaDouble(), equalTo( 6.28 ) ); - } - - @Test - public void testIsFloat() throws Exception - { - // Given - FloatValue value = new FloatValue( 6.28 ); - - // Then - assertThat( value.isFloat(), equalTo( true ) ); - } - - @Test - public void testEquals() throws Exception - { - // Given - FloatValue firstValue = new FloatValue( 6.28 ); - FloatValue secondValue = new FloatValue( 6.28 ); - - // Then - assertThat( firstValue, equalTo( secondValue ) ); - } - - @Test - public void testHashCode() throws Exception - { - // Given - FloatValue value = new FloatValue( 6.28 ); - - // Then - assertThat( value.hashCode(), notNullValue() ); - } - - @Test - public void shouldNotBeNull() - { - Value value = new FloatValue( 6.28 ); - assertFalse( value.isNull() ); - } - - @Test - public void shouldTypeAsFloat() - { - InternalValue value = new FloatValue( 6.28 ); - assertThat( value.typeConstructor(), equalTo( TypeConstructor.FLOAT_TyCon ) ); - } -} diff --git a/driver/src/test/java/org/neo4j/driver/v1/internal/value/IntegerValueTest.java b/driver/src/test/java/org/neo4j/driver/v1/internal/value/IntegerValueTest.java deleted file mode 100644 index d030d40f0f..0000000000 --- a/driver/src/test/java/org/neo4j/driver/v1/internal/value/IntegerValueTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright (c) 2002-2015 "Neo Technology," - * Network Engine for Objects in Lund AB [http://neotechnology.com] - * - * This file is part of Neo4j. - * - * Licensed 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.neo4j.driver.v1.internal.value; - -import org.junit.Test; - -import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.internal.types.TypeConstructor; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; - -public class IntegerValueTest -{ - - @Test - public void testZeroIntegerValue() throws Exception - { - // Given - IntegerValue value = new IntegerValue( 0 ); - - // Then - assertThat( value.javaBoolean(), equalTo( false ) ); - assertThat( value.javaInteger(), equalTo( 0 ) ); - assertThat( value.javaLong(), equalTo( 0L ) ); - assertThat( value.javaFloat(), equalTo( (float) 0.0 ) ); - assertThat( value.javaDouble(), equalTo( 0.0 ) ); - } - - @Test - public void testNonZeroIntegerValue() throws Exception - { - // Given - IntegerValue value = new IntegerValue( 1 ); - - // Then - assertThat( value.javaBoolean(), equalTo( true ) ); - assertThat( value.javaInteger(), equalTo( 1 ) ); - assertThat( value.javaLong(), equalTo( 1L ) ); - assertThat( value.javaFloat(), equalTo( (float) 1.0 ) ); - assertThat( value.javaDouble(), equalTo( 1.0 ) ); - } - - @Test - public void testIsInteger() throws Exception - { - // Given - IntegerValue value = new IntegerValue( 1L ); - - // Then - assertThat( value.isInteger(), equalTo( true ) ); - } - - @Test - public void testEquals() throws Exception - { - // Given - IntegerValue firstValue = new IntegerValue( 1 ); - IntegerValue secondValue = new IntegerValue( 1 ); - - // Then - assertThat( firstValue, equalTo( secondValue ) ); - } - - @Test - public void testHashCode() throws Exception - { - // Given - IntegerValue value = new IntegerValue( 1L ); - - // Then - assertThat( value.hashCode(), notNullValue() ); - } - - @Test - public void shouldNotBeNull() - { - Value value = new IntegerValue( 1L ); - assertFalse( value.isNull() ); - } - - @Test - public void shouldTypeAsInteger() - { - InternalValue value = new IntegerValue( 1L ); - assertThat( value.typeConstructor(), equalTo( TypeConstructor.INTEGER_TyCon ) ); - } -} diff --git a/driver/src/test/java/org/neo4j/driver/v1/stress/DriverStresser.java b/driver/src/test/java/org/neo4j/driver/v1/stress/DriverStresser.java index 4b20a45cc3..6dc94b3d24 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/stress/DriverStresser.java +++ b/driver/src/test/java/org/neo4j/driver/v1/stress/DriverStresser.java @@ -27,8 +27,8 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; -import org.neo4j.driver.v1.GraphDatabase; import org.neo4j.driver.v1.Driver; +import org.neo4j.driver.v1.GraphDatabase; import org.neo4j.driver.v1.Result; import org.neo4j.driver.v1.Session; import org.neo4j.driver.v1.Value; @@ -79,7 +79,7 @@ public int operation() Result result = session.run( statement, parameters ); while ( result.next() ) { - total += result.get( "n" ).javaInteger(); + total += result.value( "n" ).asInt(); } return total; } diff --git a/driver/src/test/java/org/neo4j/driver/v1/util/BytePrinterTest.java b/driver/src/test/java/org/neo4j/driver/v1/util/BytePrinterTest.java index 3c8f02917f..195abdff8c 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/util/BytePrinterTest.java +++ b/driver/src/test/java/org/neo4j/driver/v1/util/BytePrinterTest.java @@ -18,15 +18,15 @@ */ package org.neo4j.driver.v1.util; -import org.junit.Assert; -import org.junit.Test; - import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; -import org.neo4j.driver.v1.internal.util.BytePrinter; +import org.junit.Assert; +import org.junit.Test; + +import org.neo4j.driver.internal.util.BytePrinter; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; diff --git a/driver/src/test/java/org/neo4j/driver/v1/util/CertificateToolTest.java b/driver/src/test/java/org/neo4j/driver/v1/util/CertificateToolTest.java index 7f43a06512..413aac802a 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/util/CertificateToolTest.java +++ b/driver/src/test/java/org/neo4j/driver/v1/util/CertificateToolTest.java @@ -18,6 +18,20 @@ */ package org.neo4j.driver.v1.util; +import java.io.File; +import java.io.IOException; +import java.math.BigInteger; +import java.security.GeneralSecurityException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.Security; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Date; +import java.util.Enumeration; + import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; @@ -34,25 +48,12 @@ import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder; import org.junit.Test; -import java.io.File; -import java.io.IOException; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.Security; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.util.Date; -import java.util.Enumeration; - -import org.neo4j.driver.v1.internal.util.CertificateTool; +import org.neo4j.driver.internal.util.CertificateTool; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.neo4j.driver.v1.internal.util.CertificateTool.saveX509Cert; + +import static org.neo4j.driver.internal.util.CertificateTool.saveX509Cert; public class CertificateToolTest { @@ -65,7 +66,7 @@ public class CertificateToolTest /** * Create a random certificate * - * @return + * @return a random certificate * @throws GeneralSecurityException, IOException, OperatorCreationException */ public static X509Certificate generateSelfSignedCertificate() diff --git a/driver/src/test/java/org/neo4j/driver/v1/util/DumpMessage.java b/driver/src/test/java/org/neo4j/driver/v1/util/DumpMessage.java index 7abcb9a474..a8dc20a18e 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/util/DumpMessage.java +++ b/driver/src/test/java/org/neo4j/driver/v1/util/DumpMessage.java @@ -27,24 +27,23 @@ import java.util.List; import java.util.Map; +import org.neo4j.driver.internal.connector.socket.ChunkedInput; +import org.neo4j.driver.internal.messaging.AckFailureMessage; +import org.neo4j.driver.internal.messaging.DiscardAllMessage; +import org.neo4j.driver.internal.messaging.FailureMessage; +import org.neo4j.driver.internal.messaging.IgnoredMessage; +import org.neo4j.driver.internal.messaging.InitMessage; +import org.neo4j.driver.internal.messaging.Message; +import org.neo4j.driver.internal.messaging.MessageFormat; +import org.neo4j.driver.internal.messaging.MessageHandler; +import org.neo4j.driver.internal.messaging.PackStreamMessageFormatV1; +import org.neo4j.driver.internal.messaging.PullAllMessage; +import org.neo4j.driver.internal.messaging.RecordMessage; +import org.neo4j.driver.internal.messaging.RunMessage; +import org.neo4j.driver.internal.messaging.SuccessMessage; +import org.neo4j.driver.internal.packstream.PackInput; +import org.neo4j.driver.internal.util.BytePrinter; import org.neo4j.driver.v1.Value; -import org.neo4j.driver.v1.exceptions.Neo4jException; -import org.neo4j.driver.v1.internal.connector.socket.ChunkedInput; -import org.neo4j.driver.v1.internal.messaging.AckFailureMessage; -import org.neo4j.driver.v1.internal.messaging.DiscardAllMessage; -import org.neo4j.driver.v1.internal.messaging.FailureMessage; -import org.neo4j.driver.v1.internal.messaging.IgnoredMessage; -import org.neo4j.driver.v1.internal.messaging.InitMessage; -import org.neo4j.driver.v1.internal.messaging.Message; -import org.neo4j.driver.v1.internal.messaging.MessageFormat; -import org.neo4j.driver.v1.internal.messaging.MessageHandler; -import org.neo4j.driver.v1.internal.messaging.PackStreamMessageFormatV1; -import org.neo4j.driver.v1.internal.messaging.PullAllMessage; -import org.neo4j.driver.v1.internal.messaging.RecordMessage; -import org.neo4j.driver.v1.internal.messaging.RunMessage; -import org.neo4j.driver.v1.internal.messaging.SuccessMessage; -import org.neo4j.driver.v1.internal.packstream.PackInput; -import org.neo4j.driver.v1.internal.util.BytePrinter; public class DumpMessage { @@ -58,15 +57,15 @@ public static void main( String[] args ) return; } StringBuilder hexStr = new StringBuilder(); - for( int i = 0; i < args.length; i ++ ) + for ( String arg : args ) { - hexStr.append( args[i] ); + hexStr.append( arg ); } byte[] bytes = BytePrinter.hexStringToBytes( hexStr.toString() ); // for now we only handle PackStreamV1 - ArrayList messages = null; + ArrayList messages; try { // first try to interpret as a message with chunk header and 00 00 ending @@ -166,28 +165,18 @@ private static byte[] putBytesInOneChunk( byte[] bytes ) byte[] bytesWithHeadAndTail = new byte[bytes.length + 2 + 2]; // 2 for head and 2 for tail bytesWithHeadAndTail[0] = (byte) (bytes.length >>> 8); bytesWithHeadAndTail[1] = (byte) bytes.length; - for ( int i = 0; i < bytes.length; i++ ) - { - bytesWithHeadAndTail[i + 2] = bytes[i]; - } + System.arraycopy( bytes, 0, bytesWithHeadAndTail, 2, bytes.length ); return bytesWithHeadAndTail; } public static List unpack( List outcome, MessageFormat.Reader reader ) throws IOException { - try - { - do - { - reader.read( new MessageRecordedMessageHandler( outcome ) ); - } - while ( reader.hasNext() ); - } - catch ( Neo4jException e ) + do { - throw e; + reader.read( new MessageRecordedMessageHandler( outcome ) ); } + while ( reader.hasNext() ); return outcome; } diff --git a/driver/src/test/java/org/neo4j/driver/v1/util/Neo4jRunner.java b/driver/src/test/java/org/neo4j/driver/v1/util/Neo4jRunner.java index 968119f63f..d8422f439e 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/util/Neo4jRunner.java +++ b/driver/src/test/java/org/neo4j/driver/v1/util/Neo4jRunner.java @@ -23,15 +23,17 @@ import java.net.URI; import java.util.Map; +import org.neo4j.driver.internal.connector.socket.SocketClient; +import org.neo4j.driver.internal.logging.DevNullLogger; import org.neo4j.driver.v1.Config; import org.neo4j.driver.v1.Driver; import org.neo4j.driver.v1.exceptions.ClientException; -import org.neo4j.driver.v1.internal.connector.socket.SocketClient; -import org.neo4j.driver.v1.internal.logging.DevNullLogger; import static java.lang.String.format; + import static junit.framework.TestCase.assertFalse; -import static org.neo4j.driver.v1.internal.ConfigTest.deleteDefaultKnownCertFileIfExists; + +import static org.neo4j.driver.internal.ConfigTest.deleteDefaultKnownCertFileIfExists; import static org.neo4j.driver.v1.util.FileTools.deleteRecursively; import static org.neo4j.driver.v1.util.FileTools.updateProperties; diff --git a/driver/src/test/java/org/neo4j/driver/v1/util/TestNeo4j.java b/driver/src/test/java/org/neo4j/driver/v1/util/TestNeo4j.java index 9fcc532243..8321967b05 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/util/TestNeo4j.java +++ b/driver/src/test/java/org/neo4j/driver/v1/util/TestNeo4j.java @@ -18,15 +18,15 @@ */ package org.neo4j.driver.v1.util; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runners.model.Statement; + import org.neo4j.driver.v1.Driver; import org.neo4j.driver.v1.Result; import org.neo4j.driver.v1.Session; diff --git a/driver/src/test/java/org/neo4j/driver/v1/util/TestNeo4jSession.java b/driver/src/test/java/org/neo4j/driver/v1/util/TestNeo4jSession.java index f0f64f22d8..907cafafcd 100644 --- a/driver/src/test/java/org/neo4j/driver/v1/util/TestNeo4jSession.java +++ b/driver/src/test/java/org/neo4j/driver/v1/util/TestNeo4jSession.java @@ -26,6 +26,7 @@ import org.neo4j.driver.v1.Result; import org.neo4j.driver.v1.Session; import org.neo4j.driver.v1.Transaction; +import org.neo4j.driver.v1.TypeSystem; import org.neo4j.driver.v1.Value; /** @@ -99,20 +100,26 @@ public Transaction beginTransaction() } @Override - public Result run( String statementText, Map parameters ) + public Result run( String statementText, Map statementParameters ) { - return realSession.run( statementText, parameters ); + return realSession.run( statementText, statementParameters ); } @Override - public Result run( String statementText ) + public Result run( String statementTemplate ) { - return realSession.run( statementText ); + return realSession.run( statementTemplate ); } @Override public Result run( org.neo4j.driver.v1.Statement statement ) { - return realSession.run( statement.text(), statement.parameters() ); + return realSession.run( statement.template(), statement.parameters() ); + } + + @Override + public TypeSystem typeSystem() + { + return realSession.typeSystem(); } }